HarmonyOS 鸿蒙Next中在button按钮上识别双击

HarmonyOS 鸿蒙Next中在button按钮上识别双击

onclick、ontouch无法实现,使用TapGesture实现

https://developer.huawei.com/consumer/cn/doc/harmonyos-references/ts-basic-gestures-tapgesture

2 回复

在HarmonyOS鸿蒙Next中,可以通过Gesture模块实现Button按钮的双击识别。使用GestureTapGesture监听点击事件,设置count为2来识别双击。示例代码如下:

import { Button, Gesture, TapGesture } from '@ohos.arkui';

let button = new Button();
let tapGesture = new TapGesture({ count: 2 });

tapGesture.onAction(() => {
  console.log("Double Tap Detected");
});

button.addGesture(tapGesture);

此代码会在Button上检测到双击时输出日志。

更多关于HarmonyOS 鸿蒙Next中在button按钮上识别双击的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,使用TapGesture识别按钮双击的正确实现方式如下:

  1. 基本实现代码:
Button()
  .gesture(
    TapGesture()
      .onAction((event: GestureEvent) => {
        if (event.count === 2) {
          // 双击处理逻辑
          console.log('双击事件触发');
        }
      })
  )
  1. 关键点说明:
  • TapGesture的onAction回调会返回GestureEvent对象
  • 通过event.count属性可以获取点击次数
  • count值为2时表示双击事件
  1. 注意事项:
  • 不需要单独处理单击事件,系统会自动区分
  • 默认双击识别时间间隔为300ms,符合常规交互标准
  • 若需要调整识别间隔,可使用TapGesture的setCount方法

这种实现方式比传统onclick更精准,能正确区分单双击事件。

回到顶部