ts-universal-attributes-component-id.md 9.6 KB
Newer Older
Z
zengyawen 已提交
1 2
# Component ID

3
**id** identifies a component uniquely within an application. This module provides APIs for obtaining the attributes of or sending events to the component with the specified ID.
Z
zengyawen 已提交
4

5 6
>  **NOTE**
>
E
ester.zhou 已提交
7
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
Z
zengyawen 已提交
8 9 10 11


## Attributes

E
ester.zhou 已提交
12 13 14
| Name  | Type    | Description                        |
| -----| -------- | ----------------------------- |
| id   | string   | Unique ID you assigned to the component.<br>Default value: **''**|
Z
zengyawen 已提交
15 16 17 18 19


## APIs


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

getInspectorByKey(id: string): string

Obtains all attributes of the component with the specified ID, excluding the information about child components.

26 27
This API is used only for test purposes.

E
ester.zhou 已提交
28 29 30 31 32
**Parameters**

| Name  | Type     | Mandatory    | Description       |
| ---- | -------- | ---- | -------------|
| id   | string   | Yes   | ID of the component whose attributes are to be obtained.|
Z
zengyawen 已提交
33

E
ester.zhou 已提交
34 35 36 37 38
**Return value**

| Type       | Description            |
| -------| -------------- |
| string | JSON string of the component attribute list.|
Z
zengyawen 已提交
39

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

42
getInspectorTree(): Object
43 44 45

Obtains the component tree and component attributes.

46 47
This API is used only for test purposes.

E
ester.zhou 已提交
48
**Return value**
49

E
ester.zhou 已提交
50 51
| Type    | Description                           |
| ------ | --------------------------- |
52
| Object | JSON object of the component tree and component attribute list.|
53 54

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

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

Sends an event to the component with the specified ID.

60 61
This API is used only for test purposes.

E
ester.zhou 已提交
62 63 64 65 66 67 68 69 70
**Parameters**

| Name      | Type     | Mandatory      | Description                        |
| ------ | -------| ---- | -------------------------- |
| id     | string | Yes   | ID of the component to which the event is to be sent.                     |
| action | number | Yes   | Type of the event to be sent. The options are as follows:<br>- **10**: click event.<br>- **11**: long-click event.|
| params | string | Yes   | Event parameters. If there is no parameter, pass an empty string **""**.           |

**Return value**
Z
zengyawen 已提交
71

E
ester.zhou 已提交
72 73 74
| Type         | Description                        |
| -------- | --------------------------|
| boolean  | Returns **true** if the component with the specified ID is found; returns **false** otherwise.|
75 76 77 78 79 80 81

### sendTouchEvent<sup>9+</sup>

sendTouchEvent(event: TouchObject): boolean

Sends a touch event.

82 83
This API is used only for test purposes.

E
ester.zhou 已提交
84
**Parameters**
85

E
ester.zhou 已提交
86 87
| Name     | Type           | Mandatory | Description                                                        |
| ----- | ----------- | ---- | ------------------------------------------------------------ |
E
ester.zhou 已提交
88
| event | [TouchObject](ts-universal-events-touch.md#touchobject) | Yes   | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).|
89

E
ester.zhou 已提交
90
**Return value**
91

E
ester.zhou 已提交
92 93 94
| Type     | Description                        |
| ------- | ---------------------------|
| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
95 96 97 98 99 100 101

### sendKeyEvent<sup>9+</sup>

sendKeyEvent(event: KeyEvent): boolean

Sends a key event.

102 103
This API is used only for test purposes.

E
ester.zhou 已提交
104
**Parameters**
105

E
ester.zhou 已提交
106 107
| Name   | Type    | Mandatory     | Description                                                        |
| ----- | -------- | ----  | ------------------------------------------------------------ |
E
ester.zhou 已提交
108
| event | [KeyEvent](ts-universal-events-key.md#keyevent) | Yes    | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).|
109

E
ester.zhou 已提交
110
**Return value**
111

E
ester.zhou 已提交
112 113 114
| Type     | Description                          |
| ------- | ------------------------------|
| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
115 116 117 118 119 120 121

### sendMouseEvent<sup>9+</sup>

sendMouseEvent(event: MouseEvent): boolean

Sends a mouse event.

122 123
This API is used only for test purposes.

E
ester.zhou 已提交
124
**Parameters**
125

E
ester.zhou 已提交
126 127
| Name    | Type      | Mandatory      | Description                                    |
| ----- | ---------- | ----  | --------------------------------------- |
E
ester.zhou 已提交
128
| event | [MouseEvent](ts-universal-mouse-key.md#mouseevent) | Yes   | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).|
129

E
ester.zhou 已提交
130
**Return value**
Z
zengyawen 已提交
131

E
ester.zhou 已提交
132 133 134
| Type     | Description                                |
| ------- | ---------------------------------- |
| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
Z
zengyawen 已提交
135 136 137

## Example

138 139 140
```ts
// xxx.ets
class Utils {
E
ester.zhou 已提交
141 142 143 144 145
  static rect_left
  static rect_top
  static rect_right
  static rect_bottom
  static rect_value
146

E
ester.zhou 已提交
147
  // Obtain the coordinates of the rectangular area occupied by the component.
148
  static getComponentRect(key) {
E
ester.zhou 已提交
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 + ']')
E
ester.zhou 已提交
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(() => {
E
ester.zhou 已提交
187
          sendEventByKey("longClick", 11, "") // Send a long-click event to the component whose ID is "longClick".
Z
zengyawen 已提交
188 189 190 191
        }, 2000)
      }).id('click')

      Button() {
192 193
        Text('longClick').fontSize(25).fontWeight(FontWeight.Bold)
      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
Z
zengyawen 已提交
194
      .gesture(
195 196 197 198
      LongPressGesture().onActionEnd(() => {
        console.info('long clicked')
        this.text = "Button 'longClick' is longclicked"
        setTimeout(() => {
E
ester.zhou 已提交
199
          let rect = Utils.getComponentRect('onTouch') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onTouch".
200 201
          let touchPoint: TouchObject = {
            id: 1,
E
ester.zhou 已提交
202 203
            x: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
            y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center.
204
            type: TouchType.Down,
E
ester.zhou 已提交
205 206
            screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
            screenY: rect.left + (rect.right - rect.left) / 2, // Y coordinate of the component center.
207
          }
E
ester.zhou 已提交
208
          sendTouchEvent(touchPoint) // Send a touch event.
209
          touchPoint.type = TouchType.Up
E
ester.zhou 已提交
210
          sendTouchEvent(touchPoint) // Send a touch event.
211 212 213 214 215 216 217 218 219 220
        }, 2000)
      })).id('longClick')

      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(() => {
E
ester.zhou 已提交
221
          let rect = Utils.getComponentRect('onMouse') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onMouse".
222 223 224
          let mouseEvent: MouseEvent = {
            button: MouseButton.Left,
            action: MouseAction.Press,
E
ester.zhou 已提交
225 226 227 228
            x: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
            y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center.
            screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
            screenY: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center.
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
                }
              }
            },
E
ester.zhou 已提交
244 245 246 247 248
            source: SourceType.Mouse,
            pressure: 1,
            tiltX: 1,
            tiltY: 1,
            sourceTool: SourceTool.Unknown
249
          }
E
ester.zhou 已提交
250
          sendMouseEvent(mouseEvent) // Send a mouse event.
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
          }
E
ester.zhou 已提交
270
          sendKeyEvent(keyEvent) // Send a key event.
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
  }
}
```