天天看點

HarmonyOS實戰—實作輕按兩下事件1. 輕按兩下事件2. 實作案例

1. 輕按兩下事件

輕按兩下事件和單擊事件有些類似,也有四種實作的方法

1.通過

id

找到元件。

2.給按鈕元件設定輕按兩下事件。

3.本類實作

DoubleClickedListener

接口重寫。

4.重寫

onDoubleClick

方法

2. 實作案例

  • 當滑鼠輕按兩下按鈕後,Text文本内容就會發生變化
HarmonyOS實戰—實作輕按兩下事件1. 輕按兩下事件2. 實作案例
HarmonyOS實戰—實作輕按兩下事件1. 輕按兩下事件2. 實作案例
  • 建立項目 ListenerApplication2
HarmonyOS實戰—實作輕按兩下事件1. 輕按兩下事件2. 實作案例
  • 采用 目前類實作作為實作類 的方式來實作
  • 代碼實作:

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">

    <Text
        ohos:id="$+id:text1"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="text"
        ohos:text_size="50">
    </Text>

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

</DirectionalLayout>           

MainAbilitySlice

package com.xdr630.listenerapplication2.slice;

import com.xdr630.listenerapplication2.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;

public class MainAbilitySlice extends AbilitySlice implements Component.DoubleClickedListener {
    //把text1提為成員變量,不然onDoubleClick方法就通路不到
    //初始化預設值
    Text text1 = null;

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

        // 1.找到文本框元件和按鈕元件
        text1 = (Text) findComponentById(ResourceTable.Id_text1);
        Button but1 = (Button) findComponentById(ResourceTable.Id_but1);

        // 2.綁定事件(想到點誰,就給誰綁定事件)
        // 當輕按兩下了but1按鈕之後,就會執行本類中的 onDoubleClick 方法
        but1.setDoubleClickedListener(this);
    }

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

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

    @Override
    public void onDoubleClick(Component component) {
        //Component表示點選元件的對象
        //簡單了解:我點了誰,那麼 Component 就表示誰的對象
        //這裡Component表示的是按鈕對象

        //點選之後要做的是改變文本框中的内容
        text1.setText("輕按兩下");
    }
}           
  • 運作:
HarmonyOS實戰—實作輕按兩下事件1. 輕按兩下事件2. 實作案例
  • 輕按兩下後:
HarmonyOS實戰—實作輕按兩下事件1. 輕按兩下事件2. 實作案例

繼續閱讀