[文章]#HarmonyOS征文#—HarmonyOS实现双击事件

阅读量0
0
1
1. 双击事件
双击事件和单击事件有些类似,也有四种实现的方法
1.通过id找到组件。
2.给按钮组件设置双击事件。
3.本类实现DoubleClickedListener接口重写。
4.重写onDoubleClick方法
2. 实现案例
  • 当鼠标双击按钮后,Text文本内容就会发生变化
  • 新建项目 ListenerApplication2
  • 采用 当前类实现作为实现类 的方式来实现
  • 代码实现:
ability_main.xml
    1. <?xml version="1.0" encoding="utf-8"?>
    2. <DirectionalLayout
    3.     xmlns:ohos="http://schemas.huawei.com/res/ohos"
    4.     ohos:height="match_parent"
    5.     ohos:width="match_parent"
    6.     ohos:alignment="center"
    7.     ohos:orientation="vertical">

    8.     <Text
    9.         ohos:id="$+id:text1"
    10.         ohos:height="match_content"
    11.         ohos:width="match_content"
    12.         ohos:text="text"
    13.         ohos:text_size="50">
    14.     </Text>

    15.     <Button
    16.         ohos:id="$+id:but1"
    17.         ohos:height="match_content"
    18.         ohos:width="match_content"
    19.         ohos:text="点我"
    20.         ohos:text_size="100"
    21.         ohos:background_element="red">
    22.     </Button>

    23. </DirectionalLayout>
    复制代码

MainAbilitySlice
    1. package com.xdr630.listenerapplication2.slice;

    2. import com.xdr630.listenerapplication2.ResourceTable;
    3. import ohos.aafwk.ability.AbilitySlice;
    4. import ohos.aafwk.content.Intent;
    5. import ohos.agp.components.Button;
    6. import ohos.agp.components.Component;
    7. import ohos.agp.components.Text;

    8. public class MainAbilitySlice extends AbilitySlice implements Component.DoubleClickedListener {
    9.     //把text1提为成员变量,不然onDoubleClick方法就访问不到
    10.     //初始化默认值
    11.     Text text1 = null;

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

    16.         // 1.找到文本框组件和按钮组件
    17.         text1 = (Text) findComponentById(ResourceTable.Id_text1);
    18.         Button but1 = (Button) findComponentById(ResourceTable.Id_but1);

    19.         // 2.绑定事件(想到点谁,就给谁绑定事件)
    20.         // 当双击了but1按钮之后,就会执行本类中的 onDoubleClick 方法
    21.         but1.setDoubleClickedListener(this);
    22.     }

    23.     @Override
    24.     public void onActive() {
    25.         super.onActive();
    26.     }

    27.     @Override
    28.     public void onForeground(Intent intent) {
    29.         super.onForeground(intent);
    30.     }

    31.     @Override
    32.     public void onDoubleClick(Component component) {
    33.         //Component表示点击组件的对象
    34.         //简单理解:我点了谁,那么 Component 就表示谁的对象
    35.         //这里Component表示的是按钮对象

    36.         //点击之后要做的是改变文本框中的内容
    37.         text1.setText("双击");
    38.     }
    39. }
    复制代码

  • 运行:
  • 双击后:

回帖

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容图片侵权或者其他问题,请联系本站作侵删。 侵权投诉
链接复制成功,分享给好友