ts-universal-attributes-component-id.md 9.3 KB
Newer Older
Z
zengyawen 已提交
1 2
# 组件标识

3 4
id为组件的唯一标识,在整个应用内唯一。本模块提供组件标识相关接口,可以获取指定id组件的属性,也提供向指定id组件发送事件的功能。

H
geshi  
HelloCrease 已提交
5
>  **说明:**
H
hebingxue 已提交
6
>
Z
zengyawen 已提交
7 8 9 10 11
> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。


## 属性

H
hebingxue 已提交
12 13
| 名称   | 参数说明     | 描述                         |
| -----| -------- | ----------------------------- |
14
| id   | string   | 组件的唯一标识,唯一性由使用者保证。<br>默认值:''<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
Z
zengyawen 已提交
15 16 17 18 19


## 接口


Z
zcdqs 已提交
20
### getInspectorByKey<sup>9+</sup>
Z
zengyawen 已提交
21 22 23 24 25

getInspectorByKey(id: string): string

获取指定id的组件的所有属性,不包括子组件信息。

26 27
此接口仅用于对应用的测试。

H
hebingxue 已提交
28 29 30 31 32
**参数:**

| 参数   | 类型      | 必填     | 描述        |
| ---- | -------- | ---- | -------------|
| id   | string   | 是    | 要获取属性的组件id。 |
Z
zengyawen 已提交
33

H
hebingxue 已提交
34 35 36 37 38
**返回值:**

| 类型        | 描述             |
| -------| -------------- |
| string | 组件属性列表的JSON字符串。 |
Z
zengyawen 已提交
39

Z
zcdqs 已提交
40
### getInspectorTree<sup>9+</sup>
41

42
getInspectorTree(): Object
43 44 45

获取组件树及组件属性。

46 47
此接口仅用于对应用的测试。

H
hebingxue 已提交
48
**返回值:**
49

H
hebingxue 已提交
50 51
| 类型     | 描述                            |
| ------ | --------------------------- |
52
| Object | 组件树及组件属性列表的JSON对象。 |
Z
zengyawen 已提交
53

Z
zcdqs 已提交
54
### sendEventByKey<sup>9+</sup>
Z
zengyawen 已提交
55 56 57 58 59

sendEventByKey(id: string, action: number, params: string): boolean

给指定id的组件发送事件。

60 61
此接口仅用于对应用的测试。

H
hebingxue 已提交
62 63 64 65 66 67 68 69 70
**参数:**

| 参数       | 类型      | 必填       | 描述                         |
| ------ | -------| ---- | -------------------------- |
| id     | string | 是    | 要触发事件的组件的id。                      |
| action | number | 是    | 要触发的事件类型,目前支持取值:<br/>-&nbsp;点击事件Click:&nbsp;10<br/>-&nbsp;长按事件LongClick:&nbsp;11。 |
| params | string | 是    | 事件参数,无参数传空字符串&nbsp;""。            |

**返回值:**
Z
zengyawen 已提交
71

H
hebingxue 已提交
72 73 74
| 类型          | 描述                         |
| -------- | --------------------------|
| boolean  | 找不到指定id的组件时返回false,其余情况返回true。 |
Z
zengyawen 已提交
75

Z
zcdqs 已提交
76
### sendTouchEvent<sup>9+</sup>
77 78 79 80 81

sendTouchEvent(event: TouchObject): boolean

发送触摸事件。

82 83
此接口仅用于对应用的测试。

H
hebingxue 已提交
84
**参数:**
85

