• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Class (FocusController)
2
3提供控制焦点的能力,如清除、移动和激活焦点等功能。
4
5> **说明:**
6>
7> - 本模块首批接口从API version 10开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
8>
9> - 本Class首批接口从API version 12开始支持。
10>
11> - 以下API需先使用UIContext中的[getFocusController()](arkts-apis-uicontext-uicontext.md#getfocuscontroller12)方法获取FocusController实例,再通过该实例调用对应方法。
12
13## clearFocus<sup>12+</sup>
14
15clearFocus(): void
16
17清除焦点,将焦点强制转移到页面根容器节点,焦点链路上其他节点失焦。
18
19**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
20
21**系统能力:** SystemCapability.ArkUI.ArkUI.Full
22
23**示例:**
24
25```ts
26@Entry
27@Component
28struct ClearFocusExample {
29  @State inputValue: string = '';
30  @State btColor: Color = Color.Blue;
31
32  build() {
33    Column({ space: 20 }) {
34      Column({ space: 5 }) {
35        Button('button1')
36          .width(200)
37          .height(70)
38          .fontColor(Color.White)
39          .focusOnTouch(true)
40          .backgroundColor(Color.Blue)
41        Button('button2')
42          .width(200)
43          .height(70)
44          .fontColor(Color.White)
45          .focusOnTouch(true)
46          .backgroundColor(this.btColor)
47          .defaultFocus(true)
48          .onFocus(() => {
49            this.btColor = Color.Red;
50          })
51          .onBlur(() => {
52            this.btColor = Color.Blue;
53          })
54        Button('clearFocus')
55          .width(200)
56          .height(70)
57          .fontColor(Color.White)
58          .backgroundColor(Color.Blue)
59          .onClick(() => {
60            this.getUIContext().getFocusController().clearFocus();
61          })
62      }
63    }
64    .width('100%')
65    .height('100%')
66  }
67}
68```
69
70## requestFocus<sup>12+</sup>
71
72requestFocus(key: string): void
73
74通过组件的id将焦点转移到组件树对应的实体节点,当前帧生效。
75
76**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
77
78**系统能力:** SystemCapability.ArkUI.ArkUI.Full
79
80**参数:**
81
82| 参数名 | 类型 | 必填 | 说明 |
83| ------- | ------- | ------- | ------- |
84| key | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。|
85
86**错误码:**
87
88以下错误码的详细介绍请参见[焦点错误码](errorcode-focus.md)。
89
90| 错误码ID | 错误信息                                        |
91| -------- | ----------------------------------------------- |
92| 150001   | the component cannot be focused.                |
93| 150002   | This component has an unfocusable ancestor.     |
94| 150003   | the component is not on tree or does not exist. |
95
96**示例:**
97
98```ts
99@Entry
100@Component
101struct RequestExample {
102  @State btColor: Color = Color.Blue;
103
104  build() {
105    Column({ space: 20 }) {
106      Column({ space: 5 }) {
107        Button('Button')
108          .width(200)
109          .height(70)
110          .fontColor(Color.White)
111          .focusOnTouch(true)
112          .backgroundColor(this.btColor)
113          .onFocus(() => {
114            this.btColor = Color.Red;
115          })
116          .onBlur(() => {
117            this.btColor = Color.Blue;
118          })
119          .id("testButton")
120
121        Divider()
122          .vertical(false)
123          .width("80%")
124          .backgroundColor(Color.Black)
125          .height(10)
126
127        Button('requestFocus')
128          .width(200)
129          .height(70)
130          .onClick(() => {
131            this.getUIContext().getFocusController().requestFocus("testButton");
132          })
133
134        Button('requestFocus fail')
135          .width(200)
136          .height(70)
137          .onClick(() => {
138            try {
139              this.getUIContext().getFocusController().requestFocus("eee");
140            } catch (error) {
141              console.error('requestFocus failed code is ' + error.code + ' message is ' + error.message);
142            }
143          })
144      }
145    }
146    .width('100%')
147    .height('100%')
148  }
149}
150```
151
152## activate<sup>14+</sup>
153
154activate(isActive: boolean, autoInactive?: boolean): void
155
156设置当前界面的[焦点激活态](../../ui/arkts-common-events-focus-event.md)。
157
158**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
159
160**系统能力:** SystemCapability.ArkUI.ArkUI.Full
161
162**参数:**
163
164| 参数名 | 类型 | 必填 | 说明 |
165| ------- | ------- | ------- | ------- |
166| isActive| boolean| 是 | 设置是否进入/退出焦点激活态。<br/>true表示设置进入焦点激活态,false表示设置退出焦点激活态。 |
167| autoInactive | boolean | 否 | 设置焦点激活态退出逻辑。<br/>为true时,会自动在触摸事件、鼠标事件触发时退出,为false时,仅受开发者API控制。<br/>默认值:true |
168
169**示例:**
170
171```ts
172// 该示例表示在页面加载完成时进入焦点激活态,可按方向键在button间走焦
173@Entry
174@Component
175struct ActivateExample {
176  aboutToAppear() {
177    this.getUIContext().getFocusController().activate(true, false);
178  }
179
180  aboutToDisappear() {
181    this.getUIContext().getFocusController().activate(false);
182  }
183
184  build() {
185    Row() {
186      Button('Button1')
187        .width(200)
188        .height(70)
189        .defaultFocus(true)
190
191      Button('Button2')
192        .width(200)
193        .height(70)
194
195      Button('Button3')
196        .width(200)
197        .height(70)
198    }
199    .padding(10)
200    .justifyContent(FlexAlign.SpaceBetween)
201    .width(800)
202  }
203}
204```
205
206## isActive<sup>20+</sup>
207
208isActive(): boolean
209
210返回UI实例的焦点激活态。
211
212焦点激活态可参考[基础概念:焦点激活态](../../ui/arkts-common-events-focus-event.md#基础概念)。
213
214**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。
215
216**系统能力:** SystemCapability.ArkUI.ArkUI.Full
217
218**返回值:**
219
220| 类型          | 说明       |
221| ------------  | --------- |
222|  boolean  | 返回UI实例的焦点激活态。true表示当前进入焦点激活态,false表示当前已退出焦点激活态。 |
223
224**示例:**
225
226验证isActive返回UI实例的焦点激活态。
227
228```ts
229@Entry
230@Component
231struct ClearFocusExample {
232  @State inputValue: string = '';
233  @State btColor: Color = Color.Blue;
234
235  build() {
236    Column({ space: 20 }) {
237      Column({ space: 5 }) {
238        Button('button1')
239          .width(200)
240          .height(70)
241          .fontColor(Color.White)
242          .focusOnTouch(true)
243          .backgroundColor(Color.Blue)
244          .onClick(()=> {
245            console.log("button1 onClick");
246            this.getUIContext().getFocusController().activate(true);
247            console.log("focus status " + this.getUIContext().getFocusController().isActive());
248          })
249        Button('button2')
250          .width(200)
251          .height(70)
252          .fontColor(Color.White)
253          .focusOnTouch(true)
254          .backgroundColor(this.btColor)
255          .defaultFocus(true)
256          .onClick(()=> {
257            console.log("button2 onClick");
258            this.getUIContext().getFocusController().activate(false);
259            console.log("focus status " + this.getUIContext().getFocusController().isActive());
260          })
261          .onFocus(() => {
262            this.btColor = Color.Red;
263          })
264          .onBlur(() => {
265            this.btColor = Color.Blue;
266          })
267      }
268    }
269    .width('100%')
270    .height('100%')
271  }
272}
273```
274
275## setAutoFocusTransfer<sup>14+</sup>
276
277setAutoFocusTransfer(isAutoFocusTransfer: boolean): void
278
279设置页面切换时,新的页面是否需要主动获取焦点。
280
281**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
282
283**系统能力:** SystemCapability.ArkUI.ArkUI.Full
284
285**参数:**
286
287| 参数名 | 类型 | 必填 | 说明 |
288| ------- | ------- | ------- | ------- |
289| isAutoFocusTransfer | boolean| 是 | 设置页面切换时,新的页面是否需要主动获取焦点,例如[Router](js-apis-router.md#routerpushurldeprecated)、[Navigation](arkui-ts/ts-basic-components-navigation.md)、[Menu](arkui-ts/ts-basic-components-menu.md)、[Dialog](arkui-ts/ohos-arkui-advanced-Dialog.md)、[Popup](arkui-ts/ohos-arkui-advanced-Popup.md)等。true表示需要主动获取焦点,false表示不需要主动获取焦点。默认值为true。 |
290
291**示例:**
292
293```ts
294@CustomDialog
295struct CustomDialogExample {
296  controller?: CustomDialogController;
297  build() {
298    Column() {
299      Text('这是自定义弹窗')
300        .fontSize(30)
301        .height(100)
302      Text('弹窗不能主动获取焦点')
303        .fontSize(20)
304        .height(100)
305      Button('点我关闭弹窗')
306        .onClick(() => {
307          if (this.controller != undefined) {
308            this.getUIContext().getFocusController().setAutoFocusTransfer(true);
309            this.controller.close();
310          }
311        })
312        .margin(20)
313    }
314  }
315}
316@Entry
317@Component
318struct CustomDialogUser {
319  dialogController: CustomDialogController | null = new CustomDialogController({
320    builder: CustomDialogExample({
321    }),
322  });
323  aboutToDisappear() {
324    this.dialogController = null;
325  }
326
327  build() {
328    Column() {
329      Button('click me')
330        .onClick(() => {
331          if (this.dialogController != null) {
332            this.getUIContext().getFocusController().setAutoFocusTransfer(false);
333            this.dialogController.open();
334          }
335        }).backgroundColor(0x317aff)
336    }.width('100%').margin({ top: 5 })
337  }
338}
339```
340
341## setKeyProcessingMode<sup>15+</sup>
342
343setKeyProcessingMode(mode: KeyProcessingMode): void
344
345设置按键事件处理的优先级。
346
347**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
348
349**系统能力:** SystemCapability.ArkUI.ArkUI.Full
350
351**参数:**
352
353| 参数名 | 类型 | 必填 | 说明 |
354| ------- | ------- | ------- | ------- |
355| mode | [KeyProcessingMode](./arkui-ts/ts-universal-attributes-focus.md#keyprocessingmode15)| 是 | 按键处理模式。 |
356
357**示例:**
358
359```ts
360
361// 该示例演示了在页面加载完成后设置走焦类型的实现方式。
362@Entry
363@Component
364struct Index {
365
366  aboutToAppear() {
367    this.getUIContext().getFocusController().setKeyProcessingMode(KeyProcessingMode.ANCESTOR_EVENT);
368  }
369
370  build() {
371    Row() {
372      Row() {
373        Button('Button1').id('Button1').onKeyEvent((event) => {
374          console.log("Button1");
375          return true;
376        })
377        Button('Button2').id('Button2').onKeyEvent((event) => {
378          console.log("Button2");
379          return true;
380        })
381      }
382      .width('100%')
383      .height('100%')
384      .id('Row1')
385      .onKeyEventDispatch((event) => {
386        let context = this.getUIContext();
387        context.getFocusController().requestFocus('Button1');
388        return context.dispatchKeyEvent('Button1', event);
389      })
390    }
391    .height('100%')
392    .width('100%')
393    .onKeyEventDispatch((event) => {
394      if (event.type == KeyType.Down) {
395        let context = this.getUIContext();
396        context.getFocusController().requestFocus('Row1');
397        return context.dispatchKeyEvent('Row1', event);
398      }
399      return true;
400    })
401  }
402}
403```
404