[文章]HarmonyOS实战—实现长按事件

阅读量0
0
0
1. 长按事件
  • 长按事件使用的次数不是很多,但在有些特殊的情况下还是要用到的。
  • 比如:复制一段文字的时候就是长按操作
  • 长按事件和单、双击事件也非常类似
  • 接口名:LongClickedListener


2. 实现案例:长按按钮修改文本内容
  • 新建项目:ListenerApplication3
ability_main
  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="100">

  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>
  24. MainAbilitySlice
  25. package com.xdr630.listenerapplication3.slice;

  26. import com.xdr630.listenerapplication3.ResourceTable;
  27. import ohos.aafwk.ability.AbilitySlice;
  28. import ohos.aafwk.content.Intent;
  29. import ohos.agp.components.Button;
  30. import ohos.agp.components.Component;
  31. import ohos.agp.components.Text;

  32. public class MainAbilitySlice extends AbilitySlice implements Component.LongClickedListener {
  33.     //提为成员变量,否则onLongClicked访问不到文本组件,并初始化默认值
  34.     Text text1 = null;

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

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

  42.         //2.绑定长按事件,点谁就给谁绑定事件
  43.         //当对按钮进行长按操作时,就会执行this本类中onLongClicked方法
  44.         but1.setLongClickedListener(this);
  45.     }

  46.     @Override
  47.     public void onActive() {
  48.         super.onActive();
  49.     }

  50.     @Override
  51.     public void onForeground(Intent intent) {
  52.         super.onForeground(intent);
  53.     }

  54.     @Override
  55.     public void onLongClicked(Component component) {
  56.         //修改文本框的内容
  57.         text1.setText("长按");
  58.     }
  59. }
复制代码

回帖

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