• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 自定义事件拦截
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @jiangtao92-->
5<!--Designer: @piggyguy-->
6<!--Tester: @songyanhong-->
7<!--Adviser: @HelloCrease-->
8
9为组件提供自定义的事件拦截能力,开发者可根据事件在控件上按下时的位置,输入源等事件信息决定控件上的HitTestMode属性。
10
11>  **说明:**
12>
13>  从API version 12开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
14
15
16## onTouchIntercept
17
18onTouchIntercept(callback: Callback<TouchEvent, HitTestMode>): T
19
20给组件绑定自定义事件拦截回调。
21
22**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
23
24**系统能力:** SystemCapability.ArkUI.ArkUI.Full
25
26**参数:**
27
28| 参数名        | 类型                    | 必填  | 说明                         |
29| ---------- | -------------------------- | ------- | ----------------------------- |
30| callback      | Callback<[TouchEvent](ts-universal-events-touch.md#touchevent对象说明), [HitTestMode](ts-appendix-enums.md#hittestmode9)> | 是     |  自定义事件拦截回调。在做[触摸测试](../../../ui/arkts-interaction-basic-principles.md#触摸测试)时回调此函数。通过返回值设置组件的[触摸碰撞测试模式](ts-universal-attributes-hit-test-behavior.md)。 |
31
32**返回值:**
33
34| 类型 | 说明 |
35| -------- | -------- |
36| T | 返回当前组件。 |
37
38## 示例
39
40该示例通过onTouchIntercept修改组件的HitTestMode属性。
41
42```ts
43// xxx.ets
44@Entry
45@Component
46struct Index {
47  isPolygon(event: TouchEvent) {
48    return true;
49  }
50
51  build() {
52    Row() {
53      Column() {
54        Text("hello world")
55          .backgroundColor(Color.Blue)
56          .fontSize(50)
57          .fontWeight(FontWeight.Bold)
58          .onClick(() => {
59            console.info("Text click");
60          })
61      }
62      .width(400)
63      .height(300)
64      .backgroundColor(Color.Pink)
65      .onClick(() => {
66        console.info("Column click");
67      })
68      // 调用onTouchIntercept修改该组件的HitTestMode属性
69      .onTouchIntercept((event: TouchEvent) => {
70        console.info("OnTouchIntercept + " + JSON.stringify(event));
71        // 使用touches时需要先校验是否为空
72        if (event && event.touches) {
73          let touches = event.touches;
74          for(let i = 0; touches[i] != null; i++) {
75            console.info('onTouchIntercept touches:', JSON.stringify(touches[i]));
76          }
77        }
78        if (this.isPolygon(event)) {
79          return HitTestMode.None;
80        }
81        return HitTestMode.Default;
82      })
83    }
84    .width('100%')
85  }
86}
87```
88