• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.arkui.UIContext (UIContext)
2
3在Stage模型中,WindowStage/Window可以通过[loadContent](js-apis-window.md#loadcontent9)接口加载页面并创建UI的实例,并将页面内容渲染到关联的窗口中,所以UI实例和窗口是一一关联的。一些全局的UI接口是和具体UI实例的执行上下文相关的,在当前接口调用时,通过追溯调用链跟踪到UI的上下文,来确定具体的UI实例。若在非UI页面中或者一些异步回调中调用这类接口,可能无法跟踪到当前UI的上下文,导致接口执行失败。
4
5@ohos.window在API version 10 新增[getUIContext](js-apis-window.md#getuicontext10)接口,获取UI上下文实例UIContext对象,使用UIContext对象提供的替代方法,可以直接作用在对应的UI实例上。
6
7> **说明:**
8>
9> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
10>
11> 示例效果请以真机运行为准,当前IDE预览器不支持。
12
13## UIContext
14
15以下API需先使用ohos.window中的[getUIContext()](js-apis-window.md#getuicontext10)方法获取UIContext实例,再通过此实例调用对应方法。或者可以通过自定义组件内置方法[getUIContext()](arkui-ts/ts-custom-component-api.md#getuicontext)获取。本文中UIContext对象以uiContext表示。
16
17### getFont
18
19getFont(): Font
20
21获取Font对象。
22
23**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
24
25**系统能力:** SystemCapability.ArkUI.ArkUI.Full
26
27**返回值:**
28
29| 类型            | 说明          |
30| ------------- | ----------- |
31| [Font](#font) | 返回Font实例对象。 |
32
33**示例:**
34
35```ts
36uiContext.getFont();
37```
38### getComponentUtils
39
40getComponentUtils(): ComponentUtils
41
42获取ComponentUtils对象。
43
44**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
45
46**系统能力:** SystemCapability.ArkUI.ArkUI.Full
47
48**返回值:**
49
50| 类型                                | 说明                    |
51| --------------------------------- | --------------------- |
52| [ComponentUtils](#componentutils) | 返回ComponentUtils实例对象。 |
53
54**示例:**
55
56```ts
57uiContext.getComponentUtils();
58```
59
60### getUIInspector
61
62getUIInspector(): UIInspector
63
64获取UIInspector对象。
65
66**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
67
68**系统能力:** SystemCapability.ArkUI.ArkUI.Full
69
70**返回值:**
71
72| 类型                          | 说明                 |
73| --------------------------- | ------------------ |
74| [UIInspector](#uiinspector) | 返回UIInspector实例对象。 |
75
76**示例:**
77
78```ts
79uiContext.getUIInspector();
80```
81
82### getUIObserver<sup>11+</sup>
83
84getUIObserver(): UIObserver
85
86获取UIObserver对象。
87
88**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
89
90**系统能力:** SystemCapability.ArkUI.ArkUI.Full
91
92**返回值:**
93
94| 类型                          | 说明                 |
95| --------------------------- | ------------------ |
96| [UIObserver](#uiobserver11) | 返回UIObserver实例对象。 |
97
98**示例:**
99
100```ts
101uiContext.getUIObserver();
102```
103
104### getMediaQuery
105
106getMediaQuery(): MediaQuery
107
108获取MediaQuery对象。
109
110**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
111
112**系统能力:** SystemCapability.ArkUI.ArkUI.Full
113
114**返回值:**
115
116| 类型                        | 说明                |
117| ------------------------- | ----------------- |
118| [MediaQuery](#mediaquery) | 返回MediaQuery实例对象。 |
119
120**示例:**
121
122```ts
123uiContext.getMediaQuery();
124```
125
126### getRouter
127
128getRouter(): Router
129
130获取Router对象。
131
132**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
133
134**系统能力:** SystemCapability.ArkUI.ArkUI.Full
135
136**返回值:**
137
138| 类型                | 说明            |
139| ----------------- | ------------- |
140| [Router](#router) | 返回Router实例对象。 |
141
142**示例:**
143
144```ts
145uiContext.getRouter();
146```
147
148### getPromptAction
149
150getPromptAction(): PromptAction
151
152获取PromptAction对象。
153
154**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
155
156**系统能力:** SystemCapability.ArkUI.ArkUI.Full
157
158**返回值:**
159
160| 类型                            | 说明                  |
161| ----------------------------- | ------------------- |
162| [PromptAction](#promptaction) | 返回PromptAction实例对象。 |
163
164**示例:**
165
166```ts
167uiContext.getPromptAction();
168```
169
170### getOverlayManager<sup>12+</sup>
171
172getOverlayManager(): OverlayManager
173
174获取OverlayManager对象。
175
176**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
177
178**系统能力:**: SystemCapability.ArkUI.ArkUI.Full
179
180**返回值:**
181
182| 类型                           | 说明                 |
183| ----------------------------- | ------------------- |
184| [OverlayManager](#overlaymanager12) | 返回OverlayManager实例对象。 |
185
186**示例:**
187
188```ts
189uiContext.getOverlayManager();
190```
191
192### animateTo
193
194animateTo(value: AnimateParam, event: () => void): void
195
196提供animateTo接口来指定由于闭包代码导致的状态变化插入过渡动效。
197
198**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
199
200**系统能力:** SystemCapability.ArkUI.ArkUI.Full
201
202**参数:**
203
204| 参数名   | 类型                                       | 必填   | 说明                                    |
205| ----- | ---------------------------------------- | ---- | ------------------------------------- |
206| value | [AnimateParam](arkui-ts/ts-explicit-animation.md#animateparam对象说明) | 是    | 设置动画效果相关参数。                           |
207| event | () => void                               | 是    | 指定显示动效的闭包函数,在闭包函数中导致的状态变化系统会自动插入过渡动画。 |
208
209**示例:**
210
211```ts
212// xxx.ets
213@Entry
214@Component
215struct AnimateToExample {
216  @State widthSize: number = 250
217  @State heightSize: number = 100
218  @State rotateAngle: number = 0
219  private flag: boolean = true
220  uiContext: UIContext | undefined = undefined;
221
222  aboutToAppear() {
223    this.uiContext = this.getUIContext();
224    if (!this.uiContext) {
225      console.warn("no uiContext");
226      return;
227    }
228  }
229
230  build() {
231    Column() {
232      Button('change size')
233        .width(this.widthSize)
234        .height(this.heightSize)
235        .margin(30)
236        .onClick(() => {
237          if (this.flag) {
238            this.uiContext?.animateTo({
239              duration: 2000,
240              curve: Curve.EaseOut,
241              iterations: 3,
242              playMode: PlayMode.Normal,
243              onFinish: () => {
244                console.info('play end')
245              }
246            }, () => {
247              this.widthSize = 150
248              this.heightSize = 60
249            })
250          } else {
251            this.uiContext?.animateTo({}, () => {
252              this.widthSize = 250
253              this.heightSize = 100
254            })
255          }
256          this.flag = !this.flag
257        })
258      Button('stop rotating')
259        .margin(50)
260        .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
261        .onAppear(() => {
262          // 组件出现时开始做动画
263          this.uiContext?.animateTo({
264            duration: 1200,
265            curve: Curve.Friction,
266            delay: 500,
267            iterations: -1, // 设置-1表示动画无限循环
268            playMode: PlayMode.Alternate,
269            expectedFrameRateRange: {
270              min: 10,
271              max: 120,
272              expected: 60,
273            }
274          }, () => {
275            this.rotateAngle = 90
276          })
277        })
278        .onClick(() => {
279          this.uiContext?.animateTo({ duration: 0 }, () => {
280            // this.rotateAngle之前为90,在duration为0的动画中修改属性,可以停止该属性之前的动画,按新设置的属性显示
281            this.rotateAngle = 0
282          })
283        })
284    }.width('100%').margin({ top: 5 })
285  }
286}
287```
288
289### getSharedLocalStorage<sup>12+</sup>
290
291getSharedLocalStorage(): LocalStorage | undefined
292
293获取当前stage共享的LocalStorage实例。
294
295**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
296
297**系统能力:** SystemCapability.ArkUI.ArkUI.Full
298
299**模型约束:** 此接口仅可在Stage模型下使用。
300
301**返回值:**
302
303| 类型                             | 描述                |
304| ------------------------------ | ----------------- |
305| [LocalStorage](arkui-ts/ts-state-management.md#localstorage9)&nbsp;\|&nbsp;undefined | 返回LocalStorage实例。共享的LocalStorage实例不存在时返回undefined。 |
306
307**示例:**
308
309```ts
310// index.ets
311import { router } from '@kit.ArkUI';
312
313@Entry
314@Component
315struct SharedLocalStorage {
316  localStorage = this.getUIContext().getSharedLocalStorage()
317
318  build() {
319    Row() {
320      Column() {
321        Button("Change Local Storage to 47")
322          .onClick(() => {
323            this.localStorage?.setOrCreate("propA",47)
324          })
325        Button("Get Local Storage")
326          .onClick(() => {
327            console.info(`localStorage: ${this.localStorage?.get("propA")}`)
328          })
329        Button("To Page")
330          .onClick(() => {
331            router.pushUrl({
332              url: 'pages/GetSharedLocalStorage'
333            })
334          })
335      }
336      .width('100%')
337    }
338    .height('100%')
339  }
340}
341
342// GetSharedLocalStorage.ets
343import {router} from '@kit.ArkUI';
344
345@Entry
346@Component
347struct GetSharedLocalStorage {
348  localStorage = this.getUIContext().getSharedLocalStorage()
349
350  build() {
351    Row() {
352      Column() {
353        Button("Change Local Storage to 100")
354          .onClick(() => {
355            this.localStorage?.setOrCreate("propA",100)
356          })
357        Button("Get Local Storage")
358          .onClick(() => {
359            console.info(`localStorage: ${this.localStorage?.get("propA")}`)
360          })
361
362        Button("Back Index")
363          .onClick(() => {
364            router.back()
365          })
366      }
367      .width('100%')
368    }
369  }
370}
371```
372
373### getHostContext<sup>12+</sup>
374
375getHostContext(): Context | undefined
376
377获得当前元能力的Context。
378
379**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
380
381**系统能力:** SystemCapability.ArkUI.ArkUI.Full
382
383**模型约束:** 此接口仅可在Stage模型下使用。
384
385**返回值:**
386
387| 类型 | 说明                             |
388| ------ | ------------------------------- |
389| [Context](../../application-models/application-context-stage.md#应用上下文context)&nbsp;\|&nbsp;undefined | 返回当前组件所在Ability的Context,Context的具体类型为当前Ability关联的Context对象。例如:在UIAbility窗口中的页面调用该接口,返回类型为UIAbilityContext。在ExtensionAbility窗口中的页面调用该接口,返回类型为ExtensionContext。ability上下文不存在时返回undefined。 |
390
391**示例:**
392
393```ts
394@Entry
395@Component
396struct Index {
397  uiContext = this.getUIContext();
398
399  build() {
400    Row() {
401      Column() {
402        Text("cacheDir='"+this.uiContext?.getHostContext()?.cacheDir+"'").fontSize(25)
403        Text("bundleCodeDir='"+this.uiContext?.getHostContext()?.bundleCodeDir+"'").fontSize(25)
404      }
405      .width('100%')
406    }
407    .height('100%')
408  }
409}
410```
411
412### getFrameNodeById<sup>12+</sup>
413
414getFrameNodeById(id: string): FrameNode | null
415
416通过组件的id获取组件树的实体节点。
417
418**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
419
420**系统能力:** SystemCapability.ArkUI.ArkUI.Full
421
422**参数:**
423
424| 参数名   | 类型                                       | 必填   | 说明                                    |
425| ----- | ---------------------------------------- | ---- | ------------------------------------- |
426| id | string | 是    | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。       |
427
428**返回值:**
429
430| 类型                                       | 说明            |
431| ---------------------------------------- | ------------- |
432| [FrameNode](js-apis-arkui-frameNode.md)  \| null | 返回的组件树的实体节点或者空节点。 |
433
434> **说明:**
435>
436> getFrameNodeById通过遍历查询对应id的节点,性能较差。推荐使用[getAttachedFrameNodeById](#getattachedframenodebyid12)。
437
438**示例:**
439
440```ts
441uiContext.getFrameNodeById("TestNode")
442```
443
444### getAttachedFrameNodeById<sup>12+</sup>
445
446getAttachedFrameNodeById(id: string): FrameNode | null
447
448通过组件的id获取当前窗口上的实体节点。
449
450**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
451
452**系统能力:** SystemCapability.ArkUI.ArkUI.Full
453
454**参数:**
455
456| 参数名   | 类型                                       | 必填   | 说明                                    |
457| ----- | ---------------------------------------- | ---- | ------------------------------------- |
458| id | string | 是    | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。                          |
459
460**返回值:**
461
462| 类型                                       | 说明            |
463| ---------------------------------------- | ------------- |
464| [FrameNode](js-apis-arkui-frameNode.md)  \| null | 返回的组件树的实体节点或者空节点。 |
465
466> **说明:**
467>
468> getAttachedFrameNodeById仅能查询上屏节点。
469
470**示例:**
471
472```ts
473uiContext.getAttachedFrameNodeById("TestNode")
474```
475
476### getFrameNodeByUniqueId<sup>12+</sup>
477
478getFrameNodeByUniqueId(id: number): FrameNode | null
479
480提供getFrameNodeByUniqueId接口通过组件的uniqueId获取组件树的实体节点。
4811. 当uniqueId对应的是内置组件时,返回组件所对应的FrameNode;
4822. 当uniqueId对应的是自定义组件时,若其有渲染内容,则返回其FrameNode,类型为__Common__;若其无渲染内容,则返回其第一个子组件的FrameNode。
4833. 当uniqueId无对应的组件时,返回null。
484
485**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
486
487**系统能力:** SystemCapability.ArkUI.ArkUI.Full
488
489**参数:**
490
491| 参数名   | 类型                                       | 必填   | 说明                                    |
492| ----- | ---------------------------------------- | ---- | ------------------------------------- |
493| id | number | 是    | 节点对应的UniqueId                          |
494
495**返回值:**
496
497| 类型                                       | 说明            |
498| ---------------------------------------- | ------------- |
499| [FrameNode](js-apis-arkui-frameNode.md)  \| null | 返回的组件树的实体节点或者空节点。 |
500
501**示例:**
502
503```ts
504import { UIContext, FrameNode } from '@kit.ArkUI';
505
506@Entry
507@Component
508struct MyComponent {
509  aboutToAppear() {
510    let uniqueId: number = this.getUniqueId();
511    let uiContext: UIContext = this.getUIContext();
512    if (uiContext) {
513      let node: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId);
514    }
515  }
516
517  build() {
518    // ...
519  }
520}
521```
522
523### getPageInfoByUniqueId<sup>12+</sup>
524
525getPageInfoByUniqueId(id: number): PageInfo
526
527提供getPageInfoByUniqueId接口通过组件的uniqueId获取该节点对应的Router和NavDestination页面信息。
5281. 当uniqueId对应的节点在Page节点中,routerPageInfo属性为其对应的Router信息;
5292. 当uniqueId对应的节点在NavDestination节点中,navDestinationInfo属性为其对应的NavDestination信息;
5303. 当uniqueId对应的节点无对应的Router或NavDestination信息时,对应的属性为undefined;
5314. 模态弹窗并不在任何Page节点中。当uniqueId对应的节点在模态弹窗中,例如[CustomDialog](./arkui-ts/ts-methods-custom-dialog-box.md)、[bindSheet](./arkui-ts/ts-universal-attributes-sheet-transition.md#bindsheet)和[bindContentCover](./arkui-ts/ts-universal-attributes-modal-transition.md#bindcontentcover)构建的模态页面中,routerPageInfo属性为undefined。
532
533**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
534
535**系统能力:** SystemCapability.ArkUI.ArkUI.Full
536
537**参数:**
538
539| 参数名   | 类型                                       | 必填   | 说明                                    |
540| ----- | ---------------------------------------- | ---- | ------------------------------------- |
541| id | number | 是    | 节点对应的UniqueId                          |
542
543**返回值:**
544
545| 类型                                       | 说明            |
546| ---------------------------------------- | ------------- |
547| [PageInfo](#pageinfo12) | 返回节点对应的Router和NavDestination信息。 |
548
549**示例:**
550
551```ts
552import { UIContext, PageInfo } from '@kit.ArkUI';
553
554@Entry
555@Component
556struct PageInfoExample {
557  @Provide('pageInfos') pageInfos: NavPathStack = new NavPathStack();
558
559  build() {
560    Column() {
561      Navigation(this.pageInfos) {
562        NavDestination() {
563          MyComponent()
564        }
565      }.id('navigation')
566    }
567  }
568}
569
570@Component
571struct MyComponent {
572  @State content: string = '';
573
574  build() {
575    Column() {
576      Text('PageInfoExample')
577      Button('click').onClick(() => {
578        const uiContext: UIContext = this.getUIContext();
579        const uniqueId: number = this.getUniqueId();
580        const pageInfo: PageInfo = uiContext.getPageInfoByUniqueId(uniqueId);
581        console.info('pageInfo: ' + JSON.stringify(pageInfo));
582        console.info('navigationInfo: ' + JSON.stringify(uiContext.getNavigationInfoByUniqueId(uniqueId)));
583      })
584      TextArea({
585        text: this.content
586      })
587      .width('100%')
588      .height(100)
589    }
590    .width('100%')
591    .alignItems(HorizontalAlign.Center)
592  }
593}
594```
595
596### getNavigationInfoByUniqueId<sup>12+</sup>
597
598getNavigationInfoByUniqueId(id: number): observer.NavigationInfo | undefined
599
600提供getNavigationInfoByUniqueId接口通过组件的uniqueId获取该节点对应的Navigation页面信息。
6011. 当uniqueId对应的节点在Navigation节点中,返回其对应的Navigation信息;
6022. 当uniqueId对应的节点无对应的Navigation信息时,返回undefined。
603
604**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
605
606**系统能力:** SystemCapability.ArkUI.ArkUI.Full
607
608**参数:**
609
610| 参数名   | 类型                                       | 必填   | 说明                                    |
611| ----- | ---------------------------------------- | ---- | ------------------------------------- |
612| id | number | 是    | 节点对应的UniqueId                          |
613
614**返回值:**
615
616| 类型                                       | 说明            |
617| ---------------------------------------- | ------------- |
618| observer.[NavigationInfo](js-apis-arkui-observer.md#navigationinfo12) \| undefined | 返回节点对应的Navigation信息。 |
619
620**示例:**
621
622请参考[getPageInfoByUniqueId](#getpageinfobyuniqueid12)的示例。
623
624### showAlertDialog
625
626showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions): void
627
628显示警告弹窗组件,可设置文本内容与响应回调。
629
630**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
631
632**系统能力:** SystemCapability.ArkUI.ArkUI.Full
633
634**参数:**
635
636| 参数名     | 类型                                       | 必填   | 说明                  |
637| ------- | ---------------------------------------- | ---- | ------------------- |
638| options | [AlertDialogParamWithConfirm](arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm对象说明)&nbsp;\|&nbsp;[AlertDialogParamWithButtons](arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons对象说明)&nbsp;\|&nbsp;[AlertDialogParamWithOptions](arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithoptions10对象说明) | 是    | 定义并显示AlertDialog组件。 |
639
640
641**示例:**
642
643```ts
644uiContext.showAlertDialog(
645  {
646    title: 'title',
647    message: 'text',
648    autoCancel: true,
649    alignment: DialogAlignment.Bottom,
650    offset: { dx: 0, dy: -20 },
651    gridCount: 3,
652    confirm: {
653      value: 'button',
654      action: () => {
655        console.info('Button-clicking callback')
656      }
657    },
658    cancel: () => {
659      console.info('Closed callbacks')
660    }
661  }
662)
663```
664
665### showActionSheet
666
667showActionSheet(value: ActionSheetOptions): void
668
669定义列表弹窗并弹出。
670
671**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
672
673**系统能力:** SystemCapability.ArkUI.ArkUI.Full
674
675**参数:**
676
677| 参数名 | 类型                                                         | 必填 | 说明                 |
678| ------ | ------------------------------------------------------------ | ---- | -------------------- |
679| value  | [ActionSheetOptions](arkui-ts/ts-methods-action-sheet.md#actionsheetoptions对象说明) | 是   | 配置列表弹窗的参数。 |
680
681**示例:**
682
683```ts
684uiContext.showActionSheet({
685  title: 'ActionSheet title',
686  message: 'message',
687  autoCancel: true,
688  confirm: {
689    value: 'Confirm button',
690    action: () => {
691      console.info('Get Alert Dialog handled')
692    }
693  },
694  cancel: () => {
695    console.info('actionSheet canceled')
696  },
697  alignment: DialogAlignment.Bottom,
698  offset: { dx: 0, dy: -10 },
699  sheets: [
700    {
701      title: 'apples',
702      action: () => {
703        console.info('apples')
704      }
705    },
706    {
707      title: 'bananas',
708      action: () => {
709        console.info('bananas')
710      }
711    },
712    {
713      title: 'pears',
714      action: () => {
715        console.info('pears')
716      }
717    }
718  ]
719})
720```
721
722### showDatePickerDialog
723
724showDatePickerDialog(options: DatePickerDialogOptions): void
725
726定义日期滑动选择器弹窗并弹出。
727
728**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
729
730**系统能力:** SystemCapability.ArkUI.ArkUI.Full
731
732**参数:**
733
734| 参数名  | 类型                                                         | 必填 | 说明                           |
735| ------- | ------------------------------------------------------------ | ---- | ------------------------------ |
736| options | [DatePickerDialogOptions](arkui-ts/ts-methods-datepicker-dialog.md#datepickerdialogoptions对象说明) | 是   | 配置日期滑动选择器弹窗的参数。 |
737
738**示例:**
739
740```ts
741let selectedDate: Date = new Date("2010-1-1")
742uiContext.showDatePickerDialog({
743  start: new Date("2000-1-1"),
744  end: new Date("2100-12-31"),
745  selected: selectedDate,
746  onAccept: (value: DatePickerResult) => {
747    // 通过Date的setFullYear方法设置按下确定按钮时的日期,这样当弹窗再次弹出时显示选中的是上一次确定的日期
748    selectedDate.setFullYear(Number(value.year), Number(value.month), Number(value.day))
749    console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))
750  },
751  onCancel: () => {
752    console.info("DatePickerDialog:onCancel()")
753  },
754  onChange: (value: DatePickerResult) => {
755    console.info("DatePickerDialog:onChange()" + JSON.stringify(value))
756  }
757})
758```
759
760### showTimePickerDialog
761
762showTimePickerDialog(options: TimePickerDialogOptions): void
763
764定义时间滑动选择器弹窗并弹出。
765
766**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
767
768**系统能力:** SystemCapability.ArkUI.ArkUI.Full
769
770**参数:**
771
772| 参数名  | 类型                                                         | 必填 | 说明                           |
773| ------- | ------------------------------------------------------------ | ---- | ------------------------------ |
774| options | [TimePickerDialogOptions](arkui-ts/ts-methods-timepicker-dialog.md#timepickerdialogoptions对象说明) | 是   | 配置时间滑动选择器弹窗的参数。 |
775
776**示例:**
777
778```ts
779// xxx.ets
780
781class SelectTime{
782  selectTime: Date = new Date('2020-12-25T08:30:00')
783  hours(h:number,m:number){
784    this.selectTime.setHours(h,m)
785  }
786}
787
788@Entry
789@Component
790struct TimePickerDialogExample {
791  @State selectTime: Date = new Date('2023-12-25T08:30:00');
792
793  build() {
794    Column() {
795      Button('showTimePickerDialog')
796        .margin(30)
797        .onClick(() => {
798          this.getUIContext().showTimePickerDialog({
799            selected: this.selectTime,
800            onAccept: (value: TimePickerResult) => {
801              // 设置selectTime为按下确定按钮时的时间,这样当弹窗再次弹出时显示选中的为上一次确定的时间
802              let time = new SelectTime()
803              if(value.hour&&value.minute){
804                time.hours(value.hour, value.minute)
805              }
806              console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))
807            },
808            onCancel: () => {
809              console.info("TimePickerDialog:onCancel()")
810            },
811            onChange: (value: TimePickerResult) => {
812              console.info("TimePickerDialog:onChange()" + JSON.stringify(value))
813            }
814          })
815        })
816    }.width('100%').margin({ top: 5 })
817  }
818}
819```
820
821### showTextPickerDialog
822
823showTextPickerDialog(options: TextPickerDialogOptions): void
824
825定义文本滑动选择器弹窗并弹出。
826
827**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
828
829**系统能力:** SystemCapability.ArkUI.ArkUI.Full
830
831**参数:**
832
833| 参数名  | 类型                                                         | 必填 | 说明                           |
834| ------- | ------------------------------------------------------------ | ---- | ------------------------------ |
835| options | [TextPickerDialogOptions](arkui-ts/ts-methods-textpicker-dialog.md#textpickerdialogoptions对象说明) | 是   | 配置文本滑动选择器弹窗的参数。 |
836
837**示例:**
838
839```ts
840// xxx.ets
841
842class SelectedValue{
843  select: number = 2
844  set(val:number){
845    this.select = val
846  }
847}
848class SelectedArray{
849  select: number[] = []
850  set(val:number[]){
851    this.select = val
852  }
853}
854@Entry
855@Component
856struct TextPickerDialogExample {
857  @State selectTime: Date = new Date('2023-12-25T08:30:00');
858  private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5']
859  private select : number  = 0;
860  build() {
861    Column() {
862      Button('showTextPickerDialog')
863        .margin(30)
864        .onClick(() => {
865          this.getUIContext().showTextPickerDialog({
866            range: this.fruits,
867            selected: this.select,
868            onAccept: (value: TextPickerResult) => {
869              // 设置select为按下确定按钮时候的选中项index,这样当弹窗再次弹出时显示选中的是上一次确定的选项
870              let selectedVal = new SelectedValue()
871              let selectedArr = new SelectedArray()
872              if(value.index){
873                  value.index instanceof Array?selectedArr.set(value.index) : selectedVal.set(value.index)
874              }
875              console.info("TextPickerDialog:onAccept()" + JSON.stringify(value))
876            },
877            onCancel: () => {
878              console.info("TextPickerDialog:onCancel()")
879            },
880            onChange: (value: TextPickerResult) => {
881              console.info("TextPickerDialog:onChange()" + JSON.stringify(value))
882            }
883          })
884        })
885    }.width('100%').margin({ top: 5 })
886  }
887}
888```
889
890### createAnimator
891
892createAnimator(options: AnimatorOptions): AnimatorResult
893
894定义Animator类。
895
896**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
897
898**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
899
900**参数:**
901
902| 参数名     | 类型                                       | 必填   | 说明      |
903| ------- | ---------------------------------------- | ---- | ------- |
904| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) | 是    | 定义动画选项。 |
905
906**返回值:**
907
908| 类型                                       | 说明            |
909| ---------------------------------------- | ------------- |
910| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator结果接口。 |
911
912
913**错误码**:
914
915以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
916
917| 错误码ID | 错误信息 |
918| ------- | -------- |
919| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
920
921**示例:**
922
923```ts
924import { AnimatorOptions, window } from '@kit.ArkUI';
925import { hilog } from '@kit.PerformanceAnalysisKit';
926
927// used in UIAbility
928onWindowStageCreate(windowStage: window.WindowStage) {
929  // Main window is created, set main page for this ability
930  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
931  windowStage.loadContent('pages/Index', (err, data) => {
932    if (err.code) {
933      hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
934      return;
935    }
936    hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
937    let uiContext = windowStage.getMainWindowSync().getUIContext();
938    let options:AnimatorOptions = {
939      duration: 1500,
940      easing: "friction",
941      delay: 0,
942      fill: "forwards",
943      direction: "normal",
944      iterations: 3,
945      begin: 200.0,
946      end: 400.0
947    };
948    uiContext.createAnimator(options);
949  });
950}
951```
952
953### runScopedTask
954
955runScopedTask(callback: () => void): void
956
957在当前UI上下文执行传入的回调函数。
958
959**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
960
961**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
962
963**参数:**
964
965| 参数名      | 类型         | 必填   | 说明   |
966| -------- | ---------- | ---- | ---- |
967| callback | () => void | 是    | 回调函数 |
968
969**示例:**
970
971```ts
972uiContext.runScopedTask(
973  () => {
974    console.info('Succeeded in runScopedTask');
975  }
976);
977```
978
979### setKeyboardAvoidMode<sup>11+</sup>
980
981setKeyboardAvoidMode(value: KeyboardAvoidMode): void
982
983配置虚拟键盘弹出时,页面的避让模式。
984
985**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
986
987**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
988
989**参数:**
990
991| 参数名      | 类型         | 必填   | 说明   |
992| -------- | ---------- | ---- | ---- |
993| value | [KeyboardAvoidMode](#keyboardavoidmode11)| 是    | 键盘避让时的页面避让模式。<br />默认值:KeyboardAvoidMode.OFFSET |
994
995**示例:**
996
997```ts
998import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI';
999import { hilog } from '@kit.PerformanceAnalysisKit';
1000
1001onWindowStageCreate(windowStage: window.WindowStage) {
1002    // Main window is created, set main page for this ability
1003    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
1004
1005    windowStage.loadContent('pages/Index', (err, data) => {
1006      let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext();
1007      uiContext.setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE);
1008      if (err.code) {
1009        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
1010        return;
1011      }
1012      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
1013    });
1014  }
1015```
1016
1017### getKeyboardAvoidMode<sup>11+</sup>
1018
1019getKeyboardAvoidMode(): KeyboardAvoidMode
1020
1021获取虚拟键盘弹出时,页面的避让模式。
1022
1023**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1024
1025**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1026
1027**返回值:**
1028
1029| 类型         | 说明   |
1030| ---------- | ---- |
1031| [KeyboardAvoidMode](#keyboardavoidmode11)| 返回当前的页面避让模式。|
1032
1033**示例:**
1034
1035```ts
1036import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI';
1037import { hilog } from '@kit.PerformanceAnalysisKit';
1038
1039onWindowStageCreate(windowStage: window.WindowStage) {
1040    // Main window is created, set main page for this ability
1041    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
1042
1043    windowStage.loadContent('pages/Index', (err, data) => {
1044      let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext();
1045      let KeyboardAvoidMode = uiContext.getKeyboardAvoidMode();
1046      hilog.info(0x0000, "KeyboardAvoidMode:", JSON.stringify(KeyboardAvoidMode));
1047      if (err.code) {
1048        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
1049        return;
1050      }
1051      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
1052    });
1053  }
1054
1055```
1056
1057### getAtomicServiceBar<sup>11+</sup>
1058
1059getAtomicServiceBar(): Nullable\<AtomicServiceBar>
1060
1061获取AtomicServiceBar对象,通过该对象设置原子化服务menuBar的属性。
1062
1063**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
1064
1065**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1066
1067**返回值:**
1068
1069| 类型                                              | 说明                                                         |
1070| ------------------------------------------------- | ------------------------------------------------------------ |
1071| Nullable<[AtomicServiceBar](#atomicservicebar11)> | 如果是原子化服务则返回AtomicServerBar类型,否则返回undefined。 |
1072
1073**示例:**
1074
1075```ts
1076import { UIContext, AtomicServiceBar, window } from '@kit.ArkUI';
1077import { hilog } from '@kit.PerformanceAnalysisKit';
1078onWindowStageCreate(windowStage: window.WindowStage) {
1079  // Main window is created, set main page for this ability
1080  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
1081  windowStage.loadContent('pages/Index', (err, data) => {
1082    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
1083    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
1084    if (atomicServiceBar != undefined) {
1085      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
1086    } else {
1087      hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
1088    }
1089  });
1090}
1091```
1092### getDragController<sup>11+</sup>
1093
1094getDragController(): DragController
1095
1096获取DragController对象,可通过该对象创建并发起拖拽。
1097
1098**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1099
1100**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1101
1102**返回值:**
1103
1104|类型|说明|
1105|----|----|
1106|[DragController](js-apis-arkui-dragController.md#dragController)| 获取DragController对象。|
1107
1108**示例:**
1109
1110```ts
1111uiContext.getDragController();
1112```
1113
1114### keyframeAnimateTo<sup>11+</sup>
1115
1116keyframeAnimateTo(param: KeyframeAnimateParam, keyframes: Array&lt;KeyframeState&gt;): void
1117
1118产生关键帧动画。该接口的使用说明请参考[keyframeAnimateTo](arkui-ts/ts-keyframeAnimateTo.md)。
1119
1120**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1121
1122**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1123
1124**参数:**
1125
1126| 参数名 | 类型                                              | 必填 | 说明                      |
1127| ------------ | ---------------------------------------------------- | ------- | ---------------------------- |
1128| param        | [KeyframeAnimateParam](arkui-ts/ts-keyframeAnimateTo.md#keyframeanimateparam对象说明) | 是      | 关键帧动画的整体动画参数。     |
1129| keyframes    | Array&lt;[KeyframeState](arkui-ts/ts-keyframeAnimateTo.md#keyframestate对象说明)&gt;  | 是      | 所有的关键帧状态。            |
1130
1131### getFocusController<sup>12+</sup>
1132
1133getFocusController(): FocusController
1134
1135获取[FocusController](js-apis-arkui-UIContext.md#focuscontroller12)对象,可通过该对象控制焦点。
1136
1137**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1138
1139**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1140
1141**返回值:**
1142
1143|类型|说明|
1144|----|----|
1145|[FocusController](js-apis-arkui-UIContext.md#focuscontroller12)| 获取FocusController对象。|
1146
1147**示例:**
1148
1149```ts
1150uiContext.getFocusController();
1151```
1152
1153### getFilteredInspectorTree<sup>12+</sup>
1154
1155getFilteredInspectorTree(filters?: Array\<string\>): string
1156
1157获取组件树及组件属性。
1158
1159**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1160
1161**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1162
1163**参数:**
1164
1165| 参数名  | 类型            | 必填 | 说明                                                         |
1166| ------- | --------------- | ---- | ------------------------------------------------------------ |
1167| filters | Array\<string\> | 否   | 需要获取的组件属性的过滤列表。目前仅支持过滤字段:<br/>"id":组件唯一标识。<br/>"src":资源来源。 <br/>"content":元素、组件或对象所包含的信息或数据。<br/>"editable":是否可编辑。<br/>"scrollable":是否可滚动。<br/>"selectable":是否可选择。<br/>"focusable":是否可聚焦。<br/>"focused":是否已聚焦。<br/>其余字段仅供测试场景使用。 |
1168
1169**返回值:**
1170
1171| 类型   | 说明                               |
1172| ------ | ---------------------------------- |
1173| string | 获取组件树及组件属性的JSON字符串。 |
1174
1175**错误码**:
1176
1177以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
1178
1179| 错误码ID | 错误信息 |
1180| ------- | -------- |
1181| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
1182
1183**示例:**
1184
1185```ts
1186uiContext.getFilteredInspectorTree(['id', 'src', 'content']);
1187```
1188
1189### getFilteredInspectorTreeById<sup>12+</sup>
1190
1191getFilteredInspectorTreeById(id: string, depth: number, filters?: Array\<string\>): string
1192
1193获取指定的组件及其子组件的属性。
1194
1195**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1196
1197**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1198
1199**参数:**
1200
1201| 参数名  | 类型            | 必填 | 说明                                                         |
1202| ------- | --------------- | ---- | ------------------------------------------------------------ |
1203| id      | string          | 是   | 指定的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)id。 |
1204| depth   | number          | 是   | 获取子组件的层数。当取值0时,获取指定的组件及其所有的子孙组件的属性。当取值1时,仅获取指定的组件的属性。当取值2时,指定的组件及其1层子组件的属性。以此类推。 |
1205| filters | Array\<string\> | 否   | 需要获取的组件属性的过滤列表。目前仅支持过滤字段:<br/>"id":组件唯一标识。<br/>"src":资源来源。 <br/>"content":元素、组件或对象所包含的信息或数据。<br/>"editable":是否可编辑。<br/>"scrollable":是否可滚动。<br/>"selectable":是否可选择。<br/>"focusable":是否可聚焦。<br/>"focused":是否已聚焦。<br/>其余字段仅供测试场景使用。 |
1206
1207**返回值:**
1208
1209| 类型   | 说明                                         |
1210| ------ | -------------------------------------------- |
1211| string | 获取指定的组件及其子组件的属性的JSON字符串。 |
1212
1213
1214**错误码**:
1215
1216以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
1217
1218| 错误码ID | 错误信息 |
1219| ------- | -------- |
1220| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
1221
1222**示例:**
1223
1224```ts
1225uiContext.getFilteredInspectorTreeById('testId', 0, ['id', 'src', 'content']);
1226```
1227
1228### getCursorController<sup>12+</sup>
1229
1230getCursorController(): CursorController
1231
1232获取[CursorController](js-apis-arkui-UIContext.md#cursorcontroller12)对象,可通过该对象控制光标。
1233
1234**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1235
1236**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1237
1238**返回值:**
1239
1240|类型|说明|
1241|----|----|
1242|[CursorController](js-apis-arkui-UIContext.md#cursorcontroller12)| 获取CursorController对象。|
1243
1244**示例:**
1245
1246```ts
1247uiContext.CursorController();
1248```
1249
1250### getContextMenuController<sup>12+</sup>
1251
1252getContextMenuController(): ContextMenuController
1253
1254获取[ContextMenuController](#contextmenucontroller12)对象,可通过该对象控制菜单。
1255
1256**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1257
1258**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1259
1260**返回值:**
1261
1262|类型|说明|
1263|----|----|
1264|[ContextMenuController](#contextmenucontroller12)| 获取ContextMenuController对象。|
1265
1266**示例:**
1267
1268```ts
1269uiContext.getContextMenuController();
1270```
1271
1272### getMeasureUtils<sup>12+</sup>
1273
1274getMeasureUtils(): MeasureUtils
1275
1276允许用户通过UIContext对象,获取MeasureUtils对象进行文本计算。
1277
1278**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1279
1280**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1281
1282**返回值:**
1283
1284| 类型   | 说明                                         |
1285| ------ | -------------------------------------------- |
1286| [MeasureUtils](js-apis-arkui-UIContext.md#measureutils12) | 提供文本宽度、高度等相关计算。 |
1287
1288**示例:**
1289
1290```ts
1291uiContext.getMeasureUtils();
1292```
1293
1294### getComponentSnapshot<sup>12+</sup>
1295
1296getComponentSnapshot(): ComponentSnapshot
1297
1298获取ComponentSnapshot对象,可通过该对象获取组件截图的能力。
1299
1300**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1301
1302**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1303
1304**返回值:**
1305
1306| 类型                                                         | 说明                        |
1307| ------------------------------------------------------------ | --------------------------- |
1308| [ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12) | 获取ComponentSnapshot对象。 |
1309
1310**示例:**
1311
1312```ts
1313uiContext.getComponentSnapshot();
1314```
1315
1316### vp2px<sup>12+</sup>
1317
1318vp2px(value : number) : number
1319
1320将vp单位的数值转换为以px为单位的数值。
1321
1322**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1323
1324**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1325
1326**参数:**
1327
1328| 参数名 | 类型   | 必填 | 说明                                   |
1329| ------ | ------ | ---- | -------------------------------------- |
1330| value | number | 是   | 将vp单位的数值转换为以px为单位的数值。 |
1331
1332**返回值:**
1333
1334| 类型   | 说明           |
1335| ------ | -------------- |
1336| number | 转换后的数值。 |
1337
1338**示例:**
1339
1340```tx
1341uiContext.vp2px(200);
1342```
1343
1344### px2vp<sup>12+</sup>
1345
1346px2vp(value : number) : number
1347
1348将px单位的数值转换为以vp为单位的数值。
1349
1350**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1351
1352**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1353
1354**参数:**
1355
1356| 参数名 | 类型   | 必填 | 说明                                   |
1357| ------ | ------ | ---- | -------------------------------------- |
1358| value | number | 是   | 将px单位的数值转换为以vp为单位的数值。 |
1359
1360**返回值:**
1361
1362| 类型   | 说明           |
1363| ------ | -------------- |
1364| number | 转换后的数值。 |
1365
1366**示例:**
1367
1368```tx
1369uiContext.px2vp(200);
1370```
1371
1372### fp2px<sup>12+</sup>
1373
1374fp2px(value : number) : number
1375
1376将fp单位的数值转换为以px为单位的数值。
1377
1378**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1379
1380**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1381
1382**参数:**
1383
1384| 参数名 | 类型   | 必填 | 说明                                   |
1385| ------ | ------ | ---- | -------------------------------------- |
1386| value | number | 是   | 将fp单位的数值转换为以px为单位的数值。 |
1387
1388**返回值:**
1389
1390| 类型   | 说明           |
1391| ------ | -------------- |
1392| number | 转换后的数值。 |
1393
1394**示例:**
1395
1396```tx
1397uiContext.fp2px(200);
1398```
1399
1400### px2fp<sup>12+</sup>
1401
1402px2fp(value : number) : number
1403
1404将px单位的数值转换为以fp为单位的数值。
1405
1406**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1407
1408**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1409
1410**参数:**
1411
1412| 参数名 | 类型   | 必填 | 说明                                   |
1413| ------ | ------ | ---- | -------------------------------------- |
1414| value | number | 是   | 将px单位的数值转换为以fp为单位的数值。 |
1415
1416**返回值:**
1417
1418| 类型   | 说明           |
1419| ------ | -------------- |
1420| number | 转换后的数值。 |
1421
1422**示例:**
1423
1424```tx
1425uiContext.px2fp(200);
1426```
1427
1428### lpx2px<sup>12+</sup>
1429
1430lpx2px(value : number) : number
1431
1432将lpx单位的数值转换为以px为单位的数值。
1433
1434**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1435
1436**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1437
1438**参数:**
1439
1440| 参数名 | 类型   | 必填 | 说明                                    |
1441| ------ | ------ | ---- | --------------------------------------- |
1442| value | number | 是   | 将lpx单位的数值转换为以px为单位的数值。 |
1443
1444**返回值:**
1445
1446| 类型   | 说明           |
1447| ------ | -------------- |
1448| number | 转换后的数值。 |
1449
1450**示例:**
1451
1452```tx
1453uiContext.lpx2px(200);
1454```
1455
1456### px2lpx<sup>12+</sup>
1457
1458px2lpx(value : number) : number
1459
1460将px单位的数值转换为以lpx为单位的数值。
1461
1462**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1463
1464**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1465
1466**参数:**
1467
1468| 参数名 | 类型   | 必填 | 说明                                    |
1469| ------ | ------ | ---- | --------------------------------------- |
1470| value | number | 是   | 将px单位的数值转换为以lpx为单位的数值。 |
1471
1472**返回值:**
1473
1474| 类型   | 说明           |
1475| ------ | -------------- |
1476| number | 转换后的数值。 |
1477
1478**示例:**
1479
1480```tx
1481uiContext.px2lpx(200);
1482```
1483
1484### getWindowName<sup>12+</sup>
1485
1486getWindowName(): string | undefined
1487
1488获取当前实例所在窗口的名称。
1489
1490**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1491
1492**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1493
1494**返回值:**
1495
1496| 类型   | 说明                                         |
1497| ------ | -------------------------------------------- |
1498| string \| undefined | 当前实例所在窗口的名称。若窗口不存在,则返回undefined。 |
1499
1500**示例:**
1501
1502```ts
1503import { window } from '@kit.ArkUI';
1504
1505@Entry
1506@Component
1507struct Index {
1508  @State message: string = 'Hello World'
1509
1510  aboutToAppear() {
1511    const windowName = this.getUIContext().getWindowName();
1512    console.info('WindowName ' + windowName);
1513    const currWindow = window.findWindow(windowName);
1514    const windowProperties = currWindow.getWindowProperties();
1515    console.info(`Window width ${windowProperties.windowRect.width}, height ${windowProperties.windowRect.height}`);
1516  }
1517
1518  build() {
1519    Row() {
1520      Column() {
1521        Text(this.message)
1522          .fontSize(50)
1523          .fontWeight(FontWeight.Bold)
1524      }
1525      .width('100%')
1526    }
1527    .height('100%')
1528  }
1529}
1530```
1531
1532### getWindowWidthBreakpoint<sup>13+</sup>
1533
1534getWindowWidthBreakpoint(): WidthBreakpoint
1535
1536获取当前实例所在窗口的宽度断点枚举值。具体枚举值根据窗口宽度vp值确定,详见 [WidthBreakpoint](./arkui-ts/ts-appendix-enums.md#widthbreakpoint13)。
1537
1538**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
1539
1540**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1541
1542**返回值:**
1543
1544| 类型   | 说明                                         |
1545| ------ | -------------------------------------------- |
1546| [WidthBreakpoint](./arkui-ts/ts-appendix-enums.md#widthbreakpoint13) | 当前实例所在窗口的宽度断点枚举值。若窗口宽度为 0vp,则返回WIDTH_XS。 |
1547
1548**示例:**
1549
1550```ts
1551import { UIContext } from '@kit.ArkUI';
1552
1553@Entry
1554@Component
1555struct Index {
1556  @State message: string = 'Hello World';
1557
1558  build() {
1559    Row() {
1560      Column() {
1561        Text(this.message)
1562          .fontSize(30)
1563          .fontWeight(FontWeight.Bold)
1564        Button() {
1565          Text('test')
1566            .fontSize(30)
1567        }
1568        .onClick(() => {
1569          let uiContext: UIContext = this.getUIContext();
1570          let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint();
1571          let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint();
1572          console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`)
1573        })
1574      }
1575      .width('100%')
1576    }
1577    .height('100%')
1578  }
1579}
1580```
1581
1582### getWindowHeightBreakpoint<sup>13+</sup>
1583
1584getWindowHeightBreakpoint(): HeightBreakpoint
1585
1586获取当前实例所在窗口的高度断点。具体枚举值根据窗口高宽比确定,详见 [HeightBreakpoint](./arkui-ts/ts-appendix-enums.md#heightbreakpoint13)。
1587
1588**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
1589
1590**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
1591
1592**返回值:**
1593
1594| 类型   | 说明                                         |
1595| ------ | -------------------------------------------- |
1596| [HeightBreakpoint](./arkui-ts/ts-appendix-enums.md#heightbreakpoint13) | 当前实例所在窗口的宽高比对应的高度断点枚举值。若窗口高宽比为0,则返回HEIGHT_SM。 |
1597
1598**示例:**
1599
1600```ts
1601import { UIContext } from '@kit.ArkUI';
1602
1603@Entry
1604@Component
1605struct Index {
1606  @State message: string = 'Hello World';
1607
1608  build() {
1609    Row() {
1610      Column() {
1611        Text(this.message)
1612          .fontSize(30)
1613          .fontWeight(FontWeight.Bold)
1614        Button() {
1615          Text('test')
1616            .fontSize(30)
1617        }
1618        .onClick(() => {
1619          let uiContext: UIContext = this.getUIContext();
1620          let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint();
1621          let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint();
1622          console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`)
1623        })
1624      }
1625      .width('100%')
1626    }
1627    .height('100%')
1628  }
1629}
1630```
1631
1632### postFrameCallback<sup>12+</sup>
1633
1634postFrameCallback(frameCallback: FrameCallback): void
1635
1636注册一个在下一帧进行渲染时执行的回调。
1637
1638**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1639
1640**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1641
1642**参数:**
1643
1644| 参数名 | 类型   | 必填 | 说明                                    |
1645| ------ | ------ | ---- | --------------------------------------- |
1646| frameCallback | [FrameCallback](#framecallback12) | 是   | 下一帧需要执行的回调。 |
1647
1648**示例:**
1649
1650```ts
1651import {FrameCallback } from '@kit.ArkUI';
1652
1653class MyFrameCallback extends FrameCallback {
1654  private tag: string;
1655
1656  constructor(tag: string) {
1657    super()
1658    this.tag = tag;
1659  }
1660
1661  onFrame(frameTimeNanos: number) {
1662    console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString());
1663  }
1664}
1665
1666@Entry
1667@Component
1668struct Index {
1669  build() {
1670    Row() {
1671      Button('点击触发postFrameCallback')
1672        .onClick(() => {
1673          this.getUIContext().postFrameCallback(new MyFrameCallback("normTask"));
1674        })
1675    }
1676  }
1677}
1678```
1679
1680### postDelayedFrameCallback<sup>12+</sup>
1681
1682postDelayedFrameCallback(frameCallback: FrameCallback, delayTime: number): void
1683
1684注册一个回调,在延迟一段时间后的下一帧进行渲染时执行。
1685
1686**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1687
1688**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1689
1690**参数:**
1691
1692| 参数名 | 类型   | 必填 | 说明                                    |
1693| ------ | ------ | ---- | --------------------------------------- |
1694| frameCallback | [FrameCallback](#framecallback12) | 是   | 下一帧需要执行的回调。 |
1695| delayTime | number | 是   | 延迟的时间,以毫秒为单位。传入null、undefined或小于0的值,会按0处理。 |
1696
1697**示例:**
1698
1699```ts
1700import {FrameCallback } from '@kit.ArkUI';
1701
1702class MyFrameCallback extends FrameCallback {
1703  private tag: string;
1704
1705  constructor(tag: string) {
1706    super()
1707    this.tag = tag;
1708  }
1709
1710  onFrame(frameTimeNanos: number) {
1711    console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString());
1712  }
1713}
1714
1715@Entry
1716@Component
1717struct Index {
1718  build() {
1719    Row() {
1720      Button('点击触发postDelayedFrameCallback')
1721        .onClick(() => {
1722          this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5);
1723        })
1724    }
1725  }
1726}
1727```
1728
1729### requireDynamicSyncScene<sup>12+</sup>
1730
1731requireDynamicSyncScene(id: string): Array&lt;DynamicSyncScene&gt;
1732
1733请求组件的动态帧率场景,用于自定义场景相关帧率配置。
1734
1735**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1736
1737**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1738
1739**参数:**
1740
1741| 参数名 | 类型   | 必填 | 说明                                    |
1742| ------ | ------ | ---- | --------------------------------------- |
1743| id | string | 是    | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)
1744
1745**返回值:**
1746
1747| 类型   | 说明                                         |
1748| ------ | -------------------------------------------- |
1749| Array&lt;DynamicSyncScene&gt; | 获取DynamicSyncScene对象数组。 |
1750
1751**示例:**
1752```ts
1753uiContext.DynamicSyncScene("dynamicSyncScene")
1754```
1755
1756### openBindSheet<sup>12+</sup>
1757
1758openBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions?: SheetOptions, targetId?: number): Promise&lt;void&gt;
1759
1760创建并弹出以bindSheetContent作为内容的半模态页面,使用Promise异步回调。通过该接口弹出的半模态页面样式完全按照bindSheetContent中设置的样式显示。
1761
1762> **说明:**
1763>
1764> 1. 使用该接口时,若未传入有效的targetId,则不支持设置SheetOptions.preferType为POPUP模式、不支持设置SheetOptions.mode为EMBEDDED模式。
1765>
1766> 2. 由于[updateBindSheet](#updatebindsheet12)和[closeBindSheet](#closebindsheet12)依赖bindSheetContent去更新或者关闭指定的半模态页面,开发者需自行维护传入的bindSheetContent。
1767>
1768> 3. 不支持设置SheetOptions.UIContext1769>
1770
1771**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1772
1773**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1774
1775**参数:**
1776
1777| 参数名     | 类型                                       | 必填   | 说明      |
1778| ------- | ---------------------------------------- | ---- | ------- |
1779| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 |
1780| sheetOptions | [SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions) | 否    |   半模态页面样式。<br/>**说明:** <br/>1. 不支持设置SheetOptions.uiContext,该属性的值固定为当前实例的UIContext。<br/>2. 若不传递targetId,则不支持设置SheetOptions.preferType为POPUP样式,若设置了POPUP样式则使用CENTER样式替代。<br/>3. 若不传递targetId,则不支持设置SheetOptions.mode为EMBEDDED模式,默认为OVERLAY模式。<br/>4. 其余属性的默认值参考[SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions)文档。 |
1781| targetId | number | 否    |   需要绑定组件的ID,若不指定则不绑定任何组件。 |
1782
1783**返回值:**
1784
1785| 类型                                       | 说明      |
1786| ---------------------------------------- | ------- |
1787|   Promise&lt;void&gt;           |    异常返回Promise对象。 |
1788
1789**错误码:**
1790
1791以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。
1792
1793| 错误码ID  | 错误信息                               |
1794| ------ | ---------------------------------- |
1795| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
1796| 120001 | The bindSheetContent is incorrect. |
1797| 120002 | The bindSheetContent already exists. |
1798| 120004 | The targetId does not exist. |
1799| 120005 | The node of targetId is not in the component tree. |
1800| 120006 | The node of targetId is not a child of the page node or NavDestination node. |
1801
1802**示例:**
1803
1804```ts
1805import { FrameNode, ComponentContent } from "@kit.ArkUI";
1806import { BusinessError } from '@kit.BasicServicesKit';
1807
1808class Params {
1809  text: string = ""
1810
1811  constructor(text: string) {
1812    this.text = text;
1813  }
1814}
1815
1816let contentNode: ComponentContent<Params>;
1817let gUIContext: UIContext;
1818
1819@Builder
1820function buildText(params: Params) {
1821  Column() {
1822    Text(params.text)
1823    Button('Update BindSheet')
1824      .fontSize(20)
1825      .onClick(() => {
1826        gUIContext.updateBindSheet(contentNode, {
1827          backgroundColor: Color.Pink,
1828        }, true)
1829          .then(() => {
1830            console.info('updateBindSheet success');
1831          })
1832          .catch((err: BusinessError) => {
1833            console.info('updateBindSheet error: ' + err.code + ' ' + err.message);
1834          })
1835      })
1836
1837    Button('Close BindSheet')
1838      .fontSize(20)
1839      .onClick(() => {
1840        gUIContext.closeBindSheet(contentNode)
1841          .then(() => {
1842            console.info('closeBindSheet success');
1843          })
1844          .catch((err: BusinessError) => {
1845            console.info('closeBindSheet error: ' + err.code + ' ' + err.message);
1846          })
1847      })
1848  }
1849}
1850
1851@Entry
1852@Component
1853struct UIContextBindSheet {
1854  @State message: string = 'BindSheet';
1855
1856  aboutToAppear() {
1857    gUIContext = this.getUIContext();
1858    contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message));
1859  }
1860
1861  build() {
1862    RelativeContainer() {
1863      Column() {
1864        Button('Open BindSheet')
1865          .fontSize(20)
1866          .onClick(() => {
1867            let uiContext = this.getUIContext();
1868            let uniqueId = this.getUniqueId();
1869            let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId);
1870            let targetId = frameNode?.getFirstChild()?.getUniqueId();
1871            uiContext.openBindSheet(contentNode, {
1872              height: SheetSize.MEDIUM,
1873              backgroundColor: Color.Green,
1874              title: { title: "Title", subtitle: "subtitle" }
1875            }, targetId)
1876              .then(() => {
1877                console.info('openBindSheet success');
1878              })
1879              .catch((err: BusinessError) => {
1880                console.info('openBindSheet error: ' + err.code + ' ' + err.message);
1881              })
1882          })
1883      }
1884    }
1885    .height('100%')
1886    .width('100%')
1887  }
1888}
1889```
1890
1891### updateBindSheet<sup>12+</sup>
1892
1893updateBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions: SheetOptions, partialUpdate?: boolean ): Promise&lt;void&gt;
1894
1895更新bindSheetContent对应的半模态页面的样式,使用Promise异步回调。
1896
1897> **说明:**
1898>
1899> 不支持更新SheetOptions.UIContextSheetOptions.mode、回调函数。
1900>
1901
1902**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1903
1904**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1905
1906**参数:**
1907
1908| 参数名     | 类型                                       | 必填   | 说明      |
1909| ------- | ---------------------------------------- | ---- | ------- |
1910| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 |
1911| sheetOptions | [SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions) | 是    |   半模态页面样式。<br/>**说明:** <br/>不支持更新SheetOptions.uiContextSheetOptions.mode、回调函数。 |
1912| partialUpdate | boolean | 否    |   半模态页面更新方式, 默认值为false。<br/>**说明:** <br/>1. true为增量更新,保留当前值,更新SheetOptions中的指定属性。 <br/>2. false为全量更新,除SheetOptions中的指定属性,其他属性恢复默认值。 |
1913
1914**返回值:**
1915
1916| 类型                                       | 说明      |
1917| ---------------------------------------- | ------- |
1918|   Promise&lt;void&gt;           |    异常返回Promise对象。 |
1919
1920**错误码:**
1921
1922以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。
1923
1924| 错误码ID  | 错误信息                               |
1925| ------ | ---------------------------------- |
1926| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
1927| 120001 | The bindSheetContent is incorrect. |
1928| 120003 | The bindSheetContent cannot be found. |
1929
1930**示例:**
1931
1932```ts
1933import { FrameNode, ComponentContent } from "@kit.ArkUI";
1934import { BusinessError } from '@kit.BasicServicesKit';
1935
1936class Params {
1937  text: string = ""
1938
1939  constructor(text: string) {
1940    this.text = text;
1941  }
1942}
1943
1944let contentNode: ComponentContent<Params>;
1945let gUIContext: UIContext;
1946
1947@Builder
1948function buildText(params: Params) {
1949  Column() {
1950    Text(params.text)
1951    Button('Update BindSheet')
1952      .fontSize(20)
1953      .onClick(() => {
1954        gUIContext.updateBindSheet(contentNode, {
1955          backgroundColor: Color.Pink,
1956        }, true)
1957          .then(() => {
1958            console.info('updateBindSheet success');
1959          })
1960          .catch((err: BusinessError) => {
1961            console.info('updateBindSheet error: ' + err.code + ' ' + err.message);
1962          })
1963      })
1964
1965    Button('Close BindSheet')
1966      .fontSize(20)
1967      .onClick(() => {
1968        gUIContext.closeBindSheet(contentNode)
1969          .then(() => {
1970            console.info('closeBindSheet success');
1971          })
1972          .catch((err: BusinessError) => {
1973            console.info('closeBindSheet error: ' + err.code + ' ' + err.message);
1974          })
1975      })
1976  }
1977}
1978
1979@Entry
1980@Component
1981struct UIContextBindSheet {
1982  @State message: string = 'BindSheet';
1983
1984  aboutToAppear() {
1985    gUIContext = this.getUIContext();
1986    contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message));
1987  }
1988
1989  build() {
1990    RelativeContainer() {
1991      Column() {
1992        Button('Open BindSheet')
1993          .fontSize(20)
1994          .onClick(() => {
1995            let uiContext = this.getUIContext();
1996            let uniqueId = this.getUniqueId();
1997            let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId);
1998            let targetId = frameNode?.getFirstChild()?.getUniqueId();
1999            uiContext.openBindSheet(contentNode, {
2000              height: SheetSize.MEDIUM,
2001              backgroundColor: Color.Green,
2002              title: { title: "Title", subtitle: "subtitle" }
2003            }, targetId)
2004              .then(() => {
2005                console.info('openBindSheet success');
2006              })
2007              .catch((err: BusinessError) => {
2008                console.info('openBindSheet error: ' + err.code + ' ' + err.message);
2009              })
2010          })
2011      }
2012    }
2013    .height('100%')
2014    .width('100%')
2015  }
2016}
2017```
2018
2019### closeBindSheet<sup>12+</sup>
2020
2021closeBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>): Promise&lt;void&gt;
2022
2023关闭bindSheetContent对应的半模态页面,使用Promise异步回调。
2024
2025> **说明:**
2026>
2027> 使用此接口关闭半模态页面时,不会触发shouldDismiss回调。
2028>
2029
2030**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2031
2032**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2033
2034**参数:**
2035
2036| 参数名     | 类型                                       | 必填   | 说明      |
2037| ------- | ---------------------------------------- | ---- | ------- |
2038| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 |
2039
2040**返回值:**
2041
2042| 类型                                       | 说明      |
2043| ---------------------------------------- | ------- |
2044|   Promise&lt;void&gt;           |    异常返回Promise对象。 |
2045
2046**错误码:**
2047
2048以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。
2049
2050| 错误码ID  | 错误信息                               |
2051| ------ | ---------------------------------- |
2052| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
2053| 120001 | The bindSheetContent is incorrect. |
2054| 120003 | The bindSheetContent cannot be found. |
2055
2056**示例:**
2057
2058```ts
2059import { FrameNode, ComponentContent } from "@kit.ArkUI";
2060import { BusinessError } from '@kit.BasicServicesKit';
2061
2062class Params {
2063  text: string = ""
2064
2065  constructor(text: string) {
2066    this.text = text;
2067  }
2068}
2069
2070let contentNode: ComponentContent<Params>;
2071let gUIContext: UIContext;
2072
2073@Builder
2074function buildText(params: Params) {
2075  Column() {
2076    Text(params.text)
2077    Button('Update BindSheet')
2078      .fontSize(20)
2079      .onClick(() => {
2080        gUIContext.updateBindSheet(contentNode, {
2081          backgroundColor: Color.Pink,
2082        }, true)
2083          .then(() => {
2084            console.info('updateBindSheet success');
2085          })
2086          .catch((err: BusinessError) => {
2087            console.info('updateBindSheet error: ' + err.code + ' ' + err.message);
2088          })
2089      })
2090
2091    Button('Close BindSheet')
2092      .fontSize(20)
2093      .onClick(() => {
2094        gUIContext.closeBindSheet(contentNode)
2095          .then(() => {
2096            console.info('closeBindSheet success');
2097          })
2098          .catch((err: BusinessError) => {
2099            console.info('closeBindSheet error: ' + err.code + ' ' + err.message);
2100          })
2101      })
2102  }
2103}
2104
2105@Entry
2106@Component
2107struct UIContextBindSheet {
2108  @State message: string = 'BindSheet';
2109
2110  aboutToAppear() {
2111    gUIContext = this.getUIContext();
2112    contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message));
2113  }
2114
2115  build() {
2116    RelativeContainer() {
2117      Column() {
2118        Button('Open BindSheet')
2119          .fontSize(20)
2120          .onClick(() => {
2121            let uiContext = this.getUIContext();
2122            let uniqueId = this.getUniqueId();
2123            let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId);
2124            let targetId = frameNode?.getFirstChild()?.getUniqueId();
2125            uiContext.openBindSheet(contentNode, {
2126              height: SheetSize.MEDIUM,
2127              backgroundColor: Color.Green,
2128              title: { title: "Title", subtitle: "subtitle" }
2129            }, targetId)
2130              .then(() => {
2131                console.info('openBindSheet success');
2132              })
2133              .catch((err: BusinessError) => {
2134                console.info('openBindSheet error: ' + err.code + ' ' + err.message);
2135              })
2136          })
2137      }
2138    }
2139    .height('100%')
2140    .width('100%')
2141  }
2142}
2143```
2144
2145### isFollowingSystemFontScale<sup>13+</sup>
2146
2147isFollowingSystemFontScale(): boolean
2148
2149获取当前UI上下文是否跟随系统字体倍率。
2150
2151**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
2152
2153**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2154
2155**返回值:**
2156
2157| 类型      | 说明            |
2158|---------|---------------|
2159| boolean | 当前UI上下文是否跟随系统字体倍率。 |
2160
2161**示例:**
2162```ts
2163uiContext.isFollowingSystemFontScale()
2164```
2165
2166### getMaxFontScale<sup>13+</sup>
2167
2168getMaxFontScale(): number
2169
2170获取当前UI上下文最大字体倍率。
2171
2172**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
2173
2174**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2175
2176**返回值:**
2177
2178| 类型      | 说明        |
2179|---------|-----------|
2180| number | 当前UI上下文最大字体倍率。 |
2181
2182**示例:**
2183```ts
2184uiContext.getMaxFontScale()
2185```
2186
2187### bindTabsToScrollable<sup>13+</sup>
2188
2189bindTabsToScrollable(tabsController: TabsController, scroller: Scroller): void;
2190
2191绑定Tabs组件和可滚动容器组件(支持[List](./arkui-ts/ts-container-list.md)、[Scroll](./arkui-ts/ts-container-scroll.md)、[Grid](./arkui-ts/ts-container-grid.md)、[WaterFlow](./arkui-ts/ts-container-waterflow.md)),当滑动可滚动容器组件时,会触发所有与其绑定的Tabs组件的TabBar的显示和隐藏动效。一个TabsController可与多个Scroller绑定,一个Scroller也可与多个TabsController绑定。
2192
2193>  **说明:**
2194>
2195>  当多个可滚动容器组件绑定了同一个Tabs组件时,只要滑动任意一个可滚动容器组件,就会触发TabBar的显示或隐藏。且当任意一个可滚动容器组件滑动到底部时,会立即触发TabBar的显示动效。因此不建议同时触发多个可滚动容器组件的滑动。
2196
2197**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
2198
2199**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2200
2201**参数:**
2202
2203| 参数名     | 类型                                       | 必填   | 说明      |
2204| ------- | ---------------------------------------- | ---- | ------- |
2205| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 |
2206| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 |
2207
2208**示例:**
2209
2210```ts
2211@Entry
2212@Component
2213struct TabsExample {
2214  private arr: string[] = []
2215  private parentTabsController: TabsController = new TabsController()
2216  private childTabsController: TabsController = new TabsController()
2217  private listScroller: Scroller = new Scroller()
2218  private parentScroller: Scroller = new Scroller()
2219  private childScroller: Scroller = new Scroller()
2220
2221  aboutToAppear(): void {
2222    for (let i = 0; i < 20; i++) {
2223      this.arr.push(i.toString())
2224    }
2225    let context = this.getUIContext()
2226    context.bindTabsToScrollable(this.parentTabsController, this.listScroller)
2227    context.bindTabsToScrollable(this.childTabsController, this.listScroller)
2228    context.bindTabsToNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller)
2229  }
2230
2231  aboutToDisappear(): void {
2232    let context = this.getUIContext()
2233    context.unbindTabsFromScrollable(this.parentTabsController, this.listScroller)
2234    context.unbindTabsFromScrollable(this.childTabsController, this.listScroller)
2235    context.unbindTabsFromNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller)
2236  }
2237
2238  build() {
2239    Tabs({ barPosition: BarPosition.End, controller: this.parentTabsController }) {
2240      TabContent() {
2241        Tabs({ controller: this.childTabsController }) {
2242          TabContent() {
2243            List({ space: 20, initialIndex: 0, scroller: this.listScroller }) {
2244              ForEach(this.arr, (item: string) => {
2245                ListItem() {
2246                  Text(item)
2247                    .width('100%')
2248                    .height(100)
2249                    .fontSize(16)
2250                    .textAlign(TextAlign.Center)
2251                    .borderRadius(10)
2252                    .backgroundColor(Color.Gray)
2253                }
2254              }, (item: string) => item)
2255            }
2256            .scrollBar(BarState.Off)
2257            .width('90%')
2258            .height('100%')
2259            .contentStartOffset(56)
2260            .contentEndOffset(52)
2261          }.tabBar(SubTabBarStyle.of('顶部页签'))
2262        }
2263        .width('100%')
2264        .height('100%')
2265        .barOverlap(true) // 使TabBar叠加在TabContent上,当TabBar向上或向下隐藏后,原位置处不为空白
2266        .clip(true) // 对超出Tabs组件范围的子组件进行裁剪,防止TabBar向上或向下隐藏后误触TabBar
2267      }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), 'scroller联动多个TabsController'))
2268
2269      TabContent() {
2270        Scroll(this.parentScroller) {
2271            List({ space: 20, initialIndex: 0, scroller: this.childScroller }) {
2272              ForEach(this.arr, (item: string) => {
2273                ListItem() {
2274                  Text(item)
2275                    .width('100%')
2276                    .height(100)
2277                    .fontSize(16)
2278                    .textAlign(TextAlign.Center)
2279                    .borderRadius(10)
2280                    .backgroundColor(Color.Gray)
2281                }
2282              }, (item: string) => item)
2283            }
2284            .scrollBar(BarState.Off)
2285            .width('90%')
2286            .height('100%')
2287            .contentEndOffset(52)
2288            .nestedScroll({ scrollForward: NestedScrollMode.SELF_FIRST, scrollBackward: NestedScrollMode.SELF_FIRST })
2289        }
2290        .width('100%')
2291        .height('100%')
2292        .scrollBar(BarState.Off)
2293        .scrollable(ScrollDirection.Vertical)
2294        .edgeEffect(EdgeEffect.Spring)
2295      }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), '嵌套的scroller联动TabsController'))
2296    }
2297    .width('100%')
2298    .height('100%')
2299    .barOverlap(true) // 使TabBar叠加在TabContent上,当TabBar向上或向下隐藏后,原位置处不为空白
2300    .clip(true) // 对超出Tabs组件范围的子组件进行裁剪,防止TabBar向上或向下隐藏后误触TabBar
2301  }
2302}
2303```
2304
2305![bindTabsToScrollable](figures/bindTabsToScrollable.gif)
2306
2307### unbindTabsFromScrollable<sup>13+</sup>
2308
2309unbindTabsFromScrollable(tabsController: TabsController, scroller: Scroller): void;
2310
2311解除Tabs组件和可滚动容器组件的绑定。
2312
2313**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
2314
2315**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2316
2317**参数:**
2318
2319| 参数名     | 类型                                       | 必填   | 说明      |
2320| ------- | ---------------------------------------- | ---- | ------- |
2321| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 |
2322| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 |
2323
2324**示例:**
2325
2326参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。
2327
2328### bindTabsToNestedScrollable<sup>13+</sup>
2329
2330bindTabsToNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void;
2331
2332绑定Tabs组件和嵌套的可滚动容器组件(支持[List](./arkui-ts/ts-container-list.md)、[Scroll](./arkui-ts/ts-container-scroll.md)、[Grid](./arkui-ts/ts-container-grid.md)、[WaterFlow](./arkui-ts/ts-container-waterflow.md)),当滑动父组件或子组件时,会触发所有与其绑定的Tabs组件的TabBar的显示和隐藏动效。一个TabsController可与多个嵌套的Scroller绑定,嵌套的Scroller也可与多个TabsController绑定。
2333
2334**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
2335
2336**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2337
2338**参数:**
2339
2340| 参数名     | 类型                                       | 必填   | 说明      |
2341| ------- | ---------------------------------------- | ---- | ------- |
2342| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 |
2343| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 |
2344| childScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。其对应组件为parentScroller对应组件的子组件,且组件间存在嵌套滚动关系。 |
2345
2346**示例:**
2347
2348参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。
2349
2350### unbindTabsFromNestedScrollable<sup>13+</sup>
2351
2352unbindTabsFromNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void;
2353
2354解除Tabs组件和嵌套的可滚动容器组件的绑定。
2355
2356**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
2357
2358**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2359
2360**参数:**
2361
2362| 参数名     | 类型                                       | 必填   | 说明      |
2363| ------- | ---------------------------------------- | ---- | ------- |
2364| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 |
2365| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 |
2366| childScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。其对应组件为parentScroller对应组件的子组件,且组件间存在嵌套滚动关系。 |
2367
2368**示例:**
2369
2370参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。
2371
2372## Font
2373
2374以下API需先使用UIContext中的[getFont()](#getfont)方法获取到Font对象,再通过该对象调用对应方法。
2375
2376### registerFont
2377
2378registerFont(options: font.FontOptions): void
2379
2380在字体管理中注册自定义字体。
2381
2382**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2383
2384**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2385
2386**参数:**
2387
2388| 参数名     | 类型                                       | 必填   | 说明          |
2389| ------- | ---------------------------------------- | ---- | ----------- |
2390| options | [font.FontOptions](js-apis-font.md#fontoptions) | 是    | 注册的自定义字体信息。 |
2391
2392**示例:**
2393
2394```ts
2395import { Font } from '@kit.ArkUI';
2396
2397let font:Font = uiContext.getFont();
2398font.registerFont({
2399  familyName: 'medium',
2400  familySrc: '/font/medium.ttf'
2401});
2402```
2403### getSystemFontList
2404
2405getSystemFontList(): Array\<string>
2406
2407获取系统支持的字体名称列表。
2408
2409**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2410
2411**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2412
2413**返回值:**
2414
2415| 类型             | 说明        |
2416| -------------- | --------- |
2417| Array\<string> | 系统的字体名列表。 |
2418
2419>  **说明:**
2420>
2421>  该接口仅在2in1设备上生效。
2422
2423**示例:**
2424
2425```ts
2426import { Font } from '@kit.ArkUI';
2427
2428let font:Font|undefined = uiContext.getFont();
2429if(font){
2430  font.getSystemFontList()
2431}
2432```
2433
2434### getFontByName
2435
2436getFontByName(fontName: string): font.FontInfo
2437
2438根据传入的系统字体名称获取系统字体的相关信息。
2439
2440**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2441
2442**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2443
2444**参数:**
2445
2446| 参数名      | 类型     | 必填   | 说明      |
2447| -------- | ------ | ---- | ------- |
2448| fontName | string | 是    | 系统的字体名。 |
2449
2450**返回值:**
2451
2452| 类型                                      | 说明           |
2453| ----------------------------------------- | -------------- |
2454| [font.FontInfo](js-apis-font.md#fontinfo) | 字体的详细信息 |
2455
2456**示例:**
2457
2458```ts
2459import { Font } from '@kit.ArkUI';
2460
2461let font:Font|undefined = uiContext.getFont();
2462if(font){
2463  font.getFontByName('Sans Italic')
2464}
2465```
2466
2467## ComponentUtils
2468
2469以下API需先使用UIContext中的[getComponentUtils()](#getcomponentutils)方法获取到ComponentUtils对象,再通过该对象调用对应方法。
2470
2471### getRectangleById
2472
2473getRectangleById(id: string): componentUtils.ComponentInfo
2474
2475获取组件大小、位置、平移缩放旋转及仿射矩阵属性信息。
2476
2477**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2478
2479**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2480
2481**参数:**
2482
2483| 参数名  | 类型     | 必填   | 说明        |
2484| ---- | ------ | ---- | --------- |
2485| id   | string | 是    | 组件唯一标识id。 |
2486
2487**返回值:**
2488
2489| 类型                                                         | 说明                                             |
2490| ------------------------------------------------------------ | ------------------------------------------------ |
2491| [componentUtils.ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | 组件大小、位置、平移缩放旋转及仿射矩阵属性信息。 |
2492
2493**错误码:**
2494
2495以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
2496
2497| 错误码ID  | 错误信息                |
2498| ------ | ------------------- |
2499| 100001 | UI execution context not found. |
2500
2501**示例:**
2502
2503```ts
2504import { ComponentUtils } from '@kit.ArkUI';
2505
2506let componentUtils:ComponentUtils = uiContext.getComponentUtils();
2507let modePosition = componentUtils.getRectangleById("onClick");
2508let localOffsetWidth = modePosition.size.width;
2509let localOffsetHeight = modePosition.size.height;
2510```
2511
2512## UIInspector
2513
2514以下API需先使用UIContext中的[getUIInspector()](#getuiinspector)方法获取到UIInspector对象,再通过该对象调用对应方法。
2515
2516### createComponentObserver
2517
2518createComponentObserver(id: string): inspector.ComponentObserver
2519
2520注册组件布局和绘制完成回调通知。
2521
2522**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
2523
2524**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2525
2526**参数:**
2527
2528| 参数名  | 类型     | 必填   | 说明      |
2529| ---- | ------ | ---- | ------- |
2530| id   | string | 是    | 指定组件id。 |
2531
2532**返回值:**
2533
2534| 类型                                                         | 说明                                               |
2535| ------------------------------------------------------------ | -------------------------------------------------- |
2536| [inspector.ComponentObserver](js-apis-arkui-inspector.md#componentobserver) | 组件回调事件监听句柄,用于注册和取消注册监听回调。 |
2537
2538**示例:**
2539
2540```ts
2541import { UIInspector } from '@kit.ArkUI';
2542
2543let inspector: UIInspector = uiContext.getUIInspector();
2544let listener = inspector.createComponentObserver('COMPONENT_ID');
2545```
2546
2547## PageInfo<sup>12+</sup>
2548Router和NavDestination等页面信息,若无对应的Router或NavDestination页面信息,则对应属性为undefined。
2549
2550**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2551
2552**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2553
2554| 名称 | 类型 | 必填 | 说明 |
2555| -------- | -------- | -------- | -------- |
2556| routerPageInfo | observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo) | 否 | Router信息。 |
2557| navDestinationInfo | observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo) | 否 | NavDestination信息。 |
2558
2559## UIObserver<sup>11+</sup>
2560
2561以下API需先使用UIContext中的[getUIObserver()](#getuiobserver11)方法获取到UIObserver对象,再通过该对象调用对应方法。
2562
2563### on('navDestinationUpdate')<sup>11+</sup>
2564
2565on(type: 'navDestinationUpdate', callback: Callback\<observer.NavDestinationInfo\>): void
2566
2567监听NavDestination组件的状态变化。
2568
2569**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2570
2571**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2572
2573**参数:**
2574
2575| 参数名   | 类型                                                  | 必填 | 说明                                                         |
2576| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
2577| type     | string                                                | 是   | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 |
2578| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 是   | 回调函数。返回当前的NavDestination组件状态。                 |
2579
2580**示例:**
2581
2582```ts
2583import { UIObserver } from '@kit.ArkUI';
2584
2585let observer:UIObserver = uiContext.getUIObserver();
2586observer.on('navDestinationUpdate', (info) => {
2587    console.info('NavDestination state update', JSON.stringify(info));
2588});
2589```
2590
2591### off('navDestinationUpdate')<sup>11+</sup>
2592
2593off(type: 'navDestinationUpdate', callback?: Callback\<observer.NavDestinationInfo\>): void
2594
2595取消监听NavDestination组件的状态变化。
2596
2597**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2598
2599**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2600
2601**参数:**
2602
2603| 参数名   | 类型                                                  | 必填 | 说明                                                         |
2604| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
2605| type     | string                                                | 是   | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 |
2606| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 否   | 回调函数。返回当前的NavDestination组件状态。                 |
2607
2608**示例:**
2609
2610```ts
2611import { UIObserver } from '@kit.ArkUI';
2612
2613let observer:UIObserver = uiContext.getUIObserver();
2614observer.off('navDestinationUpdate');
2615```
2616
2617### on('navDestinationUpdate')<sup>11+</sup>
2618
2619on(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback: Callback\<observer.NavDestinationInfo\>): void
2620
2621监听NavDestination组件的状态变化。
2622
2623**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2624
2625**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2626
2627**参数:**
2628
2629| 参数名   | 类型                                                         | 必填 | 说明                                                         |
2630| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2631| type     | string                                                       | 是   | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 |
2632| options  | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | 是   | 指定监听的Navigation的id。                                   |
2633| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\>        | 是   | 回调函数。返回当前的NavDestination组件状态。                 |
2634
2635**示例:**
2636
2637```ts
2638import { UIObserver } from '@kit.ArkUI';
2639
2640let observer:UIObserver = uiContext.getUIObserver();
2641observer.on('navDestinationUpdate', { navigationId: "testId" }, (info) => {
2642    console.info('NavDestination state update', JSON.stringify(info));
2643});
2644```
2645
2646### off('navDestinationUpdate')<sup>11+</sup>
2647
2648off(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback?: Callback\<observer.NavDestinationInfo\>): void
2649
2650取消监听NavDestination组件的状态变化。
2651
2652**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2653
2654**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2655
2656**参数:**
2657
2658| 参数名   | 类型                                                         | 必填 | 说明                                                         |
2659| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2660| type     | string                                                       | 是   | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 |
2661| options  | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | 是   | 指定监听的Navigation的id。                                   |
2662| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\>        | 否   | 回调函数。返回当前的NavDestination组件状态。                 |
2663
2664**示例:**
2665
2666```ts
2667import { UIObserver } from '@kit.ArkUI';
2668
2669let observer:UIObserver = uiContext.getUIObserver();
2670observer.off('navDestinationUpdate', { navigationId: "testId" });
2671```
2672
2673### on('scrollEvent')<sup>12+</sup>
2674
2675on(type: 'scrollEvent', callback: Callback\<observer.ScrollEventInfo\>): void
2676
2677监听滚动事件的开始和结束。
2678
2679**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2680
2681**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2682
2683**参数:**
2684
2685| 参数名   | 类型                                                  | 必填 | 说明                                                         |
2686| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
2687| type     | string                                                | 是   | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。      |
2688| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\> | 是   | 回调函数。返回滚动事件的信息。   |
2689
2690**示例:**
2691
2692请参考[offscrollevent示例](#offscrollevent12-1)
2693
2694### off('scrollEvent')<sup>12+</sup>
2695
2696off(type: 'scrollEvent', callback?: Callback\<observer.ScrollEventInfo\>): void
2697
2698取消监听滚动事件的开始和结束。
2699
2700**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2701
2702**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2703
2704**参数:**
2705
2706| 参数名   | 类型                                                  | 必填 | 说明                                                         |
2707| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
2708| type     | string                                                | 是   | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。      |
2709| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\> | 否   | 回调函数。返回滚动事件的信息。   |
2710
2711**示例:**
2712
2713请参考[offscrollevent示例](#offscrollevent12-1)
2714
2715### on('scrollEvent')<sup>12+</sup>
2716
2717on(type: 'scrollEvent', options: observer.ObserverOptions, callback: Callback\<observer.ScrollEventInfo\>): void
2718
2719监听滚动事件的开始和结束。
2720
2721**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2722
2723**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2724
2725**参数:**
2726
2727| 参数名   | 类型                                                         | 必填 | 说明                                                         |
2728| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2729| type     | string                                                       | 是   | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 |
2730| options  | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是   | Observer选项,包含指定监听的滚动组件的id。                    |
2731| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\>        | 是   | 回调函数。返回滚动事件的信息。                 |
2732
2733**示例:**
2734
2735请参考[offscrollevent示例](#offscrollevent12-1)
2736
2737### off('scrollEvent')<sup>12+</sup>
2738
2739off(type: 'scrollEvent', options: observer.ObserverOptions, callback?: Callback\<observer.ScrollEventInfo\>): void
2740
2741取消监听滚动事件的开始和结束。
2742
2743**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2744
2745**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2746
2747**参数:**
2748
2749| 参数名   | 类型                                                         | 必填 | 说明                                                         |
2750| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2751| type     | string                                                       | 是   | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 |
2752| options  | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是   | Observer选项,包含指定监听的滚动组件的id。                    |
2753| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\>        | 否   | 回调函数。返回滚动事件的信息。                 |
2754
2755**示例:**
2756
2757```ts
2758import { UIObserver } from '@kit.ArkUI'
2759
2760@Entry
2761@Component
2762struct Index {
2763  scroller: Scroller = new Scroller()
2764  observer: UIObserver = new UIObserver()
2765  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7]
2766
2767  build() {
2768    Row() {
2769      Column() {
2770        Scroll(this.scroller) {
2771          Column() {
2772            ForEach(this.arr, (item: number) => {
2773              Text(item.toString())
2774                .width('90%')
2775                .height(150)
2776                .backgroundColor(0xFFFFFF)
2777                .borderRadius(15)
2778                .fontSize(16)
2779                .textAlign(TextAlign.Center)
2780                .margin({ top: 10 })
2781            }, (item: string) => item)
2782          }.width('100%')
2783        }
2784        .id("testId")
2785        .height('80%')
2786      }
2787      .width('100%')
2788
2789      Row() {
2790        Button('UIObserver on')
2791          .onClick(() => {
2792            this.observer.on('scrollEvent', (info) => {
2793              console.info('scrollEventInfo', JSON.stringify(info));
2794            });
2795          })
2796        Button('UIObserver off')
2797          .onClick(() => {
2798            this.observer.off('scrollEvent');
2799          })
2800      }
2801
2802      Row() {
2803        Button('UIObserverWithId on')
2804          .onClick(() => {
2805            this.observer.on('scrollEvent', { id:"testId" }, (info) => {
2806              console.info('scrollEventInfo', JSON.stringify(info));
2807            });
2808          })
2809        Button('UIObserverWithId off')
2810          .onClick(() => {
2811            this.observer.off('scrollEvent', { id:"testId" });
2812          })
2813      }
2814    }
2815    .height('100%')
2816  }
2817}
2818```
2819
2820### on('routerPageUpdate')<sup>11+</sup>
2821
2822on(type: 'routerPageUpdate', callback: Callback\<observer.RouterPageInfo\>): void
2823
2824监听router中page页面的状态变化。
2825
2826**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2827
2828**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2829
2830**参数:**
2831
2832| 参数名   | 类型                                                         | 必填 | 说明                                                         |
2833| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2834| type     | string                                                       | 是   | 监听事件,固定为'routerPageUpdate',即router中page页面的状态变化。 |
2835| callback | Callback\<observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo)\>        | 是   | 回调函数。携带pageInfo,返回当前的page页面状态。                 |
2836
2837**示例:**
2838
2839```ts
2840import { UIContext, UIObserver } from '@kit.ArkUI';
2841
2842let observer:UIObserver = this.getUIContext().getUIObserver();
2843observer.on('routerPageUpdate', (info) => {
2844    console.info('RouterPage state updated, called by ' + `${info.name}`);
2845});
2846```
2847
2848### off('routerPageUpdate')<sup>11+</sup>
2849
2850off(type: 'routerPageUpdate', callback?: Callback\<observer.RouterPageInfo\>): void
2851
2852取消监听router中page页面的状态变化。
2853
2854**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2855
2856**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2857
2858**参数:**
2859
2860| 参数名   | 类型                                                         | 必填 | 说明                                                         |
2861| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2862| type     | string                                                       | 是   | 监听事件,固定为'routerPageUpdate',即router中page页面的状态变化。 |
2863| callback | Callback\<observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo)\>        | 否   | 需要被注销的回调函数。                 |
2864
2865**示例:**
2866
2867```ts
2868import { UIContext, UIObserver } from '@kit.ArkUI';
2869
2870let observer:UIObserver = this.getUIContext().getUIObserver();
2871function callBackFunc(info:observer.RouterPageInfo) {};
2872// callBackFunc is defined and used before
2873observer.off('routerPageUpdate', callBackFunc);
2874```
2875
2876### on('densityUpdate')<sup>12+</sup>
2877
2878on(type: 'densityUpdate', callback: Callback\<observer.DensityInfo\>): void
2879
2880监听屏幕像素密度变化。
2881
2882**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2883
2884**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2885
2886**参数:**
2887
2888| 参数名   | 类型                                                         | 必填 | 说明                                                         |
2889| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2890| type     | string                                                       | 是   | 监听事件,固定为'densityUpdate',即屏幕像素密度变化。 |
2891| callback | Callback\<observer.[DensityInfo](./js-apis-arkui-observer.md#densityinfo12)\>        | 是   | 回调函数。携带densityInfo,返回变化后的屏幕像素密度。                 |
2892
2893```ts
2894import { uiObserver } from '@kit.ArkUI';
2895
2896@Entry
2897@Component
2898struct Index {
2899  @State density: number = 0;
2900  @State message: string = '未注册监听'
2901
2902  densityUpdateCallback = (info: uiObserver.DensityInfo) => {
2903    this.density = info.density;
2904    this.message = '变化后的DPI:' + this.density.toString();
2905  }
2906
2907  build() {
2908    Column() {
2909      Text(this.message)
2910        .fontSize(24)
2911        .fontWeight(FontWeight.Bold)
2912      Button('注册屏幕像素密度变化监听')
2913        .onClick(() => {
2914          this.message = '已注册监听'
2915          this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback);
2916        })
2917    }
2918  }
2919}
2920```
2921
2922### off('densityUpdate')<sup>12+</sup>
2923
2924off(type: 'densityUpdate', callback?: Callback\<observer.DensityInfo\>): void
2925
2926取消监听屏幕像素密度的变化。
2927
2928**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2929
2930**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2931
2932**参数:**
2933
2934| 参数名   | 类型                                                                 | 必填 | 说明                                                                                         |
2935| -------- | -------------------------------------------------------------------- | ---- | -------------------------------------------------------------------------------------------- |
2936| type     | string                                                               | 是   | 监听事件,固定为'densityUpdate',即屏幕像素密度变化。                                        |
2937| callback | Callback\<observer.[DensityInfo](./js-apis-arkui-observer.md#densityinfo12)\> | 否   | 需要被注销的回调函数。若不指定具体的回调函数,则注销该UIContext下所有densityUpdate事件监听。 |
2938
2939```ts
2940import { uiObserver } from '@kit.ArkUI';
2941
2942@Entry
2943@Component
2944struct Index {
2945  @State density: number = 0;
2946  @State message: string = '未注册监听'
2947
2948  densityUpdateCallback = (info: uiObserver.DensityInfo) => {
2949    this.density = info.density;
2950    this.message = '变化后的DPI:' + this.density.toString();
2951  }
2952
2953  build() {
2954    Column() {
2955      Text(this.message)
2956        .fontSize(24)
2957        .fontWeight(FontWeight.Bold)
2958      Button('注册屏幕像素密度变化监听')
2959        .onClick(() => {
2960          this.message = '已注册监听'
2961          this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback);
2962        })
2963      Button('解除注册屏幕像素密度变化监听')
2964        .onClick(() => {
2965          this.message = '未注册监听'
2966          this.getUIContext().getUIObserver().off('densityUpdate', this.densityUpdateCallback);
2967        })
2968    }
2969  }
2970}
2971```
2972
2973### on('willDraw')<sup>12+</sup>
2974
2975on(type: 'willDraw', callback: Callback\<void\>): void
2976
2977监听每一帧绘制指令下发情况。
2978
2979**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
2980
2981**系统能力:** SystemCapability.ArkUI.ArkUI.Full
2982
2983**参数:**
2984
2985| 参数名   | 类型                                                         | 必填 | 说明                                                         |
2986| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2987| type     | string                                                       | 是   | 监听事件,固定为'willDraw',即是否将要绘制。 |
2988| callback | Callback\<void\>        | 是   | 回调函数。                 |
2989
2990```ts
2991import { uiObserver } from '@kit.ArkUI';
2992
2993@Entry
2994@Component
2995struct Index {
2996  willDrawCallback = () => {
2997    console.info("willDraw指令下发");
2998  }
2999  build() {
3000    Column() {
3001      Button('注册绘制指令下发监听')
3002        .onClick(() => {
3003          this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback);
3004        })
3005    }
3006  }
3007}
3008```
3009
3010### off('willDraw')<sup>12+</sup>
3011
3012off(type: 'willDraw', callback?: Callback\<void\>): void
3013
3014取消监听每一帧绘制指令下发情况。
3015
3016**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3017
3018**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3019
3020**参数:**
3021
3022| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3023| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3024| type     | string                                                       | 是   | 监听事件,固定为'willDraw',即是否将要绘制。 |
3025| callback | Callback\<void\>        | 否   | 需要被注销的回调函数。                  |
3026
3027```ts
3028import { uiObserver } from '@kit.ArkUI';
3029
3030@Entry
3031@Component
3032struct Index {
3033  willDrawCallback = () => {
3034    console.info("willDraw指令下发")
3035  }
3036
3037  build() {
3038    Column() {
3039      Button('注册绘制指令下发监听')
3040        .onClick(() => {
3041          this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback);
3042        })
3043      Button('解除注册绘制指令下发监听')
3044        .onClick(() => {
3045          this.getUIContext().getUIObserver().off('willDraw', this.willDrawCallback);
3046        })
3047    }
3048  }
3049}
3050```
3051
3052### on('didLayout')<sup>12+</sup>
3053
3054on(type: 'didLayout', callback: Callback\<void\>): void
3055
3056监听每一帧布局完成情况。
3057
3058**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3059
3060**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3061
3062**参数:**
3063
3064| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3065| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3066| type     | string                                                       | 是   | 监听事件,固定为'didLayout',即是否布局完成。 |
3067| callback | Callback\<void\>        | 是   | 回调函数。                 |
3068
3069```ts
3070import { uiObserver } from '@kit.ArkUI';
3071
3072@Entry
3073@Component
3074struct Index {
3075  didLayoutCallback = () => {
3076    console.info("layout布局完成");
3077  }
3078  build() {
3079    Column() {
3080      Button('注册布局完成监听')
3081        .onClick(() => {
3082          this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback);
3083        })
3084    }
3085  }
3086}
3087```
3088
3089### off('didLayout')<sup>12+</sup>
3090
3091off(type: 'didLayout', callback?: Callback\<void\>): void
3092
3093取消监听每一帧布局完成情况。
3094
3095**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3096
3097**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3098
3099**参数:**
3100
3101| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3102| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3103| type     | string                                                       | 是   | 监听事件,固定为'didLayout',即是否将要绘制。 |
3104| callback | Callback\<void\>        | 否   | 需要被注销的回调函数。                  |
3105
3106```ts
3107import { uiObserver } from '@kit.ArkUI';
3108
3109@Entry
3110@Component
3111struct Index {
3112  didLayoutCallback = () => {
3113    console.info("layout布局完成")
3114  }
3115
3116  build() {
3117    Column() {
3118      Button('注册布局完成监听')
3119        .onClick(() => {
3120          this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback);
3121        })
3122      Button('解除注册注册布局完成监听')
3123        .onClick(() => {
3124          this.getUIContext().getUIObserver().off('didLayout', this.didLayoutCallback);
3125        })
3126    }
3127  }
3128}
3129```
3130
3131### on('navDestinationSwitch')<sup>12+</sup>
3132
3133on(type: 'navDestinationSwitch', callback: Callback\<observer.NavDestinationSwitchInfo\>): void
3134
3135监听Navigation的页面切换事件。
3136
3137**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3138
3139**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3140
3141**参数:**
3142
3143| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3144| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3145| type     | string                                                       | 是   | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 |
3146| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\>        | 是   | 回调函数。携带NavDestinationSwitchInfo,返回页面切换事件的信息。                 |
3147
3148**示例:**
3149
3150```ts
3151// Index.ets
3152// 演示 UIObserver.on('navDestinationSwitch', callback)
3153// UIObserver.off('navDestinationSwitch', callback)
3154import { uiObserver } from '@kit.ArkUI';
3155
3156@Component
3157struct PageOne {
3158  build() {
3159    NavDestination() {
3160      Text("pageOne")
3161    }.title("pageOne")
3162  }
3163}
3164
3165function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) {
3166  console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`)
3167}
3168
3169@Entry
3170@Component
3171struct Index {
3172  private stack: NavPathStack = new NavPathStack();
3173
3174  @Builder
3175  PageBuilder(name: string) {
3176    PageOne()
3177  }
3178
3179  aboutToAppear() {
3180    let obs = this.getUIContext().getUIObserver();
3181    obs.on('navDestinationSwitch', callBackFunc);
3182  }
3183
3184  aboutToDisappear() {
3185    let obs = this.getUIContext().getUIObserver();
3186    obs.off('navDestinationSwitch', callBackFunc);
3187  }
3188
3189  build() {
3190    Column() {
3191      Navigation(this.stack) {
3192        Button("push").onClick(() => {
3193          this.stack.pushPath({name: "pageOne"});
3194        })
3195      }
3196      .title("Navigation")
3197      .navDestination(this.PageBuilder)
3198    }
3199    .width('100%')
3200    .height('100%')
3201  }
3202}
3203```
3204
3205### off('navDestinationSwitch')<sup>12+</sup>
3206
3207off(type: 'navDestinationSwitch', callback?: Callback\<observer.NavDestinationSwitchInfo\>): void
3208
3209取消监听Navigation的页面切换事件。
3210
3211**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3212
3213**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3214
3215**参数:**
3216
3217| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3218| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3219| type     | string                                                       | 是   | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 |
3220| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\>        | 否   | 需要被注销的回调函数。                 |
3221
3222**示例代码参考上述UIObserver.on('navDestinationSwitch')接口的示例代码**
3223
3224### on('navDestinationSwitch')<sup>12+</sup>
3225
3226on(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback: Callback\<observer.NavDestinationSwitchInfo\>): void
3227
3228监听Navigation的页面切换事件。
3229
3230**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3231
3232**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3233
3234**参数:**
3235
3236| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3237| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3238| type     | string                                                       | 是   | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 |
3239| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12)        | 是   | 监听选项。   |
3240| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\>        | 是   | 回调函数。携带NavDestinationSwitchInfo,返回页面切换事件的信息。                 |
3241
3242**示例:**
3243
3244```ts
3245// Index.ets
3246// 演示 UIObserver.on('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback)
3247// UIObserver.off('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback)
3248import { uiObserver } from '@kit.ArkUI';
3249
3250@Component
3251struct PageOne {
3252  build() {
3253    NavDestination() {
3254      Text("pageOne")
3255    }.title("pageOne")
3256  }
3257}
3258
3259function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) {
3260  console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`)
3261}
3262
3263@Entry
3264@Component
3265struct Index {
3266  private stack: NavPathStack = new NavPathStack();
3267
3268  @Builder
3269  PageBuilder(name: string) {
3270    PageOne()
3271  }
3272
3273  aboutToAppear() {
3274    let obs = this.getUIContext().getUIObserver();
3275    obs.on('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc)
3276  }
3277
3278  aboutToDisappear() {
3279    let obs = this.getUIContext().getUIObserver();
3280    obs.off('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc)
3281  }
3282
3283  build() {
3284    Column() {
3285      Navigation(this.stack) {
3286        Button("push").onClick(() => {
3287          this.stack.pushPath({name: "pageOne"});
3288        })
3289      }
3290      .id("myNavId")
3291      .title("Navigation")
3292      .navDestination(this.PageBuilder)
3293    }
3294    .width('100%')
3295    .height('100%')
3296  }
3297}
3298```
3299
3300### off('navDestinationSwitch')<sup>12+</sup>
3301
3302off(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback?: Callback\<observer.NavDestinationSwitchInfo\>): void
3303
3304取消监听Navigation的页面切换事件。
3305
3306**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3307
3308**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3309
3310**参数:**
3311
3312| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3313| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3314| type     | string                                                       | 是   | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 |
3315| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12)        | 是   | 监听选项。   |
3316| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\>        | 否   | 需要被注销的回调函数。                 |
3317
3318**示例代码参考上述UIObserver.on('navDestinationSwitch')接口的示例代码**
3319
3320### on('willClick')<sup>12+</sup>
3321
3322on(type: 'willClick', callback: GestureEventListenerCallback): void
3323
3324监听点击事件指令下发情况。
3325
3326**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3327
3328**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3329
3330**参数:**
3331
3332| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3333| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3334| type     | string                                                       | 是   | 监听事件,固定为'willClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发前触发。 |
3335| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 是   | 回调函数。可以获得点击事件的GestureEvent和组件的FrameNode。  |
3336
3337**示例:**
3338
3339```ts
3340// 在页面Component中使用
3341import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3342
3343// callback是开发者定义的监听回调函数
3344let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
3345let observer: UIObserver = this.getUIContext().getUIObserver();
3346observer.on('willClick', callback);
3347```
3348
3349### off('willClick')<sup>12+</sup>
3350
3351off(type: 'willClick', callback?: GestureEventListenerCallback): void
3352
3353取消监听点击事件指令下发情况。
3354
3355**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3356
3357**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3358
3359**参数:**
3360
3361| 参数名   | 类型                                                         | 必填 | 说明                                                  |
3362| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
3363| type     | string                                                       | 是   | 监听事件,固定为'willClick',即点击事件指令下发情况。 |
3364| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 否   | 需要被注销的回调函数。                                |
3365
3366**示例:**
3367
3368```ts
3369// 在页面Component中使用
3370import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3371
3372// callback是开发者定义的监听回调函数
3373let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
3374let observer: UIObserver = this.getUIContext().getUIObserver();
3375observer.off('willClick', callback);
3376```
3377
3378### on('didClick')<sup>12+</sup>
3379
3380on(type: 'didClick', callback: GestureEventListenerCallback): void
3381
3382监听点击事件指令下发情况。
3383
3384**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3385
3386**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3387
3388**参数:**
3389
3390| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3391| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3392| type     | string                                                       | 是   | 监听事件,固定为'didClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发后触发。 |
3393| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 是   | 回调函数。可以获得点击事件的GestureEvent和组件的FrameNode。  |
3394
3395**示例:**
3396
3397```ts
3398// 在页面Component中使用
3399import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3400
3401// callback是开发者定义的监听回调函数
3402let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
3403let observer: UIObserver = this.getUIContext().getUIObserver();
3404observer.on('didClick', callback);
3405```
3406
3407### off('didClick')<sup>12+</sup>
3408
3409off(type: 'didClick', callback?: GestureEventListenerCallback): void
3410
3411取消监听点击事件指令下发情况。
3412
3413**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3414
3415**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3416
3417**参数:**
3418
3419| 参数名   | 类型                                                         | 必填 | 说明                                                 |
3420| -------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------- |
3421| type     | string                                                       | 是   | 监听事件,固定为'didClick',即点击事件指令下发情况。 |
3422| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 否   | 需要被注销的回调函数。                               |
3423
3424**示例:**
3425
3426```ts
3427// 在页面Component中使用
3428import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3429
3430// callback是开发者定义的监听回调函数
3431let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
3432let observer: UIObserver = this.getUIContext().getUIObserver();
3433observer.off('didClick', callback);
3434```
3435
3436### on('willClick')<sup>12+</sup>
3437
3438on(type: 'willClick', callback: ClickEventListenerCallback): void
3439
3440监听点击事件指令下发情况。
3441
3442**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3443
3444**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3445
3446**参数:**
3447
3448| 参数名   | 类型                                                        | 必填 | 说明                                                         |
3449| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
3450| type     | string                                                      | 是   | 监听事件,固定为'willClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发前触发。 |
3451| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 是   | 回调函数。可以获得点击事件的ClickEvent和组件的FrameNode。    |
3452
3453**示例:**
3454
3455```ts
3456// 在页面Component中使用
3457import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3458
3459// callback是开发者定义的监听回调函数
3460let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
3461let observer: UIObserver = this.getUIContext().getUIObserver();
3462observer.on('willClick', callback);
3463```
3464
3465### off('willClick')<sup>12+</sup>
3466
3467off(type: 'willClick', callback?: ClickEventListenerCallback): void
3468
3469取消监听点击事件指令下发情况。
3470
3471**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3472
3473**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3474
3475**参数:**
3476
3477| 参数名   | 类型                                                        | 必填 | 说明                                                  |
3478| -------- | ----------------------------------------------------------- | ---- | ----------------------------------------------------- |
3479| type     | string                                                      | 是   | 监听事件,固定为'willClick',即点击事件指令下发情况。 |
3480| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 否   | 需要被注销的回调函数。                                |
3481
3482**示例:**
3483
3484```ts
3485// 在页面Component中使用
3486import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3487
3488// callback是开发者定义的监听回调函数
3489let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
3490let observer: UIObserver = this.getUIContext().getUIObserver();
3491observer.off('willClick', callback);
3492```
3493
3494### on('didClick')<sup>12+</sup>
3495
3496on(type: 'didClick', callback: ClickEventListenerCallback): void
3497
3498监听点击事件指令下发情况。
3499
3500**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3501
3502**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3503
3504**参数:**
3505
3506| 参数名   | 类型                                                        | 必填 | 说明                                                         |
3507| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
3508| type     | string                                                      | 是   | 监听事件,固定为'didClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发后触发。 |
3509| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 是   | 回调函数。可以获得点击事件的ClickEvent和组件的FrameNode。    |
3510
3511**示例:**
3512
3513```ts
3514// 在页面Component中使用
3515import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3516
3517// callback是开发者定义的监听回调函数
3518let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
3519let observer: UIObserver = this.getUIContext().getUIObserver();
3520observer.on('didClick', callback);
3521```
3522
3523### off('didClick')<sup>12+</sup>
3524
3525off(type: 'didClick', callback?: ClickEventListenerCallback): void
3526
3527取消监听点击事件指令下发情况。
3528
3529**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3530
3531**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3532
3533**参数:**
3534
3535| 参数名   | 类型                                                        | 必填 | 说明                                                 |
3536| -------- | ----------------------------------------------------------- | ---- | ---------------------------------------------------- |
3537| type     | string                                                      | 是   | 监听事件,固定为'didClick',即点击事件指令下发情况。 |
3538| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 否   | 需要被注销的回调函数。                               |
3539
3540**示例:**
3541
3542```ts
3543// 在页面Component中使用
3544import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3545
3546// callback是开发者定义的监听回调函数
3547let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
3548let observer: UIObserver = this.getUIContext().getUIObserver();
3549observer.off('didClick', callback);
3550```
3551
3552### on('tabContentUpdate')<sup>12+</sup>
3553
3554on(type: 'tabContentUpdate', callback: Callback\<observer.TabContentInfo\>): void
3555
3556监听TabContent页面的切换事件。
3557
3558**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3559
3560**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3561
3562**参数:**
3563
3564| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3565| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3566| type     | string                                                       | 是   | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 |
3567| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | 是   | 回调函数。携带TabContentInfo,返回TabContent页面切换事件的信息。 |
3568
3569**示例:**
3570
3571```ts
3572import { uiObserver } from '@kit.ArkUI';
3573
3574function callbackFunc(info: uiObserver.TabContentInfo) {
3575  console.info('tabContentUpdate', JSON.stringify(info));
3576}
3577
3578@Entry
3579@Component
3580struct TabsExample {
3581
3582  aboutToAppear(): void {
3583    let observer = this.getUIContext().getUIObserver();
3584    observer.on('tabContentUpdate', callbackFunc);
3585  }
3586
3587  aboutToDisappear(): void {
3588    let observer = this.getUIContext().getUIObserver();
3589    observer.off('tabContentUpdate', callbackFunc);
3590  }
3591
3592  build() {
3593    Column() {
3594      Tabs() {
3595        TabContent() {
3596          Column().width('100%').height('100%').backgroundColor('#00CB87')
3597        }.tabBar('green').id('tabContentId0')
3598
3599        TabContent() {
3600          Column().width('100%').height('100%').backgroundColor('#007DFF')
3601        }.tabBar('blue').id('tabContentId1')
3602
3603        TabContent() {
3604          Column().width('100%').height('100%').backgroundColor('#FFBF00')
3605        }.tabBar('yellow').id('tabContentId2')
3606
3607        TabContent() {
3608          Column().width('100%').height('100%').backgroundColor('#E67C92')
3609        }.tabBar('pink').id('tabContentId3')
3610      }
3611      .width(360)
3612      .height(296)
3613      .backgroundColor('#F1F3F5')
3614      .id('tabsId')
3615    }.width('100%')
3616  }
3617}
3618```
3619
3620### off('tabContentUpdate')<sup>12+</sup>
3621
3622off(type: 'tabContentUpdate', callback?: Callback\<observer.TabContentInfo\>): void
3623
3624取消监听TabContent页面的切换事件。
3625
3626**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3627
3628**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3629
3630**参数:**
3631
3632| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3633| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3634| type     | string                                                       | 是   | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 |
3635| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | 否   | 需要被注销的回调函数。 |
3636
3637**示例:**
3638
3639参考[on('tabContentUpdate')](#ontabcontentupdate12)接口示例。
3640
3641### on('tabContentUpdate')<sup>12+</sup>
3642
3643on(type: 'tabContentUpdate', options: observer.ObserverOptions, callback: Callback\<observer.TabContentInfo\>): void
3644
3645监听TabContent页面的切换事件。
3646
3647**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3648
3649**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3650
3651**参数:**
3652
3653| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3654| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3655| type     | string                                                       | 是   | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 |
3656| options  | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是   | 指定监听的Tabs组件的id。 |
3657| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | 是   | 回调函数。携带TabContentInfo,返回TabContent页面切换事件的信息。 |
3658
3659**示例:**
3660
3661```ts
3662import { uiObserver } from '@kit.ArkUI';
3663
3664function callbackFunc(info: uiObserver.TabContentInfo) {
3665  console.info('tabContentUpdate', JSON.stringify(info));
3666}
3667
3668@Entry
3669@Component
3670struct TabsExample {
3671
3672  aboutToAppear(): void {
3673    let observer = this.getUIContext().getUIObserver();
3674    observer.on('tabContentUpdate', { id: 'tabsId' }, callbackFunc);
3675  }
3676
3677  aboutToDisappear(): void {
3678    let observer = this.getUIContext().getUIObserver();
3679    observer.off('tabContentUpdate', { id: 'tabsId' }, callbackFunc);
3680  }
3681
3682  build() {
3683    Column() {
3684      Tabs() {
3685        TabContent() {
3686          Column().width('100%').height('100%').backgroundColor('#00CB87')
3687        }.tabBar('green').id('tabContentId0')
3688
3689        TabContent() {
3690          Column().width('100%').height('100%').backgroundColor('#007DFF')
3691        }.tabBar('blue').id('tabContentId1')
3692
3693        TabContent() {
3694          Column().width('100%').height('100%').backgroundColor('#FFBF00')
3695        }.tabBar('yellow').id('tabContentId2')
3696
3697        TabContent() {
3698          Column().width('100%').height('100%').backgroundColor('#E67C92')
3699        }.tabBar('pink').id('tabContentId3')
3700      }
3701      .width(360)
3702      .height(296)
3703      .backgroundColor('#F1F3F5')
3704      .id('tabsId')
3705    }.width('100%')
3706  }
3707}
3708```
3709
3710### off('tabContentUpdate')<sup>12+</sup>
3711
3712off(type: 'tabContentUpdate', options: observer.ObserverOptions, callback?: Callback\<observer.TabContentInfo\>): void
3713
3714取消监听TabContent页面的切换事件。
3715
3716**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3717
3718**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3719
3720**参数:**
3721
3722| 参数名   | 类型                                                         | 必填 | 说明                                                         |
3723| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3724| type     | string                                                       | 是   | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 |
3725| options  | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是   | 指定监听的Tabs组件的id。 |
3726| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | 否   | 需要被注销的回调函数。 |
3727
3728**示例:**
3729
3730参考[on('tabContentUpdate')](#ontabcontentupdate12-1)接口示例。
3731
3732## GestureEventListenerCallback<sup>12+</sup>
3733type GestureEventListenerCallback = (event: GestureEvent, node?: FrameNode) => void
3734
3735ArkTS GestureEvent事件监听函数类型。
3736
3737**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3738
3739**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3740
3741**参数:**
3742
3743| 参数名  | 类型   | 必填 | 说明                          |
3744| ------- | ------ | ---- | --------------------------- |
3745| event | [GestureEvent](../apis-arkui/arkui-ts/ts-gesture-settings.md#gestureevent对象说明) | 是 | 触发事件监听的手势事件的相关信息。 |
3746| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | 否 | 触发事件监听的手势事件所绑定的组件。 |
3747
3748## ClickEventListenerCallback<sup>12+</sup>
3749type ClickEventListenerCallback = (event: ClickEvent, node?: FrameNode) => void
3750
3751ArkTS GestureEvent事件监听函数类型。
3752
3753**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
3754
3755**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3756
3757**参数:**
3758
3759| 参数名  | 类型   | 必填 | 说明                          |
3760| ------- | ------ | ---- | --------------------------- |
3761| event | [ClickEvent](../apis-arkui/arkui-ts/ts-universal-events-click.md#clickevent对象说明) | 是 | 触发事件监听的点击事件的相关信息。 |
3762| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | 否 | 触发事件监听的点击事件所绑定的组件。 |
3763
3764## MediaQuery
3765
3766以下API需先使用UIContext中的[getMediaQuery()](#getmediaquery)方法获取到MediaQuery对象,再通过该对象调用对应方法。
3767
3768### matchMediaSync
3769
3770matchMediaSync(condition: string): mediaQuery.MediaQueryListener
3771
3772设置媒体查询的查询条件,并返回对应的监听句柄。
3773
3774**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
3775
3776**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3777
3778**参数:**
3779
3780| 参数名       | 类型     | 必填   | 说明                                       |
3781| --------- | ------ | ---- | ---------------------------------------- |
3782| condition | string | 是    | 媒体事件的匹配条件,具体可参考[媒体查询语法规则](../../ui/arkts-layout-development-media-query.md#语法规则)。 |
3783
3784**返回值:**
3785
3786| 类型                                                         | 说明                                         |
3787| ------------------------------------------------------------ | -------------------------------------------- |
3788| [mediaQuery.MediaQueryListener](js-apis-mediaquery.md#mediaquerylistener) | 媒体事件监听句柄,用于注册和去注册监听回调。 |
3789
3790**示例:**
3791
3792```ts
3793import { MediaQuery } from '@kit.ArkUI';
3794
3795let mediaquery: MediaQuery = uiContext.getMediaQuery();
3796let listener = mediaquery.matchMediaSync('(orientation: landscape)'); //监听横屏事件
3797```
3798
3799## Router
3800
3801以下API需先使用UIContext中的[getRouter()](#getrouter)方法获取到Router对象,再通过该对象调用对应方法。
3802
3803### pushUrl
3804
3805pushUrl(options: router.RouterOptions): Promise&lt;void&gt;
3806
3807跳转到应用内的指定页面,通过Promise获取跳转异常的返回结果。
3808
3809**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
3810
3811**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3812
3813**参数:**
3814
3815| 参数名     | 类型                                       | 必填   | 说明        |
3816| ------- | ---------------------------------------- | ---- | --------- |
3817| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是    | 跳转页面描述信息。 |
3818
3819**返回值:**
3820
3821| 类型                  | 说明      |
3822| ------------------- | ------- |
3823| Promise&lt;void&gt; | 异常返回结果。 |
3824
3825**错误码:**
3826
3827以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
3828
3829| 错误码ID  | 错误信息                               |
3830| ------ | ---------------------------------- |
3831| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
3832| 100001 | Internal error. |
3833| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist.           |
3834| 100003 | Page stack error. Too many pages are pushed.  |
3835
3836**示例:**
3837
3838```ts
3839import { Router } from '@kit.ArkUI';
3840import { BusinessError } from '@kit.BasicServicesKit';
3841
3842let router:Router = uiContext.getRouter();
3843try {
3844  router.pushUrl({
3845    url: 'pages/routerpage2',
3846    params: {
3847      data1: 'message',
3848      data2: {
3849        data3: [123, 456, 789]
3850      }
3851    }
3852  })
3853} catch (err) {
3854  let message = (err as BusinessError).message;
3855  let code = (err as BusinessError).code;
3856  console.error(`pushUrl failed, code is ${code}, message is ${message}`);
3857}
3858```
3859
3860### pushUrl
3861
3862pushUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;): void
3863
3864跳转到应用内的指定页面。
3865
3866**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
3867
3868**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3869
3870**参数:**
3871
3872| 参数名      | 类型                                       | 必填   | 说明        |
3873| -------- | ---------------------------------------- | ---- | --------- |
3874| options  | [router.RouterOptions](js-apis-router.md#routeroptions) | 是    | 跳转页面描述信息。 |
3875| callback | AsyncCallback&lt;void&gt;                | 是    | 异常响应回调。   |
3876
3877**错误码:**
3878
3879以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
3880
3881| 错误码ID  | 错误信息                               |
3882| ------ | ---------------------------------- |
3883| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
3884| 100001 | Internal error. |
3885| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist.           |
3886| 100003 | Page stack error. Too many pages are pushed.  |
3887
3888**示例:**
3889
3890```ts
3891import { Router } from '@kit.ArkUI';
3892import { BusinessError } from '@kit.BasicServicesKit';
3893
3894let router:Router = uiContext.getRouter();
3895router.pushUrl({
3896  url: 'pages/routerpage2',
3897  params: {
3898    data1: 'message',
3899    data2: {
3900      data3: [123, 456, 789]
3901    }
3902  }
3903}, (err: Error) => {
3904  if (err) {
3905    let message = (err as BusinessError).message;
3906    let code = (err as BusinessError).code;
3907    console.error(`pushUrl failed, code is ${code}, message is ${message}`);
3908    return;
3909  }
3910  console.info('pushUrl success');
3911})
3912```
3913
3914### pushUrl
3915
3916pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
3917
3918跳转到应用内的指定页面,通过Promise获取跳转异常的返回结果。
3919
3920**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
3921
3922**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3923
3924**参数:**
3925
3926| 参数名     | 类型                                       | 必填   | 说明         |
3927| ------- | ---------------------------------------- | ---- | ---------- |
3928| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是    | 跳转页面描述信息。  |
3929| mode    | [router.RouterMode](js-apis-router.md#routermode9) | 是    | 跳转页面使用的模式。 |
3930
3931**返回值:**
3932
3933| 类型                  | 说明      |
3934| ------------------- | ------- |
3935| Promise&lt;void&gt; | 异常返回结果。 |
3936
3937**错误码:**
3938
3939以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
3940
3941| 错误码ID  | 错误信息                               |
3942| ------ | ---------------------------------- |
3943| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
3944| 100001 | Internal error. |
3945| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist.           |
3946| 100003 | Page stack error. Too many pages are pushed.  |
3947
3948**示例:**
3949
3950```ts
3951import { Router, router } from '@kit.ArkUI';
3952import { BusinessError } from '@kit.BasicServicesKit';
3953
3954let routerF:Router = uiContext.getRouter();
3955class RouterTmp{
3956  Standard:router.RouterMode = router.RouterMode.Standard
3957}
3958let rtm:RouterTmp = new RouterTmp()
3959try {
3960  routerF.pushUrl({
3961    url: 'pages/routerpage2',
3962    params: {
3963      data1: 'message',
3964      data2: {
3965        data3: [123, 456, 789]
3966      }
3967    }
3968  }, rtm.Standard)
3969} catch (err) {
3970  let message = (err as BusinessError).message;
3971  let code = (err as BusinessError).code;
3972  console.error(`pushUrl failed, code is ${code}, message is ${message}`);
3973}
3974```
3975
3976### pushUrl
3977
3978pushUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
3979
3980跳转到应用内的指定页面。
3981
3982**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
3983
3984**系统能力:** SystemCapability.ArkUI.ArkUI.Full
3985
3986**参数:**
3987
3988| 参数名      | 类型                                       | 必填   | 说明         |
3989| -------- | ---------------------------------------- | ---- | ---------- |
3990| options  | [router.RouterOptions](js-apis-router.md#routeroptions) | 是    | 跳转页面描述信息。  |
3991| mode     | [router.RouterMode](js-apis-router.md#routermode9) | 是    | 跳转页面使用的模式。 |
3992| callback | AsyncCallback&lt;void&gt;                | 是    | 异常响应回调。    |
3993
3994**错误码:**
3995
3996以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
3997
3998| 错误码ID  | 错误信息                               |
3999| ------ | ---------------------------------- |
4000| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4001| 100001 | Internal error. |
4002| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist.           |
4003| 100003 | Page stack error. Too many pages are pushed.  |
4004
4005**示例:**
4006
4007```ts
4008import { Router, router } from '@kit.ArkUI';
4009import { BusinessError } from '@kit.BasicServicesKit';
4010
4011let routerF:Router = uiContext.getRouter();
4012class RouterTmp{
4013  Standard:router.RouterMode = router.RouterMode.Standard
4014}
4015let rtm:RouterTmp = new RouterTmp()
4016routerF.pushUrl({
4017  url: 'pages/routerpage2',
4018  params: {
4019    data1: 'message',
4020    data2: {
4021      data3: [123, 456, 789]
4022    }
4023  }
4024}, rtm.Standard, (err) => {
4025  if (err) {
4026    let message = (err as BusinessError).message;
4027    let code = (err as BusinessError).code;
4028    console.error(`pushUrl failed, code is ${code}, message is ${message}`);
4029    return;
4030  }
4031  console.info('pushUrl success');
4032})
4033```
4034
4035### replaceUrl
4036
4037replaceUrl(options: router.RouterOptions): Promise&lt;void&gt;
4038
4039用应用内的某个页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回的结果。
4040
4041**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4042
4043**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4044
4045**参数:**
4046
4047| 参数名     | 类型                                       | 必填   | 说明        |
4048| ------- | ---------------------------------------- | ---- | --------- |
4049| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是    | 替换页面描述信息。 |
4050
4051**返回值:**
4052
4053| 类型                  | 说明      |
4054| ------------------- | ------- |
4055| Promise&lt;void&gt; | 异常返回结果。 |
4056
4057**错误码:**
4058
4059以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4060
4061| 错误码ID  | 错误信息                                     |
4062| ------ | ---------------------------------------- |
4063| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4064| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
4065| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist.                 |
4066
4067**示例:**
4068
4069```ts
4070import { Router } from '@kit.ArkUI';
4071import { BusinessError } from '@kit.BasicServicesKit';
4072
4073let router:Router = uiContext.getRouter();
4074try {
4075  router.replaceUrl({
4076    url: 'pages/detail',
4077    params: {
4078      data1: 'message'
4079    }
4080  })
4081} catch (err) {
4082  let message = (err as BusinessError).message;
4083  let code = (err as BusinessError).code;
4084  console.error(`replaceUrl failed, code is ${code}, message is ${message}`);
4085}
4086```
4087
4088### replaceUrl
4089
4090replaceUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;): void
4091
4092用应用内的某个页面替换当前页面,并销毁被替换的页面。
4093
4094**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4095
4096**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4097
4098**参数:**
4099
4100| 参数名      | 类型                                       | 必填   | 说明        |
4101| -------- | ---------------------------------------- | ---- | --------- |
4102| options  | [router.RouterOptions](js-apis-router.md#routeroptions) | 是    | 替换页面描述信息。 |
4103| callback | AsyncCallback&lt;void&gt;                | 是    | 异常响应回调。   |
4104
4105**错误码:**
4106
4107以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4108
4109| 错误码ID  | 错误信息                                     |
4110| ------ | ---------------------------------------- |
4111| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4112| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
4113| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. |
4114
4115**示例:**
4116
4117```ts
4118import { Router } from '@kit.ArkUI';
4119import { BusinessError } from '@kit.BasicServicesKit';
4120
4121let router:Router = uiContext.getRouter();
4122router.replaceUrl({
4123  url: 'pages/detail',
4124  params: {
4125    data1: 'message'
4126  }
4127}, (err: Error) => {
4128  if (err) {
4129    let message = (err as BusinessError).message;
4130    let code = (err as BusinessError).code;
4131    console.error(`replaceUrl failed, code is ${code}, message is ${message}`);
4132    return;
4133  }
4134  console.info('replaceUrl success');
4135})
4136```
4137
4138### replaceUrl
4139
4140replaceUrl(options: router.RouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
4141
4142用应用内的某个页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。
4143
4144**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4145
4146**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4147
4148**参数:**
4149
4150| 参数名     | 类型                                       | 必填   | 说明         |
4151| ------- | ---------------------------------------- | ---- | ---------- |
4152| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是    | 替换页面描述信息。  |
4153| mode    | [router.RouterMode](js-apis-router.md#routermode9) | 是    | 跳转页面使用的模式。 |
4154
4155**返回值:**
4156
4157| 类型                  | 说明      |
4158| ------------------- | ------- |
4159| Promise&lt;void&gt; | 异常返回结果。 |
4160
4161**错误码:**
4162
4163以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4164
4165| 错误码ID  | 错误信息                                     |
4166| ------ | ---------------------------------------- |
4167| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4168| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. |
4169| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist.                 |
4170
4171**示例:**
4172
4173```ts
4174import { Router, router } from '@kit.ArkUI';
4175import { BusinessError } from '@kit.BasicServicesKit';
4176
4177let routerF:Router = uiContext.getRouter();
4178class RouterTmp{
4179  Standard:router.RouterMode = router.RouterMode.Standard
4180}
4181let rtm:RouterTmp = new RouterTmp()
4182try {
4183  routerF.replaceUrl({
4184    url: 'pages/detail',
4185    params: {
4186      data1: 'message'
4187    }
4188  }, rtm.Standard)
4189} catch (err) {
4190  let message = (err as BusinessError).message;
4191  let code = (err as BusinessError).code;
4192  console.error(`replaceUrl failed, code is ${code}, message is ${message}`);
4193}
4194```
4195
4196### replaceUrl
4197
4198replaceUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
4199
4200用应用内的某个页面替换当前页面,并销毁被替换的页面。
4201
4202**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4203
4204**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4205
4206**参数:**
4207
4208| 参数名      | 类型                                       | 必填   | 说明         |
4209| -------- | ---------------------------------------- | ---- | ---------- |
4210| options  | [router.RouterOptions](js-apis-router.md#routeroptions) | 是    | 替换页面描述信息。  |
4211| mode     | [router.RouterMode](js-apis-router.md#routermode9) | 是    | 跳转页面使用的模式。 |
4212| callback | AsyncCallback&lt;void&gt;                | 是    | 异常响应回调。    |
4213
4214**错误码:**
4215
4216以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4217
4218| 错误码ID  | 错误信息                                     |
4219| ------ | ---------------------------------------- |
4220| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4221| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
4222| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist.               |
4223
4224**示例:**
4225
4226```ts
4227import { Router, router } from '@kit.ArkUI';
4228import { BusinessError } from '@kit.BasicServicesKit';
4229
4230let routerF:Router = uiContext.getRouter();
4231class RouterTmp{
4232  Standard:router.RouterMode = router.RouterMode.Standard
4233}
4234let rtm:RouterTmp = new RouterTmp()
4235routerF.replaceUrl({
4236  url: 'pages/detail',
4237  params: {
4238    data1: 'message'
4239  }
4240}, rtm.Standard, (err: Error) => {
4241  if (err) {
4242    let message = (err as BusinessError).message;
4243    let code = (err as BusinessError).code;
4244    console.error(`replaceUrl failed, code is ${code}, message is ${message}`);
4245    return;
4246  }
4247  console.info('replaceUrl success');
4248});
4249```
4250
4251### pushNamedRoute
4252
4253pushNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt;
4254
4255跳转到指定的命名路由页面,通过Promise获取跳转异常的返回结果。
4256
4257**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4258
4259**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4260
4261**参数:**
4262
4263| 参数名     | 类型                                       | 必填   | 说明        |
4264| ------- | ---------------------------------------- | ---- | --------- |
4265| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是    | 跳转页面描述信息。 |
4266
4267**返回值:**
4268
4269| 类型                  | 说明      |
4270| ------------------- | ------- |
4271| Promise&lt;void&gt; | 异常返回结果。 |
4272
4273**错误码:**
4274
4275以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4276
4277| 错误码ID  | 错误信息                               |
4278| ------ | ---------------------------------- |
4279| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4280| 100001 | Internal error. |
4281| 100003 | Page stack error. Too many pages are pushed.  |
4282| 100004 | Named route error. The named route does not exist.   |
4283
4284**示例:**
4285
4286```ts
4287import { Router } from '@kit.ArkUI';
4288import { BusinessError } from '@kit.BasicServicesKit';
4289
4290let router:Router = uiContext.getRouter();
4291try {
4292  router.pushNamedRoute({
4293    name: 'myPage',
4294    params: {
4295      data1: 'message',
4296      data2: {
4297        data3: [123, 456, 789]
4298      }
4299    }
4300  })
4301} catch (err) {
4302  let message = (err as BusinessError).message;
4303  let code = (err as BusinessError).code;
4304  console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
4305}
4306```
4307
4308### pushNamedRoute
4309
4310pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt;void&gt;): void
4311
4312跳转到指定的命名路由页面。
4313
4314**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4315
4316**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4317
4318**参数:**
4319
4320| 参数名      | 类型                                       | 必填   | 说明        |
4321| -------- | ---------------------------------------- | ---- | --------- |
4322| options  | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是    | 跳转页面描述信息。 |
4323| callback | AsyncCallback&lt;void&gt;                | 是    | 异常响应回调。   |
4324
4325**错误码:**
4326
4327以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4328
4329| 错误码ID  | 错误信息                               |
4330| ------ | ---------------------------------- |
4331| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4332| 100001 | Internal error. |
4333| 100003 | Page stack error. Too many pages are pushed.  |
4334| 100004 | Named route error. The named route does not exist.  |
4335
4336**示例:**
4337
4338```ts
4339import { Router } from '@kit.ArkUI';
4340import { BusinessError } from '@kit.BasicServicesKit';
4341
4342let router:Router = uiContext.getRouter();
4343router.pushNamedRoute({
4344  name: 'myPage',
4345  params: {
4346    data1: 'message',
4347    data2: {
4348      data3: [123, 456, 789]
4349    }
4350  }
4351}, (err: Error) => {
4352  if (err) {
4353    let message = (err as BusinessError).message;
4354    let code = (err as BusinessError).code;
4355    console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
4356    return;
4357  }
4358  console.info('pushNamedRoute success');
4359})
4360```
4361### pushNamedRoute
4362
4363pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
4364
4365跳转到指定的命名路由页面,通过Promise获取跳转异常的返回结果。
4366
4367**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4368
4369**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4370
4371**参数:**
4372
4373| 参数名     | 类型                                       | 必填   | 说明         |
4374| ------- | ---------------------------------------- | ---- | ---------- |
4375| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是    | 跳转页面描述信息。  |
4376| mode    | [router.RouterMode](js-apis-router.md#routermode9) | 是    | 跳转页面使用的模式。 |
4377
4378**返回值:**
4379
4380| 类型                  | 说明      |
4381| ------------------- | ------- |
4382| Promise&lt;void&gt; | 异常返回结果。 |
4383
4384**错误码:**
4385
4386以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4387
4388| 错误码ID  | 错误信息                               |
4389| ------ | ---------------------------------- |
4390| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4391| 100001 | Internal error. |
4392| 100003 | Page stack error. Too many pages are pushed.  |
4393| 100004 | Named route error. The named route does not exist.  |
4394
4395**示例:**
4396
4397```ts
4398import { Router, router } from '@kit.ArkUI';
4399import { BusinessError } from '@kit.BasicServicesKit';
4400
4401let routerF:Router = uiContext.getRouter();
4402class RouterTmp{
4403  Standard:router.RouterMode = router.RouterMode.Standard
4404}
4405let rtm:RouterTmp = new RouterTmp()
4406try {
4407  routerF.pushNamedRoute({
4408    name: 'myPage',
4409    params: {
4410      data1: 'message',
4411      data2: {
4412        data3: [123, 456, 789]
4413      }
4414    }
4415  }, rtm.Standard)
4416} catch (err) {
4417  let message = (err as BusinessError).message;
4418  let code = (err as BusinessError).code;
4419  console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
4420}
4421```
4422
4423### pushNamedRoute
4424
4425pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
4426
4427跳转到指定的命名路由页面。
4428
4429**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4430
4431**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4432
4433**参数:**
4434
4435| 参数名      | 类型                                       | 必填   | 说明         |
4436| -------- | ---------------------------------------- | ---- | ---------- |
4437| options  | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是    | 跳转页面描述信息。  |
4438| mode     | [router.RouterMode](js-apis-router.md#routermode9) | 是    | 跳转页面使用的模式。 |
4439| callback | AsyncCallback&lt;void&gt;                | 是    | 异常响应回调。    |
4440
4441**错误码:**
4442
4443以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4444
4445| 错误码ID  | 错误信息                               |
4446| ------ | ---------------------------------- |
4447| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4448| 100001 | Internal error. |
4449| 100003 | Page stack error. Too many pages are pushed.  |
4450| 100004 | Named route error. The named route does not exist.   |
4451
4452**示例:**
4453
4454```ts
4455import { Router, router } from '@kit.ArkUI';
4456import { BusinessError } from '@kit.BasicServicesKit';
4457
4458let routerF:Router = uiContext.getRouter();
4459class RouterTmp{
4460  Standard:router.RouterMode = router.RouterMode.Standard
4461}
4462let rtm:RouterTmp = new RouterTmp()
4463routerF.pushNamedRoute({
4464  name: 'myPage',
4465  params: {
4466    data1: 'message',
4467    data2: {
4468      data3: [123, 456, 789]
4469    }
4470  }
4471}, rtm.Standard, (err: Error) => {
4472  if (err) {
4473    let message = (err as BusinessError).message;
4474    let code = (err as BusinessError).code;
4475    console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
4476    return;
4477  }
4478  console.info('pushNamedRoute success');
4479})
4480```
4481
4482### replaceNamedRoute
4483
4484replaceNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt;
4485
4486用指定的命名路由页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。
4487
4488**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4489
4490**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4491
4492**参数:**
4493
4494| 参数名     | 类型                                       | 必填   | 说明        |
4495| ------- | ---------------------------------------- | ---- | --------- |
4496| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是    | 替换页面描述信息。 |
4497
4498**返回值:**
4499
4500| 类型                  | 说明      |
4501| ------------------- | ------- |
4502| Promise&lt;void&gt; | 异常返回结果。 |
4503
4504**错误码:**
4505
4506以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4507
4508| 错误码ID  | 错误信息                                     |
4509| ------ | ---------------------------------------- |
4510| 401      | if the number of parameters is less than 1 or the type of the url parameter is not string. |
4511| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
4512| 100004 | Named route error. The named route does not exist.        |
4513
4514**示例:**
4515
4516```ts
4517import { Router } from '@kit.ArkUI';
4518import { BusinessError } from '@kit.BasicServicesKit';
4519
4520let router:Router = uiContext.getRouter();
4521try {
4522  router.replaceNamedRoute({
4523    name: 'myPage',
4524    params: {
4525      data1: 'message'
4526    }
4527  })
4528} catch (err) {
4529  let message = (err as BusinessError).message;
4530  let code = (err as BusinessError).code;
4531  console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`);
4532}
4533```
4534
4535### replaceNamedRoute
4536
4537replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt;void&gt;): void
4538
4539用指定的命名路由页面替换当前页面,并销毁被替换的页面。
4540
4541**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4542
4543**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4544
4545**参数:**
4546
4547| 参数名      | 类型                                       | 必填   | 说明        |
4548| -------- | ---------------------------------------- | ---- | --------- |
4549| options  | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是    | 替换页面描述信息。 |
4550| callback | AsyncCallback&lt;void&gt;                | 是    | 异常响应回调。   |
4551
4552**错误码:**
4553
4554以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4555
4556| 错误码ID  | 错误信息                                     |
4557| ------ | ---------------------------------------- |
4558| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4559| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
4560| 100004 | Named route error. The named route does not exist.         |
4561
4562**示例:**
4563
4564```ts
4565import { Router } from '@kit.ArkUI';
4566import { BusinessError } from '@kit.BasicServicesKit';
4567
4568let router:Router = uiContext.getRouter();
4569router.replaceNamedRoute({
4570  name: 'myPage',
4571  params: {
4572    data1: 'message'
4573  }
4574}, (err: Error) => {
4575  if (err) {
4576    let message = (err as BusinessError).message;
4577    let code = (err as BusinessError).code;
4578    console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`);
4579    return;
4580  }
4581  console.info('replaceNamedRoute success');
4582})
4583```
4584
4585### replaceNamedRoute
4586
4587replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
4588
4589用指定的命名路由页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。
4590
4591**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4592
4593**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4594
4595**参数:**
4596
4597| 参数名     | 类型                                       | 必填   | 说明         |
4598| ------- | ---------------------------------------- | ---- | ---------- |
4599| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是    | 替换页面描述信息。  |
4600| mode    | [router.RouterMode](js-apis-router.md#routermode9) | 是    | 跳转页面使用的模式。 |
4601
4602
4603**返回值:**
4604
4605| 类型                  | 说明      |
4606| ------------------- | ------- |
4607| Promise&lt;void&gt; | 异常返回结果。 |
4608
4609**错误码:**
4610
4611以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4612
4613| 错误码ID  | 错误信息                                     |
4614| ------ | ---------------------------------------- |
4615| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4616| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. |
4617| 100004 | Named route error. The named route does not exist.       |
4618
4619**示例:**
4620
4621```ts
4622import { Router, router } from '@kit.ArkUI';
4623import { BusinessError } from '@kit.BasicServicesKit';
4624
4625let routerF:Router = uiContext.getRouter();
4626class RouterTmp{
4627  Standard:router.RouterMode = router.RouterMode.Standard
4628}
4629let rtm:RouterTmp = new RouterTmp()
4630try {
4631  routerF.replaceNamedRoute({
4632    name: 'myPage',
4633    params: {
4634      data1: 'message'
4635    }
4636  }, rtm.Standard)
4637} catch (err) {
4638  let message = (err as BusinessError).message;
4639  let code = (err as BusinessError).code;
4640  console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`);
4641}
4642```
4643
4644### replaceNamedRoute
4645
4646replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
4647
4648用指定的命名路由页面替换当前页面,并销毁被替换的页面。
4649
4650**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4651
4652**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4653
4654**参数:**
4655
4656| 参数名      | 类型                                       | 必填   | 说明         |
4657| -------- | ---------------------------------------- | ---- | ---------- |
4658| options  | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是    | 替换页面描述信息。  |
4659| mode     | [router.RouterMode](js-apis-router.md#routermode9) | 是    | 跳转页面使用的模式。 |
4660| callback | AsyncCallback&lt;void&gt;                | 是    | 异常响应回调。    |
4661
4662**错误码:**
4663
4664以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4665
4666| 错误码ID  | 错误信息                                     |
4667| ------ | ---------------------------------------- |
4668| 401      | if the number of parameters is less than 1 or the type of the url parameter is not string. |
4669| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
4670| 100004 | Named route error. The named route does not exist.        |
4671
4672**示例:**
4673
4674```ts
4675import { Router, router } from '@kit.ArkUI';
4676import { BusinessError } from '@kit.BasicServicesKit';
4677
4678let routerF:Router = uiContext.getRouter();
4679class RouterTmp{
4680  Standard:router.RouterMode = router.RouterMode.Standard
4681}
4682let rtm:RouterTmp = new RouterTmp()
4683routerF.replaceNamedRoute({
4684  name: 'myPage',
4685  params: {
4686    data1: 'message'
4687  }
4688}, rtm.Standard, (err: Error) => {
4689  if (err) {
4690    let message = (err as BusinessError).message;
4691    let code = (err as BusinessError).code;
4692    console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`);
4693    return;
4694  }
4695  console.info('replaceNamedRoute success');
4696});
4697```
4698
4699### back
4700
4701back(options?: router.RouterOptions ): void
4702
4703返回上一页面或指定的页面。
4704
4705**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4706
4707**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4708
4709**参数:**
4710
4711| 参数名     | 类型                                       | 必填   | 说明                                       |
4712| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
4713| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 否    | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面不会重新构建,页面栈里面的page不会回收,出栈后会被回收。 |
4714
4715**示例:**
4716
4717```ts
4718import { Router } from '@kit.ArkUI';
4719let router: Router = uiContext.getRouter();
4720router.back({url:'pages/detail'});
4721```
4722
4723### back<sup>12+</sup>
4724
4725back(index: number, params?: Object): void;
4726
4727返回指定的页面。
4728
4729**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
4730
4731**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4732
4733**参数:**
4734
4735| 参数名     | 类型                              | 必填   | 说明         |
4736| ------- | ------------------------------- | ---- | ---------- |
4737| index | number | 是    | 跳转目标页面的索引值。  |
4738| params    | Object      | 否    | 页面返回时携带的参数。 |
4739
4740**示例:**
4741
4742```ts
4743import { Router } from '@kit.ArkUI';
4744
4745let router: Router = uiContext.getRouter();
4746router.back(1);
4747```
4748
4749```ts
4750import { Router } from '@kit.ArkUI';
4751
4752let router: Router = uiContext.getRouter();
4753router.back(1, {info:'来自Home页'}); //携带参数返回
4754```
4755
4756### clear
4757
4758clear(): void
4759
4760清空页面栈中的所有历史页面,仅保留当前页面作为栈顶页面。
4761
4762**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4763
4764**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4765
4766**示例:**
4767
4768```ts
4769import { Router } from '@kit.ArkUI';
4770
4771let router: Router = uiContext.getRouter();
4772router.clear();
4773```
4774
4775### getLength
4776
4777getLength(): string
4778
4779获取当前在页面栈内的页面数量。
4780
4781**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4782
4783**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4784
4785**返回值:**
4786
4787| 类型     | 说明                 |
4788| ------ | ------------------ |
4789| string | 页面数量,页面栈支持最大数值是32。 |
4790
4791**示例:**
4792
4793```ts
4794import { Router } from '@kit.ArkUI';
4795
4796let router: Router = uiContext.getRouter();
4797let size = router.getLength();
4798console.info('pages stack size = ' + size);
4799```
4800
4801### getState
4802
4803getState(): router.RouterState
4804
4805获取当前页面的状态信息。
4806
4807**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4808
4809**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4810
4811**返回值:**
4812
4813| 类型                                       | 说明      |
4814| ---------------------------------------- | ------- |
4815| router.[RouterState](js-apis-router.md#routerstate) | 页面状态信息。 |
4816
4817**示例:**
4818
4819```ts
4820import { Router } from '@kit.ArkUI';
4821
4822let router: Router = uiContext.getRouter();
4823let page = router.getState();
4824console.info('current index = ' + page.index);
4825console.info('current name = ' + page.name);
4826console.info('current path = ' + page.path);
4827```
4828
4829### getStateByIndex<sup>12+</sup>
4830
4831getStateByIndex(index: number): router.RouterState | undefined
4832
4833通过索引值获取对应页面的状态信息。
4834
4835**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
4836
4837**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4838
4839**参数:**
4840
4841| 参数名     | 类型                              | 必填   | 说明         |
4842| ------- | ------------------------------- | ---- | ---------- |
4843| index    | number | 是   | 表示要获取的页面索引。  |
4844
4845**返回值:**
4846
4847| 类型                          | 说明      |
4848| --------------------------- | ------- |
4849| router.[RouterState](js-apis-router.md#outerstate) \| undefined | 返回页面状态信息。索引不存在时返回undefined。 |
4850
4851**示例:**
4852
4853```ts
4854import { Router } from '@kit.ArkUI';
4855
4856let router: Router = uiContext.getRouter();
4857let options: router.RouterState | undefined = router.getStateByIndex(1);
4858if (options != undefined) {
4859  console.info('index = ' + options.index);
4860  console.info('name = ' + options.name);
4861  console.info('path = ' + options.path);
4862  console.info('params = ' + options.params);
4863}
4864```
4865### getStateByUrl<sup>12+</sup>
4866
4867getStateByUrl(url: string): Array<router.[RouterState](js-apis-router.md#outerstate)>
4868
4869通过url获取当前页面的状态信息。
4870
4871**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
4872
4873**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4874
4875**参数:**
4876
4877| 参数名     | 类型                              | 必填   | 说明         |
4878| ------- | ------------------------------- | ---- | ---------- |
4879| url    | string | 是   | 表示要获取对应页面信息的url。  |
4880
4881**返回值:**
4882
4883| 类型                          | 说明      |
4884| --------------------------- | ------- |
4885| Array<router.[RouterState](js-apis-router.md#outerstate)> | 页面状态信息。 |
4886
4887**示例:**
4888
4889```ts
4890import { Router } from '@kit.ArkUI';
4891let router: Router = uiContext.getRouter();
4892let options:Array<router.RouterState> = router.getStateByUrl('pages/index');
4893for (let i: number = 0; i < options.length; i++) {
4894  console.info('index = ' + options[i].index);
4895  console.info('name = ' + options[i].name);
4896  console.info('path = ' + options[i].path);
4897  console.info('params = ' + options[i].params);
4898}
4899```
4900
4901### showAlertBeforeBackPage
4902
4903showAlertBeforeBackPage(options: router.EnableAlertOptions): void
4904
4905开启页面返回询问对话框。
4906
4907**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4908
4909**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4910
4911**参数:**
4912
4913| 参数名     | 类型                                       | 必填   | 说明        |
4914| ------- | ---------------------------------------- | ---- | --------- |
4915| options | [router.EnableAlertOptions](js-apis-router.md#enablealertoptions) | 是    | 文本弹窗信息描述。 |
4916
4917**错误码:**
4918
4919以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
4920
4921| 错误码ID  | 错误信息                               |
4922| ------ | ---------------------------------- |
4923| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4924| 100001 | Internal error. |
4925
4926**示例:**
4927
4928```ts
4929import { Router } from '@kit.ArkUI';
4930import { BusinessError } from '@kit.BasicServicesKit';
4931
4932let router: Router = uiContext.getRouter();
4933try {
4934  router.showAlertBeforeBackPage({
4935    message: 'Message Info'
4936  });
4937} catch(error) {
4938  let message = (error as BusinessError).message;
4939  let code = (error as BusinessError).code;
4940  console.error(`showAlertBeforeBackPage failed, code is ${code}, message is ${message}`);
4941}
4942```
4943
4944### hideAlertBeforeBackPage
4945
4946hideAlertBeforeBackPage(): void
4947
4948禁用页面返回询问对话框。
4949
4950**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4951
4952**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4953
4954**示例:**
4955
4956```ts
4957import { Router } from '@kit.ArkUI';
4958
4959let router: Router = uiContext.getRouter();
4960router.hideAlertBeforeBackPage();
4961```
4962
4963### getParams
4964
4965getParams(): Object
4966
4967获取发起跳转的页面往当前页传入的参数。
4968
4969**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4970
4971**系统能力:** SystemCapability.ArkUI.ArkUI.Full
4972
4973**返回值:**
4974
4975| 类型     | 说明                |
4976| ------ | ----------------- |
4977| object | 发起跳转的页面往当前页传入的参数。 |
4978
4979**示例:**
4980
4981```ts
4982import { Router } from '@kit.ArkUI';
4983
4984let router: Router = uiContext.getRouter();
4985router.getParams();
4986```
4987
4988## PromptAction
4989
4990以下API需先使用UIContext中的[getPromptAction()](#getpromptaction)方法获取到PromptAction对象,再通过该对象调用对应方法。
4991
4992### showToast
4993
4994showToast(options: promptAction.ShowToastOptions): void
4995
4996创建并显示文本提示框。
4997
4998**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
4999
5000**系统能力:** SystemCapability.ArkUI.ArkUI.Full
5001
5002**参数:**
5003
5004| 参数名     | 类型                                       | 必填   | 说明      |
5005| ------- | ---------------------------------------- | ---- | ------- |
5006| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | 是    | 文本弹窗选项。 |
5007
5008**错误码:**
5009
5010以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
5011
5012| 错误码ID  | 错误信息                               |
5013| ------ | ---------------------------------- |
5014| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5015| 100001 | Internal error. |
5016
5017**示例:**
5018
5019```ts
5020import { PromptAction } from '@kit.ArkUI';
5021import { BusinessError } from '@kit.BasicServicesKit';
5022
5023let promptAction: PromptAction = uiContext.getPromptAction();
5024try {
5025  promptAction.showToast({
5026    message: 'Message Info',
5027    duration: 2000
5028  });
5029} catch (error) {
5030  let message = (error as BusinessError).message;
5031  let code = (error as BusinessError).code;
5032  console.error(`showToast args error code is ${code}, message is ${message}`);
5033};
5034```
5035
5036### showDialog
5037
5038showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback&lt;promptAction.ShowDialogSuccessResponse&gt;): void
5039
5040创建并显示对话框,对话框响应结果异步返回。
5041
5042**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
5043
5044**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
5045
5046**参数:**
5047
5048| 参数名      | 类型                                       | 必填   | 说明           |
5049| -------- | ---------------------------------------- | ---- | ------------ |
5050| options  | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | 是    | 页面显示对话框信息描述。 |
5051| callback | AsyncCallback&lt;[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)&gt; | 是    | 对话框响应结果回调。   |
5052
5053**错误码:**
5054
5055以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
5056
5057| 错误码ID  | 错误信息                               |
5058| ------ | ---------------------------------- |
5059| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5060| 100001 | Internal error. |
5061
5062**示例:**
5063
5064```ts
5065import { PromptAction } from '@kit.ArkUI';
5066import { BusinessError } from '@kit.BasicServicesKit';
5067
5068class ButtonsModel {
5069  text: string = ""
5070  color: string = ""
5071}
5072let promptAction: PromptAction = uiContext.getPromptAction();
5073try {
5074  promptAction.showDialog({
5075    title: 'showDialog Title Info',
5076    message: 'Message Info',
5077    buttons: [
5078      {
5079        text: 'button1',
5080        color: '#000000'
5081      } as ButtonsModel,
5082      {
5083        text: 'button2',
5084        color: '#000000'
5085      } as ButtonsModel
5086    ]
5087  }, (err, data) => {
5088    if (err) {
5089      console.error('showDialog err: ' + err);
5090      return;
5091    }
5092    console.info('showDialog success callback, click button: ' + data.index);
5093  });
5094} catch (error) {
5095  let message = (error as BusinessError).message;
5096  let code = (error as BusinessError).code;
5097  console.error(`showDialog args error code is ${code}, message is ${message}`);
5098};
5099```
5100
5101### showDialog
5102
5103showDialog(options: promptAction.ShowDialogOptions): Promise&lt;promptAction.ShowDialogSuccessResponse&gt;
5104
5105创建并显示对话框,对话框响应后同步返回结果,通过Promise获取对话框响应结果。
5106
5107**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
5108
5109**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
5110
5111**参数:**
5112
5113| 参数名     | 类型                                       | 必填   | 说明     |
5114| ------- | ---------------------------------------- | ---- | ------ |
5115| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | 是    | 对话框选项。 |
5116
5117**返回值:**
5118
5119| 类型                                       | 说明       |
5120| ---------------------------------------- | -------- |
5121| Promise&lt;[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)&gt; | 对话框响应结果。 |
5122
5123**错误码:**
5124
5125以下错误码的详细介绍请参见[ 通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
5126
5127| 错误码ID  | 错误信息                               |
5128| ------ | ---------------------------------- |
5129| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5130| 100001 | Internal error. |
5131
5132**示例:**
5133
5134```ts
5135import { PromptAction } from '@kit.ArkUI';
5136import { BusinessError } from '@kit.BasicServicesKit';
5137
5138let promptAction: PromptAction = uiContext.getPromptAction();
5139try {
5140  promptAction.showDialog({
5141    title: 'Title Info',
5142    message: 'Message Info',
5143    buttons: [
5144      {
5145        text: 'button1',
5146        color: '#000000'
5147      },
5148      {
5149        text: 'button2',
5150        color: '#000000'
5151      }
5152    ],
5153  })
5154    .then(data => {
5155      console.info('showDialog success, click button: ' + data.index);
5156    })
5157    .catch((err:Error) => {
5158      console.error('showDialog error: ' + err);
5159    })
5160} catch (error) {
5161  let message = (error as BusinessError).message;
5162  let code = (error as BusinessError).code;
5163  console.error(`showDialog args error code is ${code}, message is ${message}`);
5164};
5165```
5166
5167### showActionMenu<sup>11+</sup>
5168
5169showActionMenu(options: promptAction.ActionMenuOptions, callback: AsyncCallback&lt;[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)&gt;):void
5170
5171创建并显示操作菜单,菜单响应结果异步返回。
5172
5173**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
5174
5175**系统能力:** SystemCapability.ArkUI.ArkUI.Full
5176
5177**参数:**
5178
5179| 参数名   | 类型                                                         | 必填 | 说明               |
5180| -------- | ------------------------------------------------------------ | ---- | ------------------ |
5181| options  | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是   | 操作菜单选项。     |
5182| callback | AsyncCallback&lt;[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)&gt; | 是   | 菜单响应结果回调。 |
5183
5184**错误码:**
5185
5186以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
5187
5188| 错误码ID | 错误信息                           |
5189| -------- | ---------------------------------- |
5190| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5191| 100001   | Internal error. |
5192
5193**示例:**
5194
5195```ts
5196import { PromptAction, promptAction  } from '@kit.ArkUI';
5197import { BusinessError } from '@kit.BasicServicesKit';
5198
5199let promptActionF: PromptAction = uiContext.getPromptAction();
5200try {
5201  promptActionF.showActionMenu({
5202    title: 'Title Info',
5203    buttons: [
5204      {
5205        text: 'item1',
5206        color: '#666666'
5207      },
5208      {
5209        text: 'item2',
5210        color: '#000000'
5211      }
5212    ]
5213  }, (err:BusinessError, data:promptAction.ActionMenuSuccessResponse) => {
5214    if (err) {
5215      console.error('showDialog err: ' + err);
5216      return;
5217    }
5218    console.info('showDialog success callback, click button: ' + data.index);
5219  });
5220} catch (error) {
5221  let message = (error as BusinessError).message;
5222  let code = (error as BusinessError).code;
5223  console.error(`showActionMenu args error code is ${code}, message is ${message}`);
5224};
5225```
5226
5227### showActionMenu<sup>(deprecated)</sup>
5228
5229showActionMenu(options: promptAction.ActionMenuOptions, callback: [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)):void
5230
5231创建并显示操作菜单,菜单响应结果异步返回。
5232
5233从API version11开始不再维护,建议使用[showActionMenu](#showactionmenu11)。
5234
5235**系统能力:** SystemCapability.ArkUI.ArkUI.Full5236
5237**参数:**
5238
5239| 参数名   | 类型                                                         | 必填 | 说明               |
5240| -------- | ------------------------------------------------------------ | ---- | ------------------ |
5241| options  | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是   | 操作菜单选项。     |
5242| callback | [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse) | 是   | 菜单响应结果回调。 |
5243
5244**错误码:**
5245
5246以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
5247
5248| 错误码ID  | 错误信息                               |
5249| ------ | ---------------------------------- |
5250| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5251| 100001 | Internal error. |
5252
5253**示例:**
5254
5255```ts
5256import { PromptAction,promptAction  } from '@kit.ArkUI';
5257import { BusinessError } from '@kit.BasicServicesKit';
5258
5259let promptActionF: PromptAction = uiContext.getPromptAction();
5260try {
5261  promptActionF.showActionMenu({
5262    title: 'Title Info',
5263    buttons: [
5264      {
5265        text: 'item1',
5266        color: '#666666'
5267      },
5268      {
5269        text: 'item2',
5270        color: '#000000'
5271      }
5272    ]
5273  }, { index:0 });
5274} catch (error) {
5275  let message = (error as BusinessError).message;
5276  let code = (error as BusinessError).code;
5277  console.error(`showActionMenu args error code is ${code}, message is ${message}`);
5278};
5279```
5280
5281### showActionMenu
5282
5283showActionMenu(options: promptAction.ActionMenuOptions): Promise&lt;promptAction.ActionMenuSuccessResponse&gt;
5284
5285创建并显示操作菜单,通过Promise获取菜单响应结果。
5286
5287**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
5288
5289**系统能力:** SystemCapability.ArkUI.ArkUI.Full
5290
5291**参数:**
5292
5293| 参数名     | 类型                                       | 必填   | 说明      |
5294| ------- | ---------------------------------------- | ---- | ------- |
5295| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是    | 操作菜单选项。 |
5296
5297**返回值:**
5298
5299| 类型                                       | 说明      |
5300| ---------------------------------------- | ------- |
5301| Promise&lt;[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)&gt; | 菜单响应结果。 |
5302
5303**错误码:**
5304
5305以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
5306
5307| 错误码ID  | 错误信息                               |
5308| ------ | ---------------------------------- |
5309| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5310| 100001 | Internal error. |
5311
5312**示例:**
5313
5314```ts
5315import { PromptAction,promptAction  } from '@kit.ArkUI';
5316import { BusinessError } from '@kit.BasicServicesKit';
5317
5318let promptAction: PromptAction = uiContext.getPromptAction();
5319try {
5320  promptAction.showActionMenu({
5321    title: 'showActionMenu Title Info',
5322    buttons: [
5323      {
5324        text: 'item1',
5325        color: '#666666'
5326      },
5327      {
5328        text: 'item2',
5329        color: '#000000'
5330      },
5331    ]
5332  })
5333    .then(data => {
5334      console.info('showActionMenu success, click button: ' + data.index);
5335    })
5336    .catch((err:Error) => {
5337      console.error('showActionMenu error: ' + err);
5338    })
5339} catch (error) {
5340  let message = (error as BusinessError).message;
5341  let code = (error as BusinessError).code;
5342  console.error(`showActionMenu args error code is ${code}, message is ${message}`);
5343};
5344```
5345
5346### openCustomDialog<sup>12+</sup>
5347
5348openCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>, options?: promptAction.BaseDialogOptions): Promise&lt;void&gt;
5349
5350创建并弹出dialogContent对应的自定义弹窗,使用Promise异步回调。通过该接口弹出的弹窗内容样式完全按照dialogContent中设置的样式显示,即相当于customdialog设置customStyle为true时的显示效果。暂不支持isModal = true与showInSubWindow = true同时使用。
5351
5352**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
5353
5354**系统能力:** SystemCapability.ArkUI.ArkUI.Full
5355
5356**参数:**
5357
5358| 参数名     | 类型                                       | 必填   | 说明      |
5359| ------- | ---------------------------------------- | ---- | ------- |
5360| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 |
5361| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | 否    |   弹窗样式。 |
5362
5363**返回值:**
5364
5365| 类型                                       | 说明      |
5366| ---------------------------------------- | ------- |
5367|   Promise&lt;void&gt;           |    异常返回Promise对象。 |
5368
5369**错误码:**
5370
5371以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
5372
5373| 错误码ID  | 错误信息                               |
5374| ------ | ---------------------------------- |
5375| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5376| 103301 | the ComponentContent is incorrect. |
5377| 103302 | Dialog content already exists.|
5378
5379**示例:**
5380
5381```ts
5382import { BusinessError } from '@kit.BasicServicesKit';
5383import { ComponentContent } from '@kit.ArkUI';
5384
5385class Params {
5386  text: string = ""
5387  constructor(text: string) {
5388    this.text = text;
5389  }
5390}
5391
5392@Builder
5393function buildText(params: Params) {
5394  Column() {
5395    Text(params.text)
5396      .fontSize(50)
5397      .fontWeight(FontWeight.Bold)
5398      .margin({bottom: 36})
5399  }.backgroundColor('#FFF0F0F0')
5400}
5401
5402@Entry
5403@Component
5404struct Index {
5405  @State message: string = "hello"
5406
5407  build() {
5408    Row() {
5409      Column() {
5410        Button("click me")
5411            .onClick(() => {
5412                let uiContext = this.getUIContext();
5413                let promptAction = uiContext.getPromptAction();
5414                let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
5415                try {
5416                  promptAction.openCustomDialog(contentNode);
5417                } catch (error) {
5418                  let message = (error as BusinessError).message;
5419                  let code = (error as BusinessError).code;
5420                  console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
5421                };
5422            })
5423      }
5424      .width('100%')
5425      .height('100%')
5426    }
5427    .height('100%')
5428  }
5429}
5430```
5431
5432### closeCustomDialog<sup>12+</sup>
5433
5434closeCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>): Promise&lt;void&gt;
5435
5436关闭已弹出的dialogContent对应的自定义弹窗,使用Promise异步回调。
5437
5438**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
5439
5440**系统能力:** SystemCapability.ArkUI.ArkUI.Full
5441
5442**参数:**
5443
5444| 参数名     | 类型                                       | 必填   | 说明      |
5445| ------- | ---------------------------------------- | ---- | ------- |
5446| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 |
5447
5448**返回值:**
5449
5450| 类型                                       | 说明      |
5451| ---------------------------------------- | ------- |
5452|   Promise&lt;void&gt;           |    异常返回Promise对象。 |
5453
5454**错误码:**
5455
5456以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
5457
5458| 错误码ID  | 错误信息                               |
5459| ------ | ---------------------------------- |
5460| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5461| 103301 | the ComponentContent is incorrect. |
5462| 103303 | the ComponentContent cannot be found. |
5463
5464**示例:**
5465
5466```ts
5467import { BusinessError } from '@kit.BasicServicesKit';
5468import { ComponentContent } from '@kit.ArkUI';
5469
5470class Params {
5471  text: string = ""
5472  constructor(text: string) {
5473    this.text = text;
5474  }
5475}
5476
5477@Builder
5478function buildText(params: Params) {
5479  Column() {
5480    Text(params.text)
5481      .fontSize(50)
5482      .fontWeight(FontWeight.Bold)
5483      .margin({bottom: 36})
5484  }.backgroundColor('#FFF0F0F0')
5485}
5486
5487@Entry
5488@Component
5489struct Index {
5490  @State message: string = "hello"
5491
5492  build() {
5493    Row() {
5494      Column() {
5495        Button("click me")
5496            .onClick(() => {
5497                let uiContext = this.getUIContext();
5498                let promptAction = uiContext.getPromptAction();
5499                let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
5500                try {
5501                  promptAction.openCustomDialog(contentNode);
5502                } catch (error) {
5503                  let message = (error as BusinessError).message;
5504                  let code = (error as BusinessError).code;
5505                  console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
5506                };
5507
5508                setTimeout(() => {
5509                  try {
5510                    promptAction.closeCustomDialog(contentNode);
5511                  } catch (error) {
5512                    let message = (error as BusinessError).message;
5513                    let code = (error as BusinessError).code;
5514                    console.error(`closeCustomDialog args error code is ${code}, message is ${message}`);
5515                  };
5516                }, 2000);     //2秒后自动关闭
5517            })
5518      }
5519      .width('100%')
5520      .height('100%')
5521    }
5522    .height('100%')
5523  }
5524}
5525```
5526
5527### updateCustomDialog<sup>12+</sup>
5528
5529updateCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>, options: promptAction.BaseDialogOptions): Promise&lt;void&gt;
5530
5531更新已弹出的dialogContent对应的自定义弹窗的样式,使用Promise异步回调。
5532
5533**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
5534
5535**系统能力:** SystemCapability.ArkUI.ArkUI.Full
5536
5537**参数:**
5538
5539| 参数名     | 类型                                       | 必填   | 说明      |
5540| ------- | ---------------------------------------- | ---- | ------- |
5541| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 |
5542| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | 是    |   弹窗样式,目前仅支持更新alignment、offset、autoCancel、maskColor。 |
5543
5544**返回值:**
5545
5546| 类型                                       | 说明      |
5547| ---------------------------------------- | ------- |
5548|   Promise&lt;void&gt;           |    异常返回Promise对象。 |
5549
5550**错误码:**
5551
5552以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
5553
5554| 错误码ID  | 错误信息                               |
5555| ------ | ---------------------------------- |
5556| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5557| 103301 | the ComponentContent is incorrect. |
5558| 103303 | the ComponentContent cannot be found. |
5559
5560**示例:**
5561
5562```ts
5563import { BusinessError } from '@kit.BasicServicesKit';
5564import { ComponentContent } from '@kit.ArkUI';
5565
5566class Params {
5567  text: string = ""
5568  constructor(text: string) {
5569    this.text = text;
5570  }
5571}
5572
5573@Builder
5574function buildText(params: Params) {
5575  Column() {
5576    Text(params.text)
5577      .fontSize(50)
5578      .fontWeight(FontWeight.Bold)
5579      .margin({bottom: 36})
5580  }.backgroundColor('#FFF0F0F0')
5581}
5582
5583@Entry
5584@Component
5585struct Index {
5586  @State message: string = "hello"
5587
5588  build() {
5589    Row() {
5590      Column() {
5591        Button("click me")
5592            .onClick(() => {
5593                let uiContext = this.getUIContext();
5594                let promptAction = uiContext.getPromptAction();
5595                let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
5596                try {
5597                  promptAction.openCustomDialog(contentNode);
5598                } catch (error) {
5599                  let message = (error as BusinessError).message;
5600                  let code = (error as BusinessError).code;
5601                  console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
5602                };
5603
5604                setTimeout(() => {
5605                  try {
5606                    promptAction.updateCustomDialog(contentNode, { alignment: DialogAlignment.CenterEnd });
5607                  } catch (error) {
5608                    let message = (error as BusinessError).message;
5609                    let code = (error as BusinessError).code;
5610                    console.error(`updateCustomDialog args error code is ${code}, message is ${message}`);
5611                  };
5612                }, 2000);   //2秒后自动更新弹窗位置
5613            })
5614      }
5615      .width('100%')
5616      .height('100%')
5617    }
5618    .height('100%')
5619  }
5620}
5621```
5622
5623### openCustomDialog<sup>12+</sup>
5624
5625openCustomDialog(options: promptAction.CustomDialogOptions): Promise\<number>
5626
5627创建并弹出自定义弹窗。使用Promise异步回调,返回供closeCustomDialog使用的对话框id。暂不支持isModal = true与showInSubWindow = true同时使用。
5628
5629**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
5630
5631**系统能力:** SystemCapability.ArkUI.ArkUI.Full
5632
5633**参数:**
5634
5635| 参数名  | 类型                                                         | 必填 | 说明               |
5636| ------- | ------------------------------------------------------------ | ---- | ------------------ |
5637| options | [promptAction.CustomDialogOptions](js-apis-promptAction.md#customdialogoptions11) | 是   | 自定义弹窗的内容。 |
5638
5639**返回值:**
5640
5641| 类型                | 说明                                    |
5642| ------------------- | --------------------------------------- |
5643| Promise&lt;void&gt; | 返回供closeCustomDialog使用的对话框id。 |
5644
5645**错误码:**
5646
5647以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
5648
5649| 错误码ID | 错误信息                                                     |
5650| -------- | ------------------------------------------------------------ |
5651| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
5652| 100001   | Internal error.                                              |
5653
5654### closeCustomDialog<sup>12+</sup>
5655
5656closeCustomDialog(dialogId: number): void
5657
5658关闭自定义弹窗。
5659
5660**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
5661
5662**系统能力:** SystemCapability.ArkUI.ArkUI.Full
5663
5664**参数:**
5665
5666| 参数名   | 类型   | 必填 | 说明                             |
5667| -------- | ------ | ---- | -------------------------------- |
5668| dialogId | number | 是   | openCustomDialog返回的对话框id。 |
5669
5670**错误码:**
5671
5672以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
5673
5674| 错误码ID | 错误信息                                                     |
5675| -------- | ------------------------------------------------------------ |
5676| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
5677| 100001   | Internal error.                                              |
5678
5679**示例:**
5680
5681```ts
5682import { PromptAction } from '@kit.ArkUI';
5683
5684@Entry
5685@Component
5686struct Index {
5687  promptAction: PromptAction = this.getUIContext().getPromptAction()
5688  private customDialogComponentId: number = 0
5689
5690  @Builder
5691  customDialogComponent() {
5692    Column() {
5693      Text('弹窗').fontSize(30)
5694      Row({ space: 50 }) {
5695        Button("确认").onClick(() => {
5696          this.promptAction.closeCustomDialog(this.customDialogComponentId)
5697        })
5698        Button("取消").onClick(() => {
5699          this.promptAction.closeCustomDialog(this.customDialogComponentId)
5700        })
5701      }
5702    }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
5703  }
5704
5705  build() {
5706    Row() {
5707      Column() {
5708        Button("click me")
5709          .onClick(() => {
5710            this.promptAction.openCustomDialog({
5711              builder: () => {
5712                this.customDialogComponent()
5713              },
5714              onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
5715                console.info("reason" + JSON.stringify(dismissDialogAction.reason))
5716                console.log("dialog onWillDismiss")
5717                if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
5718                  dismissDialogAction.dismiss()
5719                }
5720                if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
5721                  dismissDialogAction.dismiss()
5722                }
5723              }
5724            }).then((dialogId: number) => {
5725              this.customDialogComponentId = dialogId
5726            })
5727          })
5728      }
5729      .width('100%')
5730      .height('100%')
5731    }
5732    .height('100%')
5733  }
5734}
5735```
5736
5737## DragController<sup>11+</sup>
5738以下API需先使用UIContext中的[getDragController()](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取UIContext实例,再通过此实例调用对应方法。
5739
5740### executeDrag<sup>11+</sup>
5741
5742executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo, callback: AsyncCallback&lt;dragController.DragEventParam&gt;): void
5743
5744主动发起拖拽能力,传入拖拽发起后跟手效果所拖拽的对象以及携带拖拽信息。通过回调返回拖拽事件结果。
5745
5746**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
5747
5748**系统能力:** SystemCapability.ArkUI.ArkUI.Full
5749
5750**参数:**
5751
5752| 参数名   | 类型                                                         | 必填 | 说明                                                         |
5753| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
5754| custom   | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明) | 是   | 拖拽发起后跟手效果所拖拽的对象。 <br/> **说明:** <br/>不支持全局builder。如果builder中使用了[Image](arkui-ts/ts-basic-components-image.md)组件,应尽量开启同步加载,即配置Image的[syncLoad](arkui-ts/ts-basic-components-image.md#syncload8)为true。该builder只用于生成当次拖拽中显示的图片,builder的修改不会同步到当前正在拖拽的图片,对builder的修改需要在下一次拖拽时生效。 |
5755| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | 是   | 拖拽信息。                                                   |
5756| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;[dragController.DragEventParam](js-apis-arkui-dragController.md#drageventparam12)&gt; | 是   | 拖拽结束返回结果的回调<br/>- event:拖拽事件信息,仅包括拖拽结果。<br/>- extraParams:拖拽事件额外信息。 |
5757
5758**错误码:**
5759以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
5760
5761| 错误码ID | 错误信息      |
5762| -------- | ------------- |
5763| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
5764| 100001   | Internal handling failed. |
5765
5766**示例:**
5767
5768```ts
5769import { dragController } from "@kit.ArkUI"
5770import { unifiedDataChannel } from '@kit.ArkData';
5771
5772@Entry
5773@Component
5774struct DragControllerPage {
5775  @Builder DraggingBuilder() {
5776    Column() {
5777      Text("DraggingBuilder")
5778    }
5779    .width(100)
5780    .height(100)
5781    .backgroundColor(Color.Blue)
5782  }
5783
5784  build() {
5785    Column() {
5786      Button('touch to execute drag')
5787        .onTouch((event?:TouchEvent) => {
5788          if(event){
5789            if (event.type == TouchType.Down) {
5790              let text = new unifiedDataChannel.Text()
5791              let unifiedData = new unifiedDataChannel.UnifiedData(text)
5792
5793              let dragInfo: dragController.DragInfo = {
5794                pointerId: 0,
5795                data: unifiedData,
5796                extraParams: ''
5797              }
5798              class tmp{
5799                event:DragEvent|undefined = undefined
5800                extraParams:string = ''
5801              }
5802              let eve:tmp = new tmp()
5803              dragController.executeDrag(()=>{this.DraggingBuilder()}, dragInfo, (err, eve) => {
5804                if(eve.event){
5805                  if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) {
5806                  // ...
5807                  } else if (eve.event.getResult() == DragResult.DRAG_FAILED) {
5808                  // ...
5809                  }
5810                }
5811              })
5812            }
5813          }
5814        })
5815    }
5816  }
5817}
5818```
5819
5820### executeDrag<sup>11+</sup>
5821
5822executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo): Promise&lt;dragController.DragEventParam&gt;
5823
5824主动发起拖拽能力,传入拖拽发起后跟手效果所拖拽的对象以及携带拖拽信息。通过Promise返回拖拽事件结果。
5825
5826**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
5827
5828**系统能力:** SystemCapability.ArkUI.ArkUI.Full
5829
5830**参数:**
5831
5832| 参数名   | 类型                                                         | 必填 | 说明                             |
5833| -------- | ------------------------------------------------------------ | ---- | -------------------------------- |
5834| custom   | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明) | 是   | 拖拽发起后跟手效果所拖拽的对象。 |
5835| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo)                                        | 是   | 拖拽信息。                       |
5836
5837**返回值:**
5838
5839| 类型                                                         | 说明                                                         |
5840| ------------------------------------------------------------ | ------------------------------------------------------------ |
5841| Promise&lt;[dragController.DragEventParam](js-apis-arkui-dragController.md#drageventparam12)&gt; | 拖拽结束返回结果的回调<br/>- event:拖拽事件信息,仅包括拖拽结果。<br/>- extraParams:拖拽事件额外信息。 |
5842
5843**错误码:**
5844以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
5845
5846| 错误码ID | 错误信息      |
5847| -------- | ------------- |
5848| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
5849| 100001   | Internal handling failed. |
5850
5851**示例:**
5852
5853```ts
5854import { dragController, componentSnapshot } from "@kit.ArkUI"
5855import { image } from '@kit.ImageKit';
5856import { unifiedDataChannel } from '@kit.ArkData';
5857
5858@Entry
5859@Component
5860struct DragControllerPage {
5861  @State pixmap: image.PixelMap|null = null
5862
5863  @Builder DraggingBuilder() {
5864    Column() {
5865      Text("DraggingBuilder")
5866    }
5867    .width(100)
5868    .height(100)
5869    .backgroundColor(Color.Blue)
5870  }
5871
5872  @Builder PixmapBuilder() {
5873    Column() {
5874      Text("PixmapBuilder")
5875    }
5876    .width(100)
5877    .height(100)
5878    .backgroundColor(Color.Blue)
5879  }
5880
5881  build() {
5882    Column() {
5883      Button('touch to execute drag')
5884        .onTouch((event?:TouchEvent) => {
5885          if(event){
5886            if (event.type == TouchType.Down) {
5887              let text = new unifiedDataChannel.Text()
5888              let unifiedData = new unifiedDataChannel.UnifiedData(text)
5889
5890              let dragInfo: dragController.DragInfo = {
5891                pointerId: 0,
5892                data: unifiedData,
5893                extraParams: ''
5894              }
5895              let pb:CustomBuilder = ():void=>{this.PixmapBuilder()}
5896              componentSnapshot.createFromBuilder(pb).then((pix: image.PixelMap) => {
5897                this.pixmap = pix;
5898                let dragItemInfo: DragItemInfo = {
5899                  pixelMap: this.pixmap,
5900                  builder: ()=>{this.DraggingBuilder()},
5901                  extraInfo: "DragItemInfoTest"
5902                }
5903
5904                class tmp{
5905                  event:DragResult|undefined = undefined
5906                  extraParams:string = ''
5907                }
5908                let eve:tmp = new tmp()
5909                dragController.executeDrag(dragItemInfo, dragInfo)
5910                  .then((eve) => {
5911                    if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) {
5912                      // ...
5913                    } else if (eve.event.getResult() == DragResult.DRAG_FAILED) {
5914                      // ...
5915                    }
5916                  })
5917                  .catch((err:Error) => {
5918                  })
5919              })
5920            }
5921          }
5922        })
5923    }
5924    .width('100%')
5925    .height('100%')
5926  }
5927}
5928```
5929
5930### createDragAction<sup>11+</sup>
5931
5932createDragAction(customArray: Array&lt;CustomBuilder \| DragItemInfo&gt;, dragInfo: dragController.DragInfo): dragController.DragAction
5933
5934创建拖拽的Action对象,需要显式指定拖拽背板图(可多个),以及拖拽的数据,跟手点等信息;当通过一个已创建的 Action 对象发起的拖拽未结束时,无法再次创建新的 Action 对象,接口会抛出异常;当Action对象的生命周期结束后,注册在该对象上的回调函数会失效,因此需要在一个尽量长的作用域下持有该对象,并在每次发起拖拽前通过createDragAction返回新的对象覆盖旧值。
5935
5936**说明:** 建议控制传递的拖拽背板数量,传递过多容易导致拖起的效率问题。
5937
5938**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
5939
5940**系统能力:** SystemCapability.ArkUI.ArkUI.Full
5941
5942**参数:**
5943
5944| 参数名   | 类型                                                         | 必填 | 说明                             |
5945| --------      | ------------------------------------------------------------ | ---- | -------------------------------- |
5946| customArray  | Array&lt;[CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明)&gt; | 是   | 拖拽发起后跟手效果所拖拽的对象。 |
5947| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo)                                | 是   | 拖拽信息。                       |
5948
5949**返回值:**
5950
5951| 类型                                                   | 说明               |
5952| ------------------------------------------------------ | ------------------ |
5953| [dragController.DragAction](js-apis-arkui-dragController.md#dragaction11)| 创建拖拽Action对象,主要用于后面实现注册监听拖拽状态改变事件和启动拖拽服务。 |
5954
5955**错误码:**
5956以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
5957
5958| 错误码ID | 错误信息      |
5959| -------- | ------------- |
5960| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
5961| 100001   | Internal handling failed. |
5962
5963**示例:**
59641.在EntryAbility.ets中获取UI上下文并保存至LocalStorage中。
5965```ts
5966import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
5967import { hilog } from '@kit.PerformanceAnalysisKit';
5968import { window, UIContext } from '@kit.ArkUI';
5969
5970let uiContext: UIContext;
5971let localStorage: LocalStorage = new LocalStorage('uiContext');
5972
5973export default class EntryAbility extends UIAbility {
5974  storage: LocalStorage = localStorage;
5975  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
5976    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
5977  }
5978
5979  onDestroy(): void {
5980    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
5981  }
5982
5983  onWindowStageCreate(windowStage: window.WindowStage): void {
5984    // Main window is created, set main page for this ability
5985    let storage: LocalStorage = new LocalStorage();
5986    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
5987
5988    windowStage.loadContent('pages/Index', storage, (err, data) => {
5989      if (err.code) {
5990        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
5991        return;
5992      }
5993      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
5994      windowStage.getMainWindow((err, data) =>
5995      {
5996        if (err.code) {
5997          console.error('Failed to abtain the main window. Cause:' + err.message);
5998          return;
5999        }
6000        let windowClass: window.Window = data;
6001        uiContext = windowClass.getUIContext();
6002        this.storage.setOrCreate<UIContext>('uiContext', uiContext);
6003        // 获取UIContext实例
6004      })
6005    });
6006  }
6007
6008  onWindowStageDestroy(): void {
6009    // Main window is destroyed, release UI related resources
6010    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
6011  }
6012
6013  onForeground(): void {
6014    // Ability has brought to foreground
6015    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
6016  }
6017
6018  onBackground(): void {
6019    // Ability has back to background
6020    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
6021  }
6022}
6023```
60242.通过LocalStorage.getShared()获取上下文,进而获取DragController对象实施后续操作。
6025```ts
6026import { dragController, componentSnapshot, UIContext, DragController } from "@kit.ArkUI"
6027import { image } from '@kit.ImageKit';
6028import { unifiedDataChannel } from '@kit.ArkData';
6029
6030let storages = LocalStorage.getShared();
6031
6032@Entry(storages)
6033@Component
6034struct DragControllerPage {
6035  @State pixmap: image.PixelMap|null = null
6036  private dragAction: dragController.DragAction|null = null;
6037  customBuilders:Array<CustomBuilder | DragItemInfo> = new Array<CustomBuilder | DragItemInfo>();
6038  @Builder DraggingBuilder() {
6039    Column() {
6040      Text("DraggingBuilder")
6041    }
6042    .width(100)
6043    .height(100)
6044    .backgroundColor(Color.Blue)
6045  }
6046
6047  build() {
6048    Column() {
6049
6050      Column() {
6051        Text("测试")
6052      }
6053      .width(100)
6054      .height(100)
6055      .backgroundColor(Color.Red)
6056
6057      Button('多对象dragAction customBuilder拖拽').onTouch((event?:TouchEvent) => {
6058        if(event){
6059          if (event.type == TouchType.Down) {
6060            console.info("muti drag Down by listener");
6061            this.customBuilders.push(()=>{this.DraggingBuilder()});
6062            this.customBuilders.push(()=>{this.DraggingBuilder()});
6063            this.customBuilders.push(()=>{this.DraggingBuilder()});
6064            let text = new unifiedDataChannel.Text()
6065            let unifiedData = new unifiedDataChannel.UnifiedData(text)
6066            let dragInfo: dragController.DragInfo = {
6067              pointerId: 0,
6068              data: unifiedData,
6069              extraParams: ''
6070            }
6071            try{
6072              let uiContext: UIContext = storages.get<UIContext>('uiContext') as UIContext;
6073              this.dragAction = uiContext.getDragController().createDragAction(this.customBuilders, dragInfo)
6074              if(!this.dragAction){
6075                console.info("listener dragAction is null");
6076                return
6077              }
6078              this.dragAction.on('statusChange', (dragAndDropInfo)=>{
6079                if (dragAndDropInfo.status == dragController.DragStatus.STARTED) {
6080                  console.info("drag has start");
6081                } else if (dragAndDropInfo.status == dragController.DragStatus.ENDED){
6082                  console.info("drag has end");
6083                  if (!this.dragAction) {
6084                    return
6085                  }
6086                  this.customBuilders.splice(0, this.customBuilders.length)
6087                  this.dragAction.off('statusChange')
6088                }
6089              })
6090              this.dragAction.startDrag().then(()=>{}).catch((err:Error)=>{
6091                console.error("start drag Error:" + err.message);
6092              })
6093            } catch(err) {
6094              console.error("create dragAction Error:" + err.message);
6095            }
6096          }
6097        }
6098      }).margin({top:20})
6099    }
6100  }
6101}
6102```
6103
6104### getDragPreview<sup>11+</sup>
6105
6106getDragPreview(): dragController.DragPreview
6107
6108返回一个代表拖拽背板的对象。
6109
6110**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6111
6112**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6113
6114**返回值:**
6115
6116| 类型                                                         | 说明                                                         |
6117| ------------------------------------------------------------ | ------------------------------------------------------------ |
6118| [dragController.DragPreview](js-apis-arkui-dragController.md#dragpreview11) | 一个代表拖拽背板的对象,提供背板样式设置的接口,在OnDrop和OnDragEnd回调中使用不生效。 |
6119
6120**错误码:** 通用错误码请参考[通用错误码说明文档](../errorcode-universal.md)。
6121
6122**示例:**
6123
6124请参考[animate](js-apis-arkui-dragController.md#animate11)
6125
6126### setDragEventStrictReportingEnabled<sup>12+</sup>
6127
6128setDragEventStrictReportingEnabled(enable: boolean): void
6129
6130当目标从父组件拖拽到子组件时,通过该方法设置是否会触发父组件的onDragLeave的回调。
6131
6132**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6133
6134**系统能力:** : SystemCapability.ArkUI.ArkUI.Full
6135
6136**参数:**
6137
6138| 参数名 | 类型    | 必填 | 说明                                                         |
6139| ------ | ------- | ---- | ------------------------------------------------------------ |
6140| enable | boolean | 是   | 将目标从父组件拖拽到子组件时,是否会触发父组件的onDragLeave的回调。 |
6141
6142**示例:**
6143
6144```ts
6145import { UIAbility } from '@kit.AbilityKit';
6146import { window, UIContext } from '@kit.ArkUI';
6147
6148 export default class EntryAbility extends UIAbility {
6149   onWindowStageCreate(windowStage: window.WindowStage): void {
6150       windowStage.loadContent('pages/Index', (err, data) => {
6151         if (err.code) {
6152         return;
6153       }
6154       windowStage.getMainWindow((err, data) => {
6155         if (err.code) {
6156           return;
6157         }
6158         let windowClass: window.Window = data;
6159         let uiContext: UIContext = windowClass.getUIContext();
6160         uiContext.getDragController().setDragEventStrictReportingEnabled(true);
6161     });
6162   });
6163 }
6164}
6165```
6166
6167## OverlayManager<sup>12+</sup>
6168
6169以下API需先使用UIContext中的[getOverlayManager()](#getoverlaymanager12)方法获取到OverlayManager对象,再通过该对象调用对应方法。
6170> **说明:**
6171>
6172> OverlayManager上节点的层级在Page页面层级之上,在Dialog、Popup、Menu、BindSheet、BindContentCover和Toast等之下。
6173>
6174> OverlayManager上节点安全区域内外的绘制方式与Page一致,键盘避让方式与Page一致。
6175>
6176> 与OverlayManager相关的属性推荐采用AppStorage来进行应用全局存储,以免切换页面后属性值发生变化从而导致业务错误。
6177
6178### addComponentContent<sup>12+</sup>
6179
6180addComponentContent(content: ComponentContent, index?: number): void
6181
6182在OverlayManager上新增指定节点。
6183
6184**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6185
6186**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6187
6188**参数:**
6189
6190| 参数名     | 类型                                       | 必填   | 说明          |
6191| ------- | ---------------------------------------- | ---- | ----------- |
6192| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是    | 在OverlayManager上新增指定节点上添加此content。 <br>**说明:** <br/> 新增的节点默认处于页面居中,按层级堆叠。|
6193| index | number | 否    | 新增节点在OverlayManager上的层级位置。<br>**说明:** <br/> 当index ≥ 0时,若index的值越大,则ComponentContent的层级越高;当多个ComponentContent的index相同时,若ComponentContent添加的时间越晚,则层级越高。<br/> 当index < 0、index = null或index = undefined时,ComponentContent默认添加至最高层。<br/>当同一个ComponentContent被添加多次时,只保留最后一次添加的ComponentContent。<br/>
6194
6195**示例:**
6196
6197```ts
6198import { ComponentContent, OverlayManager, router } from '@kit.ArkUI';
6199
6200class Params {
6201  text: string = ""
6202  offset: Position
6203  constructor(text: string, offset: Position) {
6204    this.text = text
6205    this.offset = offset
6206  }
6207}
6208@Builder
6209function builderText(params: Params) {
6210  Column() {
6211    Text(params.text)
6212      .fontSize(30)
6213      .fontWeight(FontWeight.Bold)
6214  }.offset(params.offset)
6215}
6216
6217@Entry
6218@Component
6219struct OverlayExample {
6220  @State message: string = 'ComponentContent';
6221  private uiContext: UIContext = this.getUIContext()
6222  private overlayNode: OverlayManager = this.uiContext.getOverlayManager()
6223  @StorageLink('contentArray') contentArray: ComponentContent<Params>[] = []
6224  @StorageLink('componentContentIndex') componentContentIndex: number = 0
6225  @StorageLink('arrayIndex') arrayIndex: number = 0
6226  @StorageLink("componentOffset") componentOffset: Position = {x: 0, y: 80}
6227
6228  build() {
6229    Column() {
6230      Button("++componentContentIndex: " + this.componentContentIndex).onClick(()=>{
6231        ++this.componentContentIndex
6232      })
6233      Button("--componentContentIndex: " + this.componentContentIndex).onClick(()=>{
6234        --this.componentContentIndex
6235      })
6236      Button("增加ComponentContent" + this.contentArray.length).onClick(()=>{
6237        let componentContent = new ComponentContent(
6238          this.uiContext, wrapBuilder<[Params]>(builderText),
6239          new Params(this.message + (this.contentArray.length), this.componentOffset)
6240        )
6241        this.contentArray.push(componentContent)
6242        this.overlayNode.addComponentContent(componentContent, this.componentContentIndex)
6243      })
6244      Button("++arrayIndex: " + this.arrayIndex).onClick(()=>{
6245        ++this.arrayIndex
6246      })
6247      Button("--arrayIndex: " + this.arrayIndex).onClick(()=>{
6248        --this.arrayIndex
6249      })
6250      Button("删除ComponentContent" + this.arrayIndex).onClick(()=>{
6251        if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) {
6252          let componentContent = this.contentArray.splice(this.arrayIndex, 1)
6253          this.overlayNode.removeComponentContent(componentContent.pop())
6254        } else {
6255          console.info("arrayIndex有误")
6256        }
6257      })
6258      Button("显示ComponentContent" + this.arrayIndex).onClick(()=>{
6259        if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) {
6260          let componentContent = this.contentArray[this.arrayIndex]
6261          this.overlayNode.showComponentContent(componentContent)
6262        } else {
6263          console.info("arrayIndex有误")
6264        }
6265      })
6266      Button("隐藏ComponentContent" + this.arrayIndex).onClick(()=>{
6267        if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) {
6268          let componentContent = this.contentArray[this.arrayIndex]
6269          this.overlayNode.hideComponentContent(componentContent)
6270        } else {
6271          console.info("arrayIndex有误")
6272        }
6273      })
6274      Button("显示所有ComponentContent").onClick(()=>{
6275          this.overlayNode.showAllComponentContents()
6276      })
6277      Button("隐藏所有ComponentContent").onClick(()=>{
6278        this.overlayNode.hideAllComponentContents()
6279      })
6280
6281      Button("跳转页面").onClick(()=>{
6282        router.pushUrl({
6283          url: 'pages/Second'
6284        })
6285      })
6286    }
6287    .width('100%')
6288    .height('100%')
6289  }
6290}
6291```
6292
6293### removeComponentContent<sup>12+</sup>
6294
6295removeComponentContent(content: ComponentContent): void
6296
6297在overlay上删除指定节点。
6298
6299**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6300
6301**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6302
6303**参数:**
6304
6305| 参数名     | 类型                                       | 必填   | 说明          |
6306| ------- | ---------------------------------------- | ---- | ----------- |
6307| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是    | 在OverlayManager上删除此content。 |
6308
6309**示例:**
6310
6311请参考[addComponentContent示例](#addcomponentcontent12)
6312
6313### showComponentContent<sup>12+</sup>
6314
6315showComponentContent(content: ComponentContent): void
6316
6317在OverlayManager上显示指定节点。
6318
6319**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6320
6321**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6322
6323**参数:**
6324
6325| 参数名     | 类型                                       | 必填   | 说明          |
6326| ------- | ---------------------------------------- | ---- | ----------- |
6327| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是    | 在OverlayManager上显示此content。|
6328
6329**示例:**
6330
6331请参考[addComponentContent示例](#addcomponentcontent12)
6332
6333### hideComponentContent<sup>12+</sup>
6334
6335hideComponentContent(content: ComponentContent): void
6336
6337在OverlayManager上隐藏指定节点。
6338
6339**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6340
6341**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6342
6343**参数:**
6344
6345| 参数名     | 类型                                       | 必填   | 说明          |
6346| ------- | ---------------------------------------- | ---- | ----------- |
6347| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是    | 在OverlayManager上隐藏此content。 |
6348
6349**示例:**
6350
6351请参考[addComponentContent示例](#addcomponentcontent12)
6352
6353### showAllComponentContents<sup>12+</sup>
6354
6355showAllComponentContents(): void
6356
6357显示OverlayManager上所有的ComponentContent。
6358
6359**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6360
6361**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6362
6363**示例:**
6364
6365请参考[addComponentContent示例](#addcomponentcontent12)
6366
6367### hideAllComponentContents<sup>12+</sup>
6368
6369hideAllComponentContents(): void
6370
6371隐藏OverlayManager上的所有ComponentContent。
6372
6373**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6374
6375**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6376
6377**示例:**
6378
6379请参考[addComponentContent示例](#addcomponentcontent12)
6380
6381## AtomicServiceBar<sup>11+</sup>
6382
6383以下接口需要先使用UIContext中的[getAtomicServiceBar](#getatomicservicebar11)方法获取到AtomicServiceBar对象,再通过该对象调用对应方法。
6384> **说明:**
6385>
6386> 从API version 12开始原子化服务menuBar样式变更,以下接口将失效。
6387
6388### setVisible<sup>11+</sup>
6389
6390setVisible(visible: boolean): void
6391
6392通过该方法设置原子化服务menuBar是否可见。
6393> **说明:**
6394>
6395> 从API version 12开始原子化服务menuBar样式变更,menuBar默认隐藏,变为悬浮按钮,通过该接口无法改变menuBar的可见性。
6396
6397**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
6398
6399**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6400
6401**参数:**
6402
6403| 参数名 | 类型 | 必填 | 说明 |
6404| ------- | ------- | ------- | ------- |
6405| visible | boolean | 是 | 原子化服务menuBar是否可见。|
6406
6407
6408**示例:**
6409
6410```ts
6411import {UIContext, AtomicServiceBar, window } from '@kit.ArkUI';
6412import { hilog } from '@kit.PerformanceAnalysisKit';
6413
6414onWindowStageCreate(windowStage: window.WindowStage) {
6415  // Main window is created, set main page for this ability
6416  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
6417  windowStage.loadContent('pages/Index', (err, data) => {
6418    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
6419    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
6420    if (atomicServiceBar != undefined) {
6421      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
6422      atomicServiceBar.setVisible(false);
6423    } else {
6424      hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
6425    }
6426  });
6427}
6428```
6429
6430### setBackgroundColor<sup>11+</sup>
6431
6432setBackgroundColor(color:Nullable<Color | number | string>): void
6433
6434通过该方法设置原子化服务menuBar的背景颜色。
6435> **说明:**
6436>
6437> 从API version 12开始原子化服务menuBar样式变更,menuBar的背景默认隐藏,通过该接口无法改变menuBar的背景颜色。
6438
6439**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6440
6441**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
6442
6443**参数:**
6444
6445| 参数名 | 类型 | 必填 | 说明 |
6446| ------ | ------ | ------ | ------ |
6447| color | Nullable\<[Color](arkui-ts/ts-appendix-enums.md#color) \| number \| string> | 是 | 通过该方法设置原子化服务menuBar的背景颜色,undefined代表使用默认颜色。|
6448
6449**示例:**
6450
6451```ts
6452import {UIContext, AtomicServiceBar,window } from '@kit.ArkUI';
6453import { hilog } from '@kit.PerformanceAnalysisKit';
6454onWindowStageCreate(windowStage: window.WindowStage) {
6455  // Main window is created, set main page for this ability
6456  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
6457  windowStage.loadContent('pages/Index', (err, data) => {
6458    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
6459    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
6460    if (atomicServiceBar != undefined) {
6461      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
6462      atomicServiceBar.setBackgroundColor(0x88888888);
6463    } else {
6464      hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
6465    }
6466  });
6467}
6468```
6469
6470### setTitleContent<sup>11+</sup>
6471
6472setTitleContent(content:string): void
6473
6474通过该方法设置原子化服务menuBar的标题内容。
6475> **说明:**
6476>
6477> 从API version 12开始原子化服务menuBar样式变更,menuBar的标题默认隐藏,通过该接口无法改变menuBar的标题内容。
6478
6479**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6480
6481**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
6482
6483**参数:**
6484
6485|参数名|类型|必填|说明 |
6486| ------- | ------- | ------- | ------- |
6487| content | string | 是 | 原子化服务menuBar中的标题内容。|
6488
6489**示例:**
6490
6491```ts
6492import {UIContext, AtomicServiceBar,window } from '@kit.ArkUI';
6493import { hilog } from '@kit.PerformanceAnalysisKit';
6494
6495onWindowStageCreate(windowStage: window.WindowStage) {
6496  // Main window is created, set main page for this ability
6497  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
6498  windowStage.loadContent('pages/Index', (err, data) => {
6499    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
6500    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
6501    if (atomicServiceBar != undefined) {
6502      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
6503      atomicServiceBar.setTitleContent('text2');
6504    } else {
6505      hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
6506    }
6507  });
6508}
6509```
6510
6511### setTitleFontStyle<sup>11+</sup>
6512
6513setTitleFontStyle(font:FontStyle):void
6514
6515通过该方法设置原子化服务menuBar的字体样式。
6516> **说明:**
6517>
6518> 从API version 12开始原子化服务menuBar样式变更,menuBar的标题默认隐藏,通过该接口无法改变menuBar的字体样式。
6519
6520**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6521
6522**系统能力:** SystemCapability.ArkUI.ArkUI.Full6523
6524**参数:**
6525
6526| 参数名 | 类型 | 必填 | 说明 |
6527| ------ | ------ | ------ | ------ |
6528| font | [FontStyle](arkui-ts/ts-appendix-enums.md#fontstyle) | 是 | 原子化服务menuBar中的字体样式。 |
6529
6530**示例:**
6531
6532```ts
6533import {UIContext, Font, AtomicServiceBar } from '@kit.ArkUI';
6534import { hilog } from '@kit.PerformanceAnalysisKit';
6535
6536onWindowStageCreate(windowStage: window.WindowStage) {
6537  // Main window is created, set main page for this ability
6538  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
6539  windowStage.loadContent('pages/Index', (err, data) => {
6540    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
6541    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
6542    if (atomicServiceBar != undefined) {
6543      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
6544      atomicServiceBar.setTitleFontStyle(FontStyle.Normal);
6545    } else {
6546      hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
6547    }
6548  });
6549}
6550```
6551
6552### setIconColor<sup>11+</sup>
6553
6554setIconColor(color:Nullable<Color | number | string>): void
6555
6556通过该方法设置原子化服务图标的颜色。
6557> **说明:**
6558>
6559> 从API version 12开始原子化服务menuBar样式变更,menuBar默认隐藏,悬浮按钮图标不予用户设置,通过该接口无法改变menuBar的图标颜色。
6560
6561**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6562
6563**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6564
6565**参数:**
6566
6567| 参数名 | 类型 | 必填 | 说明 |
6568| ------- | ------- | ------- | ------- |
6569| color | Nullable\<[Color](arkui-ts/ts-appendix-enums.md#color) \| number \| string> | 是 | 原子化服务图标的颜色,undefined代表使用默认颜色。 |
6570
6571
6572**示例:**
6573
6574```ts
6575import {UIContext, Font, window } from '@kit.ArkUI';
6576import { hilog } from '@kit.PerformanceAnalysisKit';
6577
6578onWindowStageCreate(windowStage: window.WindowStage) {
6579  // Main window is created, set main page for this ability
6580  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
6581  windowStage.loadContent('pages/Index', (err, data) => {
6582    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
6583    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
6584    if (atomicServiceBar != undefined) {
6585      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
6586      atomicServiceBar.setIconColor(0x12345678);
6587    } else {
6588      hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
6589    }
6590  });
6591}
6592```
6593## KeyboardAvoidMode<sup>11+</sup>
6594
6595配置键盘避让时页面的避让模式。
6596
6597**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
6598
6599**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6600
6601| 名称   | 值   | 说明       |
6602| ------ | ---- | ---------- |
6603| OFFSET | 0    | 上抬模式。 |
6604| RESIZE | 1    | 压缩模式。 |
6605
6606
6607## FocusController<sup>12+</sup>
6608以下API需先使用UIContext中的[getFocusController()](js-apis-arkui-UIContext.md#getFocusController12)方法获取UIContext实例,再通过此实例调用对应方法。
6609
6610### clearFocus<sup>12+</sup>
6611
6612clearFocus(): void
6613
6614清除焦点,将焦点强制转移到页面根容器节点,焦点链路上其他节点失焦。
6615
6616**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6617
6618**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6619
6620**示例:**
6621
6622```ts
6623@Entry
6624@Component
6625struct ClearFocusExample {
6626  @State inputValue: string = ''
6627  @State btColor: Color = Color.Blue
6628
6629  build() {
6630    Column({ space: 20 }) {
6631      Column({ space: 5 }) {
6632        Button('button1')
6633          .width(200)
6634          .height(70)
6635          .fontColor(Color.White)
6636          .focusOnTouch(true)
6637          .backgroundColor(Color.Blue)
6638        Button('button2')
6639          .width(200)
6640          .height(70)
6641          .fontColor(Color.White)
6642          .focusOnTouch(true)
6643          .backgroundColor(this.btColor)
6644          .defaultFocus(true)
6645          .onFocus(() => {
6646            this.btColor = Color.Red
6647          })
6648          .onBlur(() => {
6649            this.btColor = Color.Blue
6650          })
6651        Button('clearFocus')
6652          .width(200)
6653          .height(70)
6654          .fontColor(Color.White)
6655          .backgroundColor(Color.Blue)
6656          .onClick(() => {
6657            this.getUIContext().getFocusController().clearFocus()
6658          })
6659      }
6660    }
6661    .width('100%')
6662    .height('100%')
6663  }
6664}
6665```
6666
6667### requestFocus<sup>12+</sup>
6668
6669requestFocus(key: string): void
6670
6671通过组件的id将焦点转移到组件树对应的实体节点。当前帧生效。
6672
6673**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6674
6675**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6676
6677**参数:**
6678
6679| 参数名 | 类型 | 必填 | 说明 |
6680| ------- | ------- | ------- | ------- |
6681| key | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。|
6682
6683**错误码:**
6684
6685以下错误码的详细介绍请参见[焦点错误码](errorcode-focus.md)。
6686
6687| 错误码ID | 错误信息                                        |
6688| -------- | ----------------------------------------------- |
6689| 150001   | the component cannot be focused.                |
6690| 150002   | This component has an unfocusable ancestor.     |
6691| 150003   | the component is not on tree or does not exist. |
6692
6693**示例:**
6694
6695```ts
6696@Entry
6697@Component
6698struct RequestExample {
6699  @State btColor: Color = Color.Blue
6700
6701  build() {
6702    Column({ space: 20 }) {
6703      Column({ space: 5 }) {
6704        Button('Button')
6705          .width(200)
6706          .height(70)
6707          .fontColor(Color.White)
6708          .focusOnTouch(true)
6709          .backgroundColor(this.btColor)
6710          .onFocus(() => {
6711            this.btColor = Color.Red
6712          })
6713          .onBlur(() => {
6714            this.btColor = Color.Blue
6715          })
6716          .id("testButton")
6717
6718        Divider()
6719          .vertical(false)
6720          .width("80%")
6721          .backgroundColor(Color.Black)
6722          .height(10)
6723
6724        Button('requestFocus')
6725          .width(200)
6726          .height(70)
6727          .onClick(() => {
6728            this.getUIContext().getFocusController().requestFocus("testButton")
6729          })
6730
6731        Button('requestFocus fail')
6732          .width(200)
6733          .height(70)
6734          .onClick(() => {
6735            try {
6736              this.getUIContext().getFocusController().requestFocus("eee")
6737            } catch (error) {
6738              console.error('requestFocus failed code is ' + error.code + ' message is ' + error.message)
6739            }
6740          })
6741      }
6742    }
6743    .width('100%')
6744    .height('100%')
6745  }
6746}
6747```
6748
6749## CursorController<sup>12+</sup>
6750以下API需先使用UIContext中的[getCursorController()](js-apis-arkui-UIContext.md#getcursorcontroller12)方法获取CursorController实例,再通过此实例调用对应方法。
6751
6752### restoreDefault<sup>12+</sup>
6753
6754restoreDefault(): void
6755
6756恢复默认的光标样式
6757
6758**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6759
6760**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6761
6762**示例:**
6763当光标移出绿框时,通过CursorController的restoreDefault方法恢复默认光标样式
6764
6765```ts
6766import { pointer } from '@kit.InputKit';
6767import { UIContext, CursorController } from '@kit.ArkUI';
6768
6769@Entry
6770@Component
6771struct CursorControlExample {
6772  @State text: string = ''
6773  cursorCustom: CursorController = this.getUIContext().getCursorController();
6774
6775  build() {
6776    Column() {
6777      Row().height(200).width(200).backgroundColor(Color.Green).position({x: 150 ,y:70})
6778        .onHover((flag) => {
6779          if (flag) {
6780            this.cursorCustom.setCursor(pointer.PointerStyle.EAST)
6781          } else {
6782            console.info("restoreDefault");
6783            this.cursorCustom.restoreDefault();
6784          }
6785        })
6786    }.width('100%')
6787  }
6788}
6789```
6790![cursor-restoreDefault](figures/cursor-restoreDefault.gif)
6791
6792### setCursor<sup>12+</sup>
6793
6794setCursor(value: PointerStyle): void
6795
6796更改当前的鼠标光标样式
6797
6798**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6799
6800**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6801
6802**参数:**
6803
6804| 参数名     | 类型                                       | 必填   | 说明      |
6805| ------- | ---------------------------------------- | ---- | ------- |
6806| value | [PointerStyle](../apis-input-kit/js-apis-pointer.md#pointerstyle) | 是    | 光标样式 |
6807
6808**示例:**
6809当光标进入蓝框时,通过CursorController的setCursor方法修改光标样式为PointerStyle.WEST
6810
6811```ts
6812import { pointer } from '@kit.InputKit';
6813import { UIContext, CursorController } from '@kit.ArkUI';
6814
6815@Entry
6816@Component
6817struct CursorControlExample {
6818  @State text: string = ''
6819  cursorCustom: CursorController = this.getUIContext().getCursorController();
6820
6821  build() {
6822    Column() {
6823      Row().height(200).width(200).backgroundColor(Color.Blue).position({x: 100 ,y:70})
6824        .onHover((flag) => {
6825          if (flag) {
6826            this.cursorCustom.setCursor(pointer.PointerStyle.WEST)
6827          } else {
6828            this.cursorCustom.restoreDefault();
6829          }
6830        })
6831    }.width('100%')
6832  }
6833}
6834```
6835![cursor-setCursor](figures/cursor-setCursor.gif)
6836
6837## ContextMenuController<sup>12+</sup>
6838以下API需先使用UIContext中的[getContextMenuController()](js-apis-arkui-UIContext.md#getcontextmenucontroller12)方法获取ContextMenuController实例,再通过此实例调用对应方法。
6839
6840### close<sup>12+</sup>
6841
6842close(): void
6843
6844关闭菜单
6845
6846**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6847
6848**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6849
6850**示例:**
6851通过定时器触发,调用ContextMenuController的close方法关闭菜单
6852
6853```ts
6854import { ContextMenuController } from '@kit.ArkUI';
6855
6856@Entry
6857@Component
6858struct Index {
6859  menu: ContextMenuController = this.getUIContext().getContextMenuController();
6860
6861  @Builder MenuBuilder() {
6862    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
6863      Button('Test ContextMenu1 Close')
6864      Divider().strokeWidth(2).margin(5).color(Color.Black)
6865      Button('Test ContextMenu2')
6866      Divider().strokeWidth(2).margin(5).color(Color.Black)
6867      Button('Test ContextMenu3')
6868    }
6869    .width(200)
6870    .height(160)
6871  }
6872
6873  build() {
6874    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
6875      Button("启动定时器").onClick(()=>
6876      {
6877        setTimeout(() => {
6878          this.menu.close();
6879        }, 10000);
6880      })
6881
6882      Column() {
6883        Text("Test ContextMenu close")
6884          .fontSize(20)
6885          .width('100%')
6886          .height(500)
6887          .backgroundColor(0xAFEEEE)
6888          .textAlign(TextAlign.Center)
6889      }
6890      .bindContextMenu(this.MenuBuilder, ResponseType.LongPress)
6891    }
6892    .width('100%')
6893    .height('100%')
6894  }
6895}
6896```
6897
6898![contextMenuController_close](figures/contextMenuController_close.gif)
6899
6900## MeasureUtils<sup>12+</sup>
6901
6902以下API需先使用UIContext中的[getMeasureUtils()](js-apis-arkui-UIContext.md#getmeasureutils12)方法获取MeasureUtils实例,再通过此实例调用对应方法。
6903
6904### measureText<sup>12+</sup>
6905
6906measureText(options: MeasureOptions): number
6907
6908计算指定文本单行布局下的宽度。
6909
6910**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6911
6912**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6913
6914**参数:**
6915
6916| 参数名     | 类型                              | 必填   | 说明        |
6917| ------- | ------------------------------- | ---- | --------- |
6918| options | [MeasureOptions](js-apis-measure.md#measureoptions) | 是    | 被计算文本描述信息。 |
6919
6920**返回值:**
6921
6922| 类型          | 说明       |
6923| ------------  | --------- |
6924| number        | 文本宽度。<br/>**说明:**<br/>单位px。 |
6925
6926
6927**示例:**
6928通过MeasureUtils的measureText方法获取"Hello World"文字的宽度。
6929
6930```ts
6931import { MeasureUtils } from '@kit.ArkUI';
6932
6933@Entry
6934@Component
6935struct Index {
6936  @State uiContext: UIContext = this.getUIContext();
6937  @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils();
6938  @State textWidth: number = this.uiContextMeasure.measureText({
6939    textContent: "Hello word",
6940    fontSize: '50px'
6941  })
6942
6943  build() {
6944    Row() {
6945      Column() {
6946        Text(`The width of 'Hello World': ${this.textWidth}`)
6947      }
6948      .width('100%')
6949    }
6950    .height('100%')
6951  }
6952}
6953```
6954
6955### measureTextSize<sup>12+</sup>
6956
6957measureTextSize(options: MeasureOptions): SizeOptions
6958
6959计算指定文本单行布局下的宽度和高度。
6960
6961**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
6962
6963**系统能力:** SystemCapability.ArkUI.ArkUI.Full
6964
6965**参数:**
6966
6967| 参数名     | 类型                              | 必填   | 说明        |
6968| ------- | ------------------------------- | ---- | --------- |
6969| options | [MeasureOptions](js-apis-measure.md#measureoptions) | 是    | 被计算文本描述信息。 |
6970
6971**返回值:**
6972
6973| 类型          | 说明       |
6974| ------------  | --------- |
6975| [SizeOption](arkui-ts/ts-types.md#sizeoptions)   | 返回文本所占布局宽度和高度。<br/>**说明:**<br/> 文本宽度以及高度返回值单位均为px。 |
6976
6977
6978**示例:**
6979通过MeasureUtils的measureTextSize方法获取"Hello World"文字的宽度和高度
6980
6981```ts
6982import { MeasureUtils } from '@kit.ArkUI';
6983
6984@Entry
6985@Component
6986struct Index {
6987  @State uiContext: UIContext = this.getUIContext();
6988  @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils();
6989  textSize : SizeOptions = this.uiContextMeasure.measureTextSize({
6990    textContent: "Hello word",
6991    fontSize: '50px'
6992  })
6993  build() {
6994    Row() {
6995      Column() {
6996        Text(`The width of 'Hello World': ${this.textSize.width}`)
6997        Text(`The height of 'Hello World': ${this.textSize.height}`)
6998      }
6999      .width('100%')
7000    }
7001    .height('100%')
7002  }
7003}
7004```
7005
7006## ComponentSnapshot<sup>12+</sup>
7007
7008以下API需先使用UIContext中的[getComponentSnapshot()](js-apis-arkui-UIContext.md#getcomponentsnapshot12)方法获取ComponentSnapshot对象,再通过此实例调用对应方法。
7009
7010### get<sup>12+</sup>
7011
7012get(id: string, callback: AsyncCallback<image.PixelMap>, options?: componentSnapshot.SnapshotOptions): void
7013
7014获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过回调返回结果。
7015
7016> **说明:**
7017>
7018> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
7019
7020**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
7021
7022**系统能力:** SystemCapability.ArkUI.ArkUI.Full
7023
7024**参数:**
7025
7026| 参数名   | 类型                                                         | 必填 | 说明                                                         |
7027| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
7028| id       | string                                                       | 是   | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识) |
7029| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | 是   | 截图返回结果的回调。                                         |
7030| options<sup>12+</sup>       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | 否    | 截图相关的自定义参数。 |
7031
7032**错误码:**
7033
7034以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
7035
7036| 错误码ID | 错误信息                                                     |
7037| -------- | ------------------------------------------------------------ |
7038| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
7039| 100001   | Invalid ID.                                                  |
7040
7041**示例:**
7042
7043```ts
7044import { image } from '@kit.ImageKit';
7045import { UIContext } from '@kit.ArkUI';
7046
7047@Entry
7048@Component
7049struct SnapshotExample {
7050  @State pixmap: image.PixelMap | undefined = undefined
7051  uiContext: UIContext = this.getUIContext();
7052  build() {
7053    Column() {
7054      Row() {
7055        Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5)
7056        Image($r('app.media.img')).autoResize(true).width(150).height(150).margin(5).id("root")
7057      }
7058      Button("click to generate UI snapshot")
7059        .onClick(() => {
7060          this.uiContext.getComponentSnapshot().get("root", (error: Error, pixmap: image.PixelMap) => {
7061            if (error) {
7062              console.error("error: " + JSON.stringify(error))
7063              return;
7064            }
7065            this.pixmap = pixmap
7066          }, {scale : 2, waitUntilRenderFinished : true})
7067        }).margin(10)
7068    }
7069    .width('100%')
7070    .height('100%')
7071    .alignItems(HorizontalAlign.Center)
7072  }
7073}
7074```
7075
7076### get<sup>12+</sup>
7077
7078get(id: string, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
7079
7080获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过Promise返回结果。
7081
7082> **说明:**
7083>
7084> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
7085
7086**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
7087
7088**系统能力:** SystemCapability.ArkUI.ArkUI.Full
7089
7090**参数:**
7091
7092| 参数名 | 类型   | 必填 | 说明                                                         |
7093| ------ | ------ | ---- | ------------------------------------------------------------ |
7094| id     | string | 是   | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识) |
7095| options<sup>12+</sup>       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | 否    | 截图相关的自定义参数。 |
7096
7097**返回值:**
7098
7099| 类型                                                         | 说明             |
7100| ------------------------------------------------------------ | ---------------- |
7101| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | 截图返回的结果。 |
7102
7103**错误码:**
7104
7105以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
7106
7107| 错误码ID | 错误信息                                                     |
7108| -------- | ------------------------------------------------------------ |
7109| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
7110| 100001   | Invalid ID.                                                  |
7111
7112**示例:**
7113
7114```ts
7115import { image } from '@kit.ImageKit';
7116import { UIContext } from '@kit.ArkUI';
7117
7118@Entry
7119@Component
7120struct SnapshotExample {
7121  @State pixmap: image.PixelMap | undefined = undefined
7122  uiContext: UIContext = this.getUIContext();
7123
7124  build() {
7125    Column() {
7126      Row() {
7127        Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5)
7128        Image($r('app.media.icon')).autoResize(true).width(150).height(150).margin(5).id("root")
7129      }
7130      Button("click to generate UI snapshot")
7131        .onClick(() => {
7132          this.uiContext.getComponentSnapshot()
7133            .get("root", {scale : 2, waitUntilRenderFinished : true})
7134            .then((pixmap: image.PixelMap) => {
7135              this.pixmap = pixmap
7136            })
7137            .catch((err: Error) => {
7138              console.error("error: " + err)
7139            })
7140        }).margin(10)
7141    }
7142    .width('100%')
7143    .height('100%')
7144    .alignItems(HorizontalAlign.Center)
7145  }
7146}
7147```
7148
7149### createFromBuilder<sup>12+</sup>
7150
7151createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): void
7152
7153在应用后台渲染[CustomBuilder](arkui-ts/ts-types.md#custombuilder8)自定义组件,并输出其截图。通过回调返回结果。
7154> **说明:**
7155>
7156> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。
7157>
7158> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/ts-basic-components-web.md)组件。
7159
7160**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
7161
7162**系统能力:** SystemCapability.ArkUI.ArkUI.Full
7163
7164**参数:**
7165
7166| 参数名   | 类型                                                         | 必填 | 说明                                                         |
7167| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
7168| builder  | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8)         | 是   | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。      |
7169| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | 是   | 截图返回结果的回调。支持在回调中获取离屏组件绘制区域坐标和大小。 |
7170| delay<sup>12+</sup>   | number | 否    | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 默认值:300 <br/> 单位:毫秒|
7171| checkImageStatus<sup>12+</sup>  | boolean | 否    | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false|
7172| options<sup>12+</sup>       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否    | 截图相关的自定义参数。 |
7173
7174**错误码:**
7175
7176以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
7177
7178| 错误码ID | 错误信息                                                     |
7179| -------- | ------------------------------------------------------------ |
7180| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
7181| 100001   | The builder is not a valid build function.                   |
7182| 160001   | An image component in builder is not ready for taking a snapshot. The check for the ready state is required when the checkImageStatus option is enabled. |
7183
7184**示例:**
7185
7186```ts
7187import { image } from '@kit.ImageKit';
7188import { UIContext } from '@kit.ArkUI';
7189
7190@Entry
7191@Component
7192struct ComponentSnapshotExample {
7193  @State pixmap: image.PixelMap | undefined = undefined
7194  uiContext: UIContext = this.getUIContext();
7195  @Builder
7196  RandomBuilder() {
7197    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
7198      Text('Test menu item 1')
7199        .fontSize(20)
7200        .width(100)
7201        .height(50)
7202        .textAlign(TextAlign.Center)
7203      Divider().height(10)
7204      Text('Test menu item 2')
7205        .fontSize(20)
7206        .width(100)
7207        .height(50)
7208        .textAlign(TextAlign.Center)
7209    }
7210    .width(100)
7211    .id("builder")
7212  }
7213
7214  build() {
7215    Column() {
7216      Button("click to generate UI snapshot")
7217        .onClick(() => {
7218          this.uiContext.getComponentSnapshot().createFromBuilder(() => {
7219            this.RandomBuilder()
7220          },
7221            (error: Error, pixmap: image.PixelMap) => {
7222              if (error) {
7223                console.error("error: " + JSON.stringify(error))
7224                return;
7225              }
7226              this.pixmap = pixmap
7227            }, 320, true, {scale : 2, waitUntilRenderFinished : true})
7228        })
7229      Image(this.pixmap)
7230        .margin(10)
7231        .height(200)
7232        .width(200)
7233        .border({ color: Color.Black, width: 2 })
7234    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
7235  }
7236}
7237```
7238
7239### createFromBuilder<sup>12+</sup>
7240
7241createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
7242
7243在应用后台渲染[CustomBuilder](arkui-ts/ts-types.md#custombuilder8)自定义组件,并输出其截图。通过Promise返回结果。
7244
7245> **说明:**
7246>
7247> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。
7248>
7249> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/ts-basic-components-web.md)组件。
7250
7251**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
7252
7253**系统能力:** SystemCapability.ArkUI.ArkUI.Full
7254
7255**参数:**
7256
7257| 参数名  | 类型                                                 | 必填 | 说明                                                    |
7258| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- |
7259| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | 是   | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。 |
7260
7261**返回值:**
7262
7263| 类型                                                         | 说明             |
7264| ------------------------------------------------------------ | ---------------- |
7265| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | 截图返回的结果。 |
7266| delay<sup>12+</sup>   | number | 否    | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 默认值:300 <br/> 单位:毫秒|
7267| checkImageStatus<sup>12+</sup>  | boolean | 否    | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false|
7268| options<sup>12+</sup>       | [SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)           | 否    | 截图相关的自定义参数。 |
7269
7270**错误码:**
7271
7272以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
7273
7274| 错误码ID | 错误信息                                                     |
7275| -------- | ------------------------------------------------------------ |
7276| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
7277| 100001   | The builder is not a valid build function.                   |
7278| 160001   | An image component in builder is not ready for taking a snapshot. The check for the ready state is required when the checkImageStatus option is enabled. |
7279
7280**示例:**
7281
7282```ts
7283import { image } from '@kit.ImageKit';
7284import { UIContext } from '@kit.ArkUI';
7285
7286@Entry
7287@Component
7288struct ComponentSnapshotExample {
7289  @State pixmap: image.PixelMap | undefined = undefined
7290  uiContext: UIContext = this.getUIContext();
7291  @Builder
7292  RandomBuilder() {
7293    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
7294      Text('Test menu item 1')
7295        .fontSize(20)
7296        .width(100)
7297        .height(50)
7298        .textAlign(TextAlign.Center)
7299      Divider().height(10)
7300      Text('Test menu item 2')
7301        .fontSize(20)
7302        .width(100)
7303        .height(50)
7304        .textAlign(TextAlign.Center)
7305    }
7306    .width(100)
7307    .id("builder")
7308  }
7309  build() {
7310    Column() {
7311      Button("click to generate UI snapshot")
7312        .onClick(() => {
7313          this.uiContext.getComponentSnapshot()
7314            .createFromBuilder(() => {
7315              this.RandomBuilder()
7316            }, 320, true, {scale : 2, waitUntilRenderFinished : true})
7317            .then((pixmap: image.PixelMap) => {
7318              this.pixmap = pixmap
7319            })
7320            .catch((err: Error) => {
7321              console.error("error: " + err)
7322            })
7323        })
7324      Image(this.pixmap)
7325        .margin(10)
7326        .height(200)
7327        .width(200)
7328        .border({ color: Color.Black, width: 2 })
7329    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
7330  }
7331}
7332```
7333
7334### getSync<sup>12+</sup>
7335
7336getSync(id: string, options?: componentSnapshot.SnapshotOptions): image.PixelMap
7337
7338获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。同步等待截图完成返回[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)。
7339
7340> **说明:**
7341>
7342> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。
7343
7344**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
7345
7346**系统能力:** SystemCapability.ArkUI.ArkUI.Full
7347
7348**参数:**
7349
7350| 参数名  | 类型     | 必填   | 说明                                       |
7351| ---- | ------ | ---- | ---------------------------------------- |
7352| id   | string | 是    | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识) |
7353| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | 否    | 截图相关的自定义参数。 |
7354
7355**返回值:**
7356
7357| 类型                                                         | 说明             |
7358| ------------------------------------------------------------ | ---------------- |
7359| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | 截图返回的结果。 |
7360
7361**错误码:**
7362
7363以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
7364
7365| 错误码ID | 错误信息                                                     |
7366| -------- | ------------------------------------------------------------ |
7367| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
7368| 100001   | Invalid ID.                                                  |
7369| 160002   | Timeout.                                                     |
7370
7371**示例:**
7372
7373```ts
7374import { image } from '@kit.ImageKit';
7375import { UIContext } from '@kit.ArkUI';
7376
7377@Entry
7378@Component
7379struct SnapshotExample {
7380  @State pixmap: image.PixelMap | undefined = undefined
7381
7382  build() {
7383    Column() {
7384      Row() {
7385        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
7386        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")
7387      }
7388      Button("click to generate UI snapshot")
7389        .onClick(() => {
7390          try {
7391            let pixelmap = this.getUIContext().getComponentSnapshot().getSync("root", {scale : 2, waitUntilRenderFinished : true})
7392            this.pixmap = pixelmap
7393          } catch (error) {
7394            console.error("getSync errorCode: " + error.code + " message: " + error.message)
7395          }
7396        }).margin(10)
7397    }
7398    .width('100%')
7399    .height('100%')
7400    .alignItems(HorizontalAlign.Center)
7401  }
7402}
7403```
7404
7405## FrameCallback<sup>12+</sup>
7406
7407用于设置下一帧渲染时需要执行的任务。需要配合[UIContext](#uicontext)中的[postFrameCallback](#postframecallback12)和[postDelayedFrameCallback](#postdelayedframecallback12)使用。开发者需要继承该类并重写[onFrame](#onframe12)或[onIdle](#onidle12)方法,实现具体的业务逻辑。
7408
7409### onFrame<sup>12+</sup>
7410
7411onFrame(frameTimeInNano: number): void
7412
7413在下一帧进行渲染时,该方法将被执行。
7414
7415**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
7416
7417**系统能力:** SystemCapability.ArkUI.ArkUI.Full
7418
7419**参数:**
7420
7421| 参数名  | 类型                                                 | 必填 | 说明                                                    |
7422| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- |
7423| frameTimeInNano | number | 是   | 下一帧渲染开始执行的时间,以纳秒为单位。 |
7424
7425**示例:**
7426
7427```ts
7428import {FrameCallback } from '@kit.ArkUI';
7429
7430class MyFrameCallback extends FrameCallback {
7431  private tag: string;
7432
7433  constructor(tag: string) {
7434    super()
7435    this.tag = tag;
7436  }
7437
7438  onFrame(frameTimeNanos: number) {
7439    console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString());
7440  }
7441}
7442
7443@Entry
7444@Component
7445struct Index {
7446  build() {
7447    Row() {
7448      Column() {
7449        Button('点击触发postFrameCallback')
7450          .onClick(() => {
7451            this.getUIContext().postFrameCallback(new MyFrameCallback("normTask"));
7452          })
7453        Button('点击触发postDelayedFrameCallback')
7454          .onClick(() => {
7455            this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5);
7456          })
7457      }
7458      .width('100%')
7459    }
7460    .height('100%')
7461  }
7462}
7463```
7464
7465### onIdle<sup>12+</sup>
7466
7467onIdle(timeLeftInNano: number): void
7468
7469在下一帧渲染结束时,如果距离下一个Vsync信号到来还有1ms以上的剩余时间,该方法将被执行,否则将顺延至后面的帧。
7470
7471**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
7472
7473**系统能力:** SystemCapability.ArkUI.ArkUI.Full
7474
7475**参数:**
7476
7477| 参数名  | 类型                                                 | 必填 | 说明                                                    |
7478| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- |
7479| timeLeftInNano | number | 是   | 这一帧剩余的空闲时间。 |
7480
7481**示例:**
7482
7483```ts
7484import { FrameCallback } from '@ohos.arkui.UIContext';
7485
7486class MyIdleCallback extends FrameCallback {
7487  private tag: string;
7488
7489  constructor(tag: string) {
7490    super()
7491    this.tag = tag;
7492  }
7493
7494  onIdle(timeLeftInNano: number) {
7495    console.info('MyIdleCallback ' + this.tag + ' ' + timeLeftInNano.toString());
7496  }
7497}
7498
7499@Entry
7500@Component
7501struct Index {
7502  build() {
7503    Row() {
7504      Column() {
7505        Button('点击触发postFrameCallback')
7506          .onClick(() => {
7507            this.getUIContext().postFrameCallback(new MyIdleCallback("normTask"));
7508          })
7509        Button('点击触发postDelayedFrameCallback')
7510          .onClick(() => {
7511            this.getUIContext().postDelayedFrameCallback(new MyIdleCallback("delayTask"), 5);
7512          })
7513      }
7514      .width('100%')
7515    }
7516    .height('100%')
7517  }
7518}
7519```
7520
7521## DynamicSyncScene<sup>12+</sup>
7522
7523以下接口需先使用UIContext中的requireDynamicSyncScene()方法获取DynamicSyncScene对象,再通过此实例调用对应方法。
7524
7525### setFrameRateRange<sup>12+</sup>
7526
7527setFrameRateRange(range: ExpectedFrameRateRange): void
7528
7529设置期望帧率范围。
7530
7531最终结果不一定是设置的帧率,会由系统能力做综合决策,尽量满足开发者的设置帧率。
7532
7533**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
7534
7535**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
7536
7537**参数:**
7538
7539| 参数名      | 类型         | 必填   | 说明   |
7540| -------- | ---------- | ---- | ---- |
7541| range | [ExpectedFrameRateRange](../apis-arkui/arkui-ts/ts-explicit-animation.md#expectedframeraterange11)| 是    | 设置期望的帧率范围。<br />默认值:{min:0, max:120, expected: 120} |
7542
7543**示例:**
7544
7545```ts
7546import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI'
7547
7548@Entry
7549@Component
7550struct Frame {
7551  @State ANIMATION:ExpectedFrameRateRange = {min:0, max:120, expected: 90}
7552  @State GESTURE:ExpectedFrameRateRange = {min:0, max:120, expected: 30}
7553  private scenes: SwiperDynamicSyncScene[] = []
7554
7555  build() {
7556    Column() {
7557      Text("动画"+ JSON.stringify(this.ANIMATION))
7558      Text("跟手"+ JSON.stringify(this.GESTURE))
7559      Row(){
7560        Swiper() {
7561          Text("one")
7562          Text("two")
7563          Text("three")
7564        }
7565        .width('100%')
7566        .height('300vp')
7567        .id("dynamicSwiper")
7568        .backgroundColor(Color.Blue)
7569        .autoPlay(true)
7570        .onAppear(()=>{
7571          this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[]
7572        })
7573      }
7574
7575      Button("set frame")
7576        .onClick(()=>{
7577          this.scenes.forEach((scenes: SwiperDynamicSyncScene) => {
7578
7579            if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) {
7580              scenes.setFrameRateRange(this.ANIMATION)
7581            }
7582
7583            if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) {
7584              scenes.setFrameRateRange(this.GESTURE)
7585            }
7586          });
7587        })
7588    }
7589  }
7590}
7591```
7592
7593### getFrameRateRange<sup>12+</sup>
7594
7595getFrameRateRange(): ExpectedFrameRateRange
7596
7597获取期望帧率范围。
7598
7599**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
7600
7601**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
7602
7603**返回值:**
7604
7605| 类型                  | 说明      |
7606| ------------------- | ------- |
7607| [ExpectedFrameRateRange](../apis-arkui/arkui-ts/ts-explicit-animation.md#expectedframeraterange11) | 期望帧率范围。|
7608
7609**示例:**
7610
7611```ts
7612import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI'
7613
7614@Entry
7615@Component
7616struct Frame {
7617  @State ANIMATION:ExpectedFrameRateRange = {min:0, max:120, expected: 90}
7618  @State GESTURE:ExpectedFrameRateRange = {min:0, max:120, expected: 30}
7619  private scenes: SwiperDynamicSyncScene[] = []
7620
7621  build() {
7622    Column() {
7623      Text("动画"+ JSON.stringify(this.ANIMATION))
7624      Text("跟手"+ JSON.stringify(this.GESTURE))
7625      Row(){
7626        Swiper() {
7627          Text("one")
7628          Text("two")
7629          Text("three")
7630        }
7631        .width('100%')
7632        .height('300vp')
7633        .id("dynamicSwiper")
7634        .backgroundColor(Color.Blue)
7635        .autoPlay(true)
7636        .onAppear(()=>{
7637          this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[]
7638        })
7639      }
7640
7641      Button("set frame")
7642        .onClick(()=>{
7643          this.scenes.forEach((scenes: SwiperDynamicSyncScene) => {
7644
7645            if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) {
7646              scenes.setFrameRateRange(this.ANIMATION)
7647              scenes.getFrameRateRange()
7648            }
7649
7650            if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) {
7651              scenes.setFrameRateRange(this.GESTURE)
7652              scenes.getFrameRateRange()
7653            }
7654          });
7655        })
7656      }
7657  }
7658}
7659```
7660## SwiperDynamicSyncScene<sup>12+</sup>
7661
7662SwiperDynamicSyncScene继承自[DynamicSyncScene](#dynamicsyncscene12),对应Swiper的动态帧率场景。
7663
7664**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
7665
7666**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
7667
7668| 名称       | 类型                                                      | 只读 | 可选 | 说明                                |
7669| --------- | --------------------------------------------------------- | ---- | ---- | ---------------------------------- |
7670| type      | [SwiperDynamicSyncSceneType](#swiperdynamicsyncscenetype12) | 是   | 否   | Swiper的动态帧率场景。             |
7671
7672## SwiperDynamicSyncSceneType<sup>12+</sup>
7673
7674枚举值,表示动态帧率场景的类型。
7675
7676**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
7677
7678**系统能力:**  SystemCapability.ArkUI.ArkUI.Full
7679
7680| 名称     | 值   | 说明                   |
7681| -------- | ---- | ---------------------- |
7682| GESTURE | 0   | 手势操作场景 |
7683| ANIMATION | 1   | 动画过度场景 |
7684