ts-universal-attributes-focus.md 11.3 KB
Newer Older
Z
zengyawen 已提交
1 2
# Focus Control

E
ester.zhou 已提交
3 4
Focus control attributes set whether a component is focusable, how it participates in sequential keyboard navigation, 

E
ester.zhou 已提交
5
>  **NOTE**
E
ester.zhou 已提交
6 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


E
ester.zhou 已提交
10
## Attributes
Z
zengyawen 已提交
11

E
ester.zhou 已提交
12 13
| Name              | Type| Description                                  |
| -------------------- | -------- | ---------------------------------------- |
E
ester.zhou 已提交
14
| focusable            | boolean  | Whether the current component is focusable.<br>**NOTE**<br>Components that have default interaction logic, such as **\<Button>** and **\<TextInput>**, are focusable by default. Other components, such as **\<Text>** and **\<Image>**, are not focusable by default. Only focusable components can trigger a [focus event](ts-universal-focus-event.md). |
E
ester.zhou 已提交
15 16
| tabIndex<sup>9+</sup> | number   | How the current component participates in sequential keyboard navigation.<br>- **tabIndex** >= 0: The component is focusable in sequential keyboard navigation, with its order defined by the value. A component with a larger value gains focus later than one with a smaller value. If multiple components share the same **tabIndex** value, their focus order follows their position in the component tree.<br>- **tabIndex** < 0 (usually **tabIndex** = -1): The component is focusable, but cannot be reached through sequential keyboard navigation.<br>Default value: **0**|
| defaultFocus<sup>9+</sup> | boolean  | Whether to set the current component as the default focus of the page. This attribute takes effect only when the page is new and accessed for the first time.<br>Default value: **false**|
E
ester.zhou 已提交
17
| groupDefaultFocus<sup>9+</sup> | boolean  | Whether to set the current component as the default focus of the parent container. This attribute takes effect only when the container is new and has focus for the first time.<br>Default value: **false**<br>**NOTE**<br>This attribute must be used together with **tabIndex**. When **tabIndex** is set for a container and **groupDefaultFocus** is set for a component in the container, the focus is automatically shifted to that component when the container obtains the focus for the first time. |
E
ester.zhou 已提交
18
| focusOnTouch<sup>9+</sup> | boolean | Whether the current component is focusable on touch.<br>Default value: **false**<br>**NOTE**<br>The component can obtain focus only when it is touchable or clickable.|
Z
zengyawen 已提交
19

E
ester.zhou 已提交
20
## focusControl<sup>9+</sup>
Z
zengyawen 已提交
21

E
ester.zhou 已提交
22
### requestFocus<sup>9+</sup>
Z
zengyawen 已提交
23

E
ester.zhou 已提交
24
requestFocus(value: string): boolean
Z
zengyawen 已提交
25

E
ester.zhou 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39
Requests the focus to move to the specified component. This API can be used in global method statements. 

**Parameters**

| Name| Type| Mandatory| Description|
| ----- | ------ | ---- | ---- |
| value | string | Yes  | String bound to the target component using the **key(value: string)**.|

**Return value**

| Type| Description|
| ------- | ---- |
| boolean | Returns whether the focus is successfully moved to the target component. Returns **true** if the specified component exists and the focus is successfully moved to the target component; returns **false** otherwise.|

E
ester.zhou 已提交
40 41
>  **NOTE**
>
E
ester.zhou 已提交
42
>  The following components support focus control: **\<Button>**, **\<Text>**, **\<Image>**, **\<List>**, and **\<Grid>**. Currently, the running effect of the focus event can be displayed only on a real device.
Z
zengyawen 已提交
43 44 45

## Example

E
ester.zhou 已提交
46 47 48
### Example 1

defaultFocus/groupDefaultFocus/focusOnTouch:
E
ester.zhou 已提交
49

E
ester.zhou 已提交
50
**defaultFocus** sets the bound component as the initial focus of the page after the page is created. **groupDefaultFocus** sets the bound component as the initial focus of the **tabIndex** container after the container is created. **focusOnTouch** sets the bound component to obtain focus upon being clicked.
E
ester.zhou 已提交
51