H
hebingxue 已提交
86 87
| 参数      | 类型            | 必填  | 描述                                                         |
| ----- | ----------- | ---- | ------------------------------------------------------------ |
M
match 已提交
88
| event | [TouchObject](ts-universal-events-touch.md#touchobject对象说明) | 是    | 触发触摸事件的位置,event参数见[TouchEvent](ts-universal-events-touch.md#touchevent对象说明)中TouchObject的介绍。 |
89

H
hebingxue 已提交
90
**返回值:**
91

H
hebingxue 已提交
92 93 94
| 类型      | 描述                         |
| ------- | ---------------------------|
| boolean | 事件发送失败时返回false,其余情况返回true。 |
95

Z
zcdqs 已提交
96
### sendKeyEvent<sup>9+</sup>
97 98 99 100 101

sendKeyEvent(event: KeyEvent): boolean

发送按键事件。

102 103
此接口仅用于对应用的测试。

H
hebingxue 已提交
104
**参数:**
105

H
hebingxue 已提交
106 107
| 参数    | 类型     | 必填      | 描述                                                         |
| ----- | -------- | ----  | ------------------------------------------------------------ |
M
match 已提交
108
| event | [KeyEvent](ts-universal-events-key.md#keyevent对象说明) | 是     | 按键事件,event参数见[KeyEvent](ts-universal-events-key.md#keyevent对象说明)介绍。 |
109

H
hebingxue 已提交
110
**返回值:**
111

H
hebingxue 已提交
112 113 114
| 类型      | 描述                           |
| ------- | ------------------------------|
| boolean | 事件发送失败时时返回false,其余情况返回true。 |
115

Z
zcdqs 已提交
116
### sendMouseEvent<sup>9+</sup>
117 118 119 120 121

sendMouseEvent(event: MouseEvent): boolean

发送鼠标事件。

122 123
此接口仅用于对应用的测试。

H
hebingxue 已提交
124
**参数:**
125

H
hebingxue 已提交
126 127
| 参数     | 类型       | 必填       | 描述                                     |
| ----- | ---------- | ----  | --------------------------------------- |
M
match 已提交
128
| event | [MouseEvent](ts-universal-mouse-key.md#mouseevent对象说明) | 是    | 鼠标事件,event参数见[MouseEvent](ts-universal-mouse-key.md#mouseevent对象说明)介绍。 |
129

H
hebingxue 已提交
130
**返回值:**
131

H
hebingxue 已提交
132 133 134
| 类型      | 描述                                 |
| ------- | ---------------------------------- |
| boolean | 事件发送失败时返回false,其余情况返回true。 |
Z
zengyawen 已提交
135 136 137

## 示例

H
geshi  
HelloCrease 已提交
138 139
```ts
// xxx.ets
140
class Utils {
M
matchzhou 已提交
141 142 143 144 145
  static rect_left
  static rect_top
  static rect_right
  static rect_bottom
  static rect_value
146

M
match 已提交
147
  //获取组件所占矩形区域坐标
148
  static getComponentRect(key) {
M
matchzhou 已提交
149 150 151
    let strJson = getInspectorByKey(key)
    let obj = JSON.parse(strJson)
    console.info("[getInspectorByKey] current component obj is: " + JSON.stringify(obj))
152
    let rectInfo = JSON.parse('[' + obj.$rect + ']')
M
matchzhou 已提交
153
    console.info("[getInspectorByKey] rectInfo is: " + rectInfo)
154 155 156 157 158 159 160 161 162 163
    this.rect_left = JSON.parse('[' + rectInfo[0] + ']')[0]
    this.rect_top = JSON.parse('[' + rectInfo[0] + ']')[1]
    this.rect_right = JSON.parse('[' + rectInfo[1] + ']')[0]
    this.rect_bottom = JSON.parse('[' + rectInfo[1] + ']')[1]
    return this.rect_value = {
      "left": this.rect_left, "top": this.rect_top, "right": this.rect_right, "bottom": this.rect_bottom
    }
  }
}

Z
zengyawen 已提交
164 165 166
@Entry
@Component
struct IdExample {
167 168
  @State text: string = ''

Z
zengyawen 已提交
169 170
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
171

Z
zengyawen 已提交
172
      Button() {
173 174 175 176 177 178 179 180 181 182
        Text('onKeyTab').fontSize(25).fontWeight(FontWeight.Bold)
      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
      .onKeyEvent(() => {
        this.text = "onKeyTab"
      })

      Button() {
        Text('click to start').fontSize(25).fontWeight(FontWeight.Bold)
      }.margin({ top: 20 })
      .onClick(() => {
Z
zengyawen 已提交
183
        console.info(getInspectorByKey("click"))
184
        console.info(JSON.stringify(getInspectorTree()))
185
        this.text = "Button 'click to start' is clicked"
Z
zengyawen 已提交
186
        setTimeout(() => {
M
match 已提交
187
          sendEventByKey("longClick", 11, "") // 向id为"longClick"的组件发送长按事件
Z
zengyawen 已提交
188 189 190 191
        }, 2000)
      }).id('click')

      Button() {
192
        Text('longClick').fontSize(25).fontWeight(FontWeight.Bold)
193
      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
Z
zengyawen 已提交
194
      .gesture(
195 196
      LongPressGesture().onActionEnd(() => {
        console.info('long clicked')
197
        this.text = "Button 'longClick' is longclicked"
198
        setTimeout(() => {
M
match 已提交
199
          let rect = Utils.getComponentRect('onTouch') // 获取id为"onTouch"组件的矩形区域坐标
200 201
          let touchPoint: TouchObject = {
            id: 1,
M
match 已提交
202 203
            x: rect.left + (rect.right - rect.left) / 2, // 组件中心点x坐标
            y: rect.top + (rect.bottom - rect.top) / 2, // 组件中心点y坐标
204
            type: TouchType.Down,
M
match 已提交
205 206
            screenX: rect.left + (rect.right - rect.left) / 2, // 组件中心点x坐标
            screenY: rect.left + (rect.right - rect.left) / 2, // 组件中心点y坐标
207
          }
M
match 已提交
208
          sendTouchEvent(touchPoint) // 发送触摸事件
209
          touchPoint.type = TouchType.Up
M
match 已提交
210
          sendTouchEvent(touchPoint) // 发送触摸事件
211
        }, 2000)
212
      })).id('longClick')
213 214 215 216 217 218 219 220

      Button() {
        Text('onTouch').fontSize(25).fontWeight(FontWeight.Bold)
      }.type(ButtonType.Capsule).margin({ top: 20 })
      .onClick(() => {
        console.info('onTouch is clicked')
        this.text = "Button 'onTouch' is clicked"
        setTimeout(() => {
M
match 已提交
221
          let rect = Utils.getComponentRect('onMouse') // 获取id为"onMouse"组件的矩形区域坐标
222 223 224
          let mouseEvent: MouseEvent = {
            button: MouseButton.Left,
            action: MouseAction.Press,
M
match 已提交
225 226 227 228
            x: rect.left + (rect.right - rect.left) / 2, // 组件中心点x坐标
            y: rect.top + (rect.bottom - rect.top) / 2, // 组件中心点y坐标
            screenX: rect.left + (rect.right - rect.left) / 2, // 组件中心点x坐标
            screenY: rect.top + (rect.bottom - rect.top) / 2, // 组件中心点y坐标
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
            timestamp: 1,
            target: {
              area: {
                width: 1,
                height: 1,
                position: {
                  x: 1,
                  y: 1
                },
                globalPosition: {
                  x: 1,
                  y: 1
                }
              }
            },
L
luoying_ace_admin 已提交
244 245 246 247 248
            source: SourceType.Mouse,
            pressure: 1,
            tiltX: 1,
            tiltY: 1,
            sourceTool: SourceTool.Unknown
249
          }
M
match 已提交
250
          sendMouseEvent(mouseEvent) // 发送鼠标事件
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
        }, 2000)
      }).id('onTouch')

      Button() {
        Text('onMouse').fontSize(25).fontWeight(FontWeight.Bold)
      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
      .onMouse(() => {
        console.info('onMouse')
        this.text = "Button 'onMouse' in onMouse"
        setTimeout(() => {
          let keyEvent: KeyEvent = {
            type: KeyType.Down,
            keyCode: 2049,
            keyText: 'tab',
            keySource: 4,
            deviceId: 0,
            metaKey: 0,
            timestamp: 0
          }
M
match 已提交
270
          sendKeyEvent(keyEvent) // 发送按键事件
271 272 273 274
        }, 2000)
      }).id('onMouse')

      Text(this.text).fontSize(25).padding(15)
Z
zengyawen 已提交
275
    }
276
    .width('100%').height('100%')
Z
zengyawen 已提交
277 278 279
  }
}
```