天天看點

HarmonyOS實戰—實作單擊事件流程1. 什麼是事件?2. 單擊事件(常用)3. 實作步驟4. 單擊事件小節

1. 什麼是事件?

  • 事件就是可以被識别的操作 。就是可以被文本、按鈕、圖檔等元件識别的操作。
  • 常見的事件有:單擊、輕按兩下、長按、還有觸摸事件 。
  • 可以給文本、按鈕等添加不同的事件。比如添加了單擊事件之後,當我們再次點選文本、按鈕,就可以運作對應的代碼了。
  • 常見的事件有:
HarmonyOS實戰—實作單擊事件流程1. 什麼是事件?2. 單擊事件(常用)3. 實作步驟4. 單擊事件小節

2. 單擊事件(常用)

  • 單擊事件:又叫做點選事件。是開發中使用最多的一種事件,沒有之一。
  • 接口名:ClickedListener,又叫:點選事件。
  • 如:當點選後,文字内容就會發送變化
HarmonyOS實戰—實作單擊事件流程1. 什麼是事件?2. 單擊事件(常用)3. 實作步驟4. 單擊事件小節
HarmonyOS實戰—實作單擊事件流程1. 什麼是事件?2. 單擊事件(常用)3. 實作步驟4. 單擊事件小節

3. 實作步驟

  • 建立項目名為:

    ListenerApplication

HarmonyOS實戰—實作單擊事件流程1. 什麼是事件?2. 單擊事件(常用)3. 實作步驟4. 單擊事件小節

ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:orientation="vertical">

    <Button
        ohos:id="$+id:but1"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="點我"
        ohos:text_size="200"
        ohos:background_element="red">
    </Button>

</DirectionalLayout>           

MainAbilitySlice

package com.example.listenerapplication.slice;

import com.example.listenerapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;

public class MainAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        //1.找到按鈕
        //完整寫法:this.findComponentById(ResourceTable.Id_but1);
        //this:本類的對象,指:MainAbilitySlice(子界面對象)
        // 在子界面當中,通過 id 找到對應的元件
        // 用this去調用方法,this可以省略不寫
        //findComponentById(ResourceTable.Id_but1);
        //傳回一個元件對象(是以元件的父類對象)
        //那麼我們在實際寫代碼的時候,需要向下轉型:強轉
        Component but1 = (Button) findComponentById(ResourceTable.Id_but1);

        //2.給按鈕綁定單擊事件,當點選後,就會執行 MyListener 中的方法,點一次執行一次
        // 而方法就是下面點選的内容
        but1.setClickedListener(new MyListener());

    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}

class MyListener implements Component.ClickedListener{

    @Override
    public void onClick(Component component) {
        //Component:所有元件的父類
        //component參數: 被點選的元件對象,在這裡就表示按你的對象
        //component.setText(); setText是子類特有的方法,需要向下轉型:強轉
        Button but = (Button) component;
        but.setText("被點了");
    }
}           
  • 運作:
HarmonyOS實戰—實作單擊事件流程1. 什麼是事件?2. 單擊事件(常用)3. 實作步驟4. 單擊事件小節
  • 點選後:
HarmonyOS實戰—實作單擊事件流程1. 什麼是事件?2. 單擊事件(常用)3. 實作步驟4. 單擊事件小節

4. 單擊事件小節

  • 實作步驟:

1.通過

id

找到元件。

2.給按鈕元件設定單擊事件。

3.寫一個類實作

ClickedListener

接口并重寫

onClick

方法。

4.編寫

onClick

方法體。

繼續閱讀