52
```ts
E
ester.zhou 已提交
53
// focusTest.ets
Z
zengyawen 已提交
54 55 56
@Entry
@Component
struct FocusableExample {
E
ester.zhou 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
  @State inputValue: string = ''

  build() {
    Scroll() {
      Row({ space: 20 }) {
        Column({ space: 20 }) {
          Column({ space: 5 }) {
            Button('Group1')
              .width(165)
              .height(40)
              .fontColor(Color.White)
              .focusOnTouch(true)           // The button is focusable on touch.
            Row({ space: 5 }) {
              Button()
                .width(80)
                .height(40)
                .fontColor(Color.White)
              Button()
                .width(80)
                .height(40)
                .fontColor(Color.White)
                .focusOnTouch(true)           // The button is focusable on touch.
            }
            Row({ space: 5 }) {
              Button()
                .width(80)
                .height(40)
                .fontColor(Color.White)
              Button()
                .width(80)
                .height(40)
                .fontColor(Color.White)
            }
          }.borderWidth(2).borderColor(Color.Red).borderStyle(BorderStyle.Dashed)
E
ester.zhou 已提交
91
          .tabIndex(1)                      // The column is the initial component to have focus in sequential keyboard navigation.
E
ester.zhou 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105
          Column({ space: 5 }) {
            Button('Group2')
              .width(165)
              .height(40)
              .fontColor(Color.White)
            Row({ space: 5 }) {
              Button()
                .width(80)
                .height(40)
                .fontColor(Color.White)
              Button()
                .width(80)
                .height(40)
                .fontColor(Color.White)
E
ester.zhou 已提交
106
                .groupDefaultFocus(true)      // The button obtains focus when its upper-level column is in focus.
E
ester.zhou 已提交
107 108 109 110 111 112 113 114 115 116 117 118
            }
            Row({ space: 5 }) {
              Button()
                .width(80)
                .height(40)
                .fontColor(Color.White)
              Button()
                .width(80)
                .height(40)
                .fontColor(Color.White)
            }
          }.borderWidth(2).borderColor(Color.Green).borderStyle(BorderStyle.Dashed)
E
ester.zhou 已提交
119
          .tabIndex(2)                      // The column is the second component to have focus in sequential keyboard navigation.
E
ester.zhou 已提交
120 121 122 123 124 125
        }
        Column({ space: 5 }) {
          TextInput({placeholder: 'input', text: this.inputValue})
            .onChange((value: string) => {
              this.inputValue = value
            })
E
ester.zhou 已提交
126
            .defaultFocus(true)             // The <TextInput> component is the initial default focus of the page.
E
ester.zhou 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
          Button('Group3')
            .width(165)
            .height(40)
            .fontColor(Color.White)
          Row({ space: 5 }) {
            Button()
              .width(80)
              .height(40)
              .fontColor(Color.White)
            Button()
              .width(80)
              .height(40)
              .fontColor(Color.White)
          }
          Button()
            .width(165)
            .height(40)
            .fontColor(Color.White)
          Row({ space: 5 }) {
            Button()
              .width(80)
              .height(40)
              .fontColor(Color.White)
            Button()
              .width(80)
              .height(40)
              .fontColor(Color.White)
          }
          Button()
            .width(165)
            .height(40)
            .fontColor(Color.White)
          Row({ space: 5 }) {
            Button()
              .width(80)
              .height(40)
              .fontColor(Color.White)
            Button()
              .width(80)
              .height(40)
              .fontColor(Color.White)
          }
        }.borderWidth(2).borderColor(Color.Orange).borderStyle(BorderStyle.Dashed)
E
ester.zhou 已提交
170
        .tabIndex(3)                      // The column is the third component to have focus in sequential keyboard navigation.
E
ester.zhou 已提交
171 172 173 174 175 176 177 178 179 180 181
      }.alignItems(VerticalAlign.Top)
    }
  }
}
```
Diagrams:

When you press the Tab button for the first time, the focus switches to the component bound to **defaultFocus**.

![defaultFocus](figures/defaultFocus.png)

E
ester.zhou 已提交
182
When you press the Tab button for the second time, the focus switches to the container that matches **tabIndex(1)** and automatically moves to the component bound to **groupDefaultFocus**.
E
ester.zhou 已提交
183 184 185

![groupDefaultFocus1](figures/groupDefaultFocus1.png)

