> 文档中心 > 【HarmonyOS】JavaUI组件触摸事件分发

【HarmonyOS】JavaUI组件触摸事件分发

熟悉Android开发的同学肯定对触摸事件分发比较了解,那么在HarmonyOS开发应用需要对触摸事件处理该怎么做呢,下面结合一个实际的案例来讲解一下。

【需求】

封装一个自定义组件CustomView,在组件上有个按钮Button可以响应点击事件,需要在点击按钮的时候只触发按钮的onClick事件不触发父组件的onTouch事件:

cke_264.png

伪代码如下:

public class CustomView extends ComponentContainer implements Component.TouchEventListener {    static final HiLogLabel LABEL_CUSTOMEVIEW = new HiLogLabel(HiLog.LOG_APP, 0x00201, "CUSTOMEVIEW");    public CustomView(Context context) { super(context); init(context);    }    public CustomView(Context context, AttrSet attrSet) { super(context, attrSet); init(context);    }    public CustomView(Context context, AttrSet attrSet, String styleName) { super(context, attrSet, styleName); init(context);    }    private final void init(Context context) { this.setTouchEventListener(this); LayoutConfig layoutConfig = new LayoutConfig(LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_PARENT); Button button = new Button(context); button.setText("Button"); button.setTextSize(48); this.addComponent(button,layoutConfig); button.setClickedListener(new Component.ClickedListener() {     @Override     public void onClick(Component component) {  HiLog.info(LABEL_CUSTOMEVIEW,"button onClick");     } });    }    @Override    public boolean onTouchEvent(Component component, TouchEvent touchEvent) { HiLog.info(LABEL_CUSTOMEVIEW,"componentContainer onTouchEvent"); return false;    }    }

实际效果是在点击Button的时候会先触发父组件的onTouchEvent 然后再触发Button的onClick事件:

cke_1536.png

思路

在Android开发中触摸事件从父组件向子组件分发,父组件可以对分发操作做拦截;子组件在onTouchEvent中消费触摸事件,并可以控制是否向父组件传递。

【实现】

根据这个思路,我们只需要控制Button的onTouch事件不向父组件传递即可。但HarmonyOS系统中有个区别于Android系统的地方:在Android中我们可以设置Button的Clickable属性为true,从而控制Button不向父组件传递TouchEvent,但是这个方法在HarmonyOS中无效。所以我们需要给Button添加onTouchEvent的回调,并控制返回值为true,消费掉Touch事件并不向父组件传递(API地址:Component.TouchEventListener-Interface-ohos.agp.components-Java API参考-HarmonyOS应用开发)

伪代码如下:

 button.setTouchEventListener(new Component.TouchEventListener() {     @Override     public boolean onTouchEvent(Component component, TouchEvent touchEvent) {  return true;     } });

效果如下:

cke_4406.png

【总结】

HarmonyOS中触摸事件分发和消费的思路基本与Android一致,只是个别API实现不同,只要掌握了思路对于同类型的问题都可以解决。

 欲了解更多更全技术文章,欢迎访问https://developer.huawei.com/consumer/cn/forum/?ha_source=zzh