ts-universal-attributes-component-id.md 9.4 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.

E
ester.zhou 已提交
26 27 28 29 30
**Parameters**

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

E
ester.zhou 已提交
32 33 34 35 36
**Return value**

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

38
### getInspectorTree<sup>9+</sup>
Z
zengyawen 已提交
39

40 41 42 43
getInspectorTree(): string

Obtains the component tree and component attributes.

E
ester.zhou 已提交
44
**Return value**
45

E
ester.zhou 已提交
46 47 48
| Type    | Description                           |
| ------ | --------------------------- |
| string | JSON string of the component tree and component attribute list.|
49 50

### sendEventByKey<sup>9+</sup>
Z
zengyawen 已提交
51 52 53 54 55

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

Sends an event to the component with the specified ID.

E
ester.zhou 已提交
56 57 58 59 60 61 62 63 64
**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 已提交
65

E
ester.zhou 已提交
66 67 68
| Type         | Description                        |
| -------- | --------------------------|
| boolean  | Returns **true** if the component with the specified ID is found; returns **false** otherwise.|
69 70 71 72 73 74 75

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

sendTouchEvent(event: TouchObject): boolean

Sends a touch event.

E
ester.zhou 已提交
76
**Parameters**
77

E
ester.zhou 已提交
78 79
| Name     | Type           | Mandatory | Description                                                        |
| ----- | ----------- | ---- | ------------------------------------------------------------ |
E
ester.zhou 已提交
80
| 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).|
81

E
ester.zhou 已提交
82
**Return value**
83

E
ester.zhou 已提交
84 85 86
| Type     | Description                        |
| ------- | ---------------------------|
| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
87 88 89 90 91 92 93

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

sendKeyEvent(event: KeyEvent): boolean

Sends a key event.

E
ester.zhou 已提交
94
**Parameters**
95

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

E
ester.zhou 已提交
100
**Return value**
101

E
ester.zhou 已提交
102 103 104
| Type     | Description                          |
| ------- | ------------------------------|
| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
105 106 107 108 109 110 111

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

sendMouseEvent(event: MouseEvent): boolean

Sends a mouse event.

E
ester.zhou 已提交
112
**Parameters**
113

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

E
ester.zhou 已提交
118
**Return value**
Z
zengyawen 已提交
119

E
ester.zhou 已提交
120 121 122
| Type     | Description                                |
| ------- | ---------------------------------- |
| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
Z
zengyawen 已提交
123 124 125

## Example

126 127 128
```ts
// xxx.ets
class Utils {
E
ester.zhou 已提交
129 130 131 132 133
  static rect_left
  static rect_top
  static rect_right
  static rect_bottom
  static rect_value
134

E
ester.zhou 已提交
135
  // Obtain the coordinates of the rectangular area occupied by the component.
136
  static getComponentRect(key) {
E
ester.zhou 已提交
137 138 139
    let strJson = getInspectorByKey(key)
    let obj = JSON.parse(strJson)
    console.info("[getInspectorByKey] current component obj is: " + JSON.stringify(obj))
140
    let rectInfo = JSON.parse('[' + obj.$rect + ']')
E
ester.zhou 已提交
141
    console.info("[getInspectorByKey] rectInfo is: " + rectInfo)
142 143 144 145 146 147 148 149 150 151
    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 已提交
152 153 154
@Entry
@Component
struct IdExample {
155 156
  @State text: string = ''

Z
zengyawen 已提交
157 158
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
159

Z
zengyawen 已提交
160
      Button() {
161 162 163 164 165 166 167 168 169 170
        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 已提交
171 172
        console.info(getInspectorByKey("click"))
        console.info(getInspectorTree())
173
        this.text = "Button 'click to start' is clicked"
Z
zengyawen 已提交
174
        setTimeout(() => {
E
ester.zhou 已提交
175
          sendEventByKey("longClick", 11, "") // Send a long-click event to the component whose ID is "longClick".
Z
zengyawen 已提交
176 177 178 179
        }, 2000)
      }).id('click')

      Button() {
180 181
        Text('longClick').fontSize(25).fontWeight(FontWeight.Bold)
      }.margin({ top: 20 }).backgroundColor('#0D9FFB')
Z
zengyawen 已提交
182
      .gesture(
183 184 185 186
      LongPressGesture().onActionEnd(() => {
        console.info('long clicked')
        this.text = "Button 'longClick' is longclicked"
        setTimeout(() => {
E
ester.zhou 已提交
187
          let rect = Utils.getComponentRect('onTouch') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onTouch".
188 189
          let touchPoint: TouchObject = {
            id: 1,
E
ester.zhou 已提交
190 191
            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.
192
            type: TouchType.Down,
E
ester.zhou 已提交
193 194
            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.
195
          }
E
ester.zhou 已提交
196
          sendTouchEvent(touchPoint) // Send a touch event.
197
          touchPoint.type = TouchType.Up
E
ester.zhou 已提交
198
          sendTouchEvent(touchPoint) // Send a touch event.
199 200 201 202 203 204 205 206 207 208
        }, 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 已提交
209
          let rect = Utils.getComponentRect('onMouse') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onMouse".
210 211 212
          let mouseEvent: MouseEvent = {
            button: MouseButton.Left,
            action: MouseAction.Press,
E
ester.zhou 已提交
213 214 215 216
            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.
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
            timestamp: 1,
            target: {
              area: {
                width: 1,
                height: 1,
                position: {
                  x: 1,
                  y: 1
                },
                globalPosition: {
                  x: 1,
                  y: 1
                }
              }
            },
E
ester.zhou 已提交
232 233 234 235 236
            source: SourceType.Mouse,
            pressure: 1,
            tiltX: 1,
            tiltY: 1,
            sourceTool: SourceTool.Unknown
237
          }
E
ester.zhou 已提交
238
          sendMouseEvent(mouseEvent) // Send a mouse event.
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
        }, 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 已提交
258
          sendKeyEvent(keyEvent) // Send a key event.
259 260 261 262
        }, 2000)
      }).id('onMouse')

      Text(this.text).fontSize(25).padding(15)
Z
zengyawen 已提交
263
    }
264
    .width('100%').height('100%')
Z
zengyawen 已提交
265 266 267
  }
}
```