E
ester.zhou 已提交
186
When you press the Tab button for the third time, the focus switches to the container that matches **tabIndex(2)** and automatically moves to the component bound to **groupDefaultFocus**.
E
ester.zhou 已提交
187 188 189

![groupDefaultFocus2](figures/groupDefaultFocus2.png)

E
ester.zhou 已提交
190
When you press the Tab button for the fourth time, the focus switches to the container that matches **tabIndex(3)** and automatically moves to the component bound to **groupDefaultFocus**.
E
ester.zhou 已提交
191 192 193 194 195 196 197 198 199 200 201

![groupDefaultFocus3](figures/groupDefaultFocus3.png)

Click the component bound to **focusOnTouch**. The component then obtains the focus.

![focusOnTouch](figures/focusOnTouch.png)

### Example 2

Sample code for **focusControl.requestFocus**:

E
ester.zhou 已提交
202
Use the **focusContrl.requestFocus** API to enable a specified component to obtain focus.
E
ester.zhou 已提交
203 204
```ts
// requestFocus.ets
E
ester.zhou 已提交
205
import promptAction from '@ohos.promptAction';
E
ester.zhou 已提交
206 207 208 209 210 211

@Entry
@Component
struct RequestFocusExample {
  @State idList: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'LastPageId']
  @State selectId: string = 'LastPageId'
Z
zengyawen 已提交
212 213 214

  build() {
    Column({ space:20 }){
E
ester.zhou 已提交
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
      Row({space: 5}) {
        Button("id: " + this.idList[0] + " focusable(false)")
          .width(200).height(70).fontColor(Color.White)
          .key(this.idList[0])
          .focusable(false)
        Button("id: " + this.idList[1])
          .width(200).height(70).fontColor(Color.White)
          .key(this.idList[1])
      }
      Row({space: 5}) {
        Button("id: " + this.idList[2])
          .width(200).height(70).fontColor(Color.White)
          .key(this.idList[2])
        Button("id: " + this.idList[3])
          .width(200).height(70).fontColor(Color.White)
          .key(this.idList[3])
      }
      Row({space: 5}) {
        Button("id: " + this.idList[4])
          .width(200).height(70).fontColor(Color.White)
          .key(this.idList[4])
        Button("id: " + this.idList[5])
          .width(200).height(70).fontColor(Color.White)
          .key(this.idList[5])
      }
      Row({space: 5}) {
        Select([{value: this.idList[0]},
                {value: this.idList[1]},
                {value: this.idList[2]},
                {value: this.idList[3]},
                {value: this.idList[4]},
                {value: this.idList[5]},
                {value: this.idList[6]}])
          .value(this.selectId)
          .onSelect((index: number) => {
            this.selectId = this.idList[index]
          })
        Button("RequestFocus")
          .width(200).height(70).fontColor(Color.White)
          .onClick(() => {
E
ester.zhou 已提交
255
            var res = focusControl.requestFocus(this.selectId)      // Enable the component selected by this.selectId to obtain focus.
E
ester.zhou 已提交
256
            if (res) {
E
ester.zhou 已提交
257
              promptAction.showToast({message: 'Request success'})
E
ester.zhou 已提交
258
            } else {
E
ester.zhou 已提交
259
              promptAction.showToast({message: 'Request failed'})
E
ester.zhou 已提交
260 261 262
            }
          })
      }
Z
zengyawen 已提交
263 264 265 266
    }.width('100%').margin({ top:20 })
  }
}
```
E
ester.zhou 已提交
267

E
ester.zhou 已提交
268 269 270
Diagrams:

Press the Tab button to activate the focus state.
E
ester.zhou 已提交
271

E
ester.zhou 已提交
272
Below shows how the UI behaves when you request focus for a component that does not exist.
E
ester.zhou 已提交
273 274 275

![requestFocus1](figures/requestFocus1.png)

E
ester.zhou 已提交
276
Below shows how the UI behaves when you request focus for a component that is not focusable.
E
ester.zhou 已提交
277 278 279

![requestFocus2](figures/requestFocus2.png)

E
ester.zhou 已提交
280
Below shows how the UI behaves when you request focus for a focusable component.
E
ester.zhou 已提交
281 282

![requestFocus3](figures/requestFocus3.png)