• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.arkui.UIContext (UIContext)
2
3In the stage model, a window stage or window can use the [loadContent](js-apis-window.md#loadcontent9) API to load pages, create a UI instance, and render page content to the associated window. Naturally, UI instances and windows are associated on a one-by-one basis. Some global UI APIs are executed in the context of certain UI instances. When calling these APIs, you must identify the UI context, and consequently UI instance, by tracing the call chain. If these APIs are called on a non-UI page or in some asynchronous callback, the current UI context may fail to be identified, resulting in API execution errors.
4
5**@ohos.window** adds the [getUIContext](js-apis-window.md#getuicontext10) API in API version 10 for obtaining the **UIContext** object of a UI instance. The API provided by the **UIContext** object can be directly applied to the corresponding UI instance.
6
7> **NOTE**
8>
9> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
10>
11> You can preview how this component looks on a real device, but not in DevEco Studio Previewer.
12
13## UIContext
14
15In the following API examples, you must first use [getUIContext()](js-apis-window.md#getuicontext10) in **@ohos.window** to obtain a **UIContext** instance, and then call the APIs using the obtained instance. Alternatively, you can obtain a **UIContext** instance through the built-in method [getUIContext()](arkui-ts/ts-custom-component-api.md#getuicontext) of the custom component. In this document, the **UIContext** instance is represented by **uiContext**.
16
17### getFont
18
19getFont(): Font
20
21Obtains a **Font** object.
22
23**Atomic service API**: This API can be used in atomic services since API version 11.
24
25**System capability**: SystemCapability.ArkUI.ArkUI.Full
26
27**Return value**
28
29| Type           | Description         |
30| ------------- | ----------- |
31| [Font](#font) | **Font** object.|
32
33**Example**
34
35<!--code_no_check-->
36```ts
37uiContext.getFont();
38```
39### getComponentUtils
40
41getComponentUtils(): ComponentUtils
42
43Obtains the **ComponentUtils** object.
44
45**Atomic service API**: This API can be used in atomic services since API version 11.
46
47**System capability**: SystemCapability.ArkUI.ArkUI.Full
48
49**Return value**
50
51| Type                               | Description                   |
52| --------------------------------- | --------------------- |
53| [ComponentUtils](#componentutils) | **ComponentUtils** object.|
54
55**Example**
56
57<!--code_no_check-->
58```ts
59uiContext.getComponentUtils();
60```
61
62### getUIInspector
63
64getUIInspector(): UIInspector
65
66Obtains the **UIInspector** object.
67
68**Atomic service API**: This API can be used in atomic services since API version 11.
69
70**System capability**: SystemCapability.ArkUI.ArkUI.Full
71
72**Return value**
73
74| Type                         | Description                |
75| --------------------------- | ------------------ |
76| [UIInspector](#uiinspector) | **UIInspector** object.|
77
78**Example**
79
80<!--code_no_check-->
81```ts
82uiContext.getUIInspector();
83```
84
85### getUIObserver<sup>11+</sup>
86
87getUIObserver(): UIObserver
88
89Obtains the **UIObserver** object.
90
91**Atomic service API**: This API can be used in atomic services since API version 12.
92
93**System capability**: SystemCapability.ArkUI.ArkUI.Full
94
95**Return value**
96
97| Type                         | Description                |
98| --------------------------- | ------------------ |
99| [UIObserver](#uiobserver11) | **UIObserver** object.|
100
101**Example**
102
103<!--code_no_check-->
104```ts
105uiContext.getUIObserver();
106```
107
108### getMediaQuery
109
110getMediaQuery(): MediaQuery
111
112Obtains a **MediaQuery** object.
113
114**Atomic service API**: This API can be used in atomic services since API version 11.
115
116**System capability**: SystemCapability.ArkUI.ArkUI.Full
117
118**Return value**
119
120| Type                       | Description               |
121| ------------------------- | ----------------- |
122| [MediaQuery](#mediaquery) | **MediaQuery** object.|
123
124**Example**
125
126<!--code_no_check-->
127```ts
128uiContext.getMediaQuery();
129```
130
131### getRouter
132
133getRouter(): Router
134
135Obtains a **Router** object.
136
137**Atomic service API**: This API can be used in atomic services since API version 11.
138
139**System capability**: SystemCapability.ArkUI.ArkUI.Full
140
141**Return value**
142
143| Type               | Description           |
144| ----------------- | ------------- |
145| [Router](#router) | **Router** object.|
146
147**Example**
148
149<!--code_no_check-->
150```ts
151uiContext.getRouter();
152```
153
154### getPromptAction
155
156getPromptAction(): PromptAction
157
158Obtains a **PromptAction** object.
159
160**Atomic service API**: This API can be used in atomic services since API version 11.
161
162**System capability**: SystemCapability.ArkUI.ArkUI.Full
163
164**Return value**
165
166| Type                           | Description                 |
167| ----------------------------- | ------------------- |
168| [PromptAction](#promptaction) | **PromptAction** object.|
169
170**Example**
171
172<!--code_no_check-->
173```ts
174uiContext.getPromptAction();
175```
176
177### getOverlayManager<sup>12+</sup>
178
179getOverlayManager(): OverlayManager
180
181Obtains the **OverlayManager** object.
182
183**Atomic service API**: This API can be used in atomic services since API version 12.
184
185**System capability**: SystemCapability.ArkUI.ArkUI.Full
186
187**Return value**
188
189| Type                          | Description                |
190| ----------------------------- | ------------------- |
191| [OverlayManager](#overlaymanager12) | **OverlayManager** instance obtained.|
192
193**Example**
194
195<!--code_no_check-->
196```ts
197uiContext.getOverlayManager();
198```
199
200### setOverlayManagerOptions<sup>15+</sup>
201
202setOverlayManagerOptions(options: OverlayManagerOptions): boolean
203
204Sets the parameters for [OverlayManager](#overlaymanager12). This API initializes the parameters of the **OverlayManager** before using its capabilities, including properties such as whether to render the overlay root node. It must be called before **getOverlayManager** and takes effect only once.
205
206**Atomic service API**: This API can be used in atomic services since API version 15.
207
208**System capability**: SystemCapability.ArkUI.ArkUI.Full
209
210**Parameters**
211
212| Name  | Type                                      | Mandatory  | Description                                   |
213| ----- | ---------------------------------------- | ---- | ------------------------------------- |
214| options | [OverlayManagerOptions](#overlaymanageroptions15) | Yes| Parameters for **OverlayManager**.|
215
216**Return value**
217
218| Type   | Description          |
219| ------- | -------------- |
220| boolean | Whether the setting is successful.<br>Returns **true** if the setting is successful; returns **false** otherwise.|
221
222**Example**
223
224<!--code_no_check-->
225```ts
226uiContext.setOverlayManagerOptions({ renderRootOverlay: true, enableBackPressedEvent: true });
227```
228
229### getOverlayManagerOptions<sup>15+</sup>
230
231getOverlayManagerOptions(): OverlayManagerOptions
232
233Obtains the current parameters of [OverlayManager](#overlaymanager12).
234
235**Atomic service API**: This API can be used in atomic services since API version 15.
236
237**System capability**: SystemCapability.ArkUI.ArkUI.Full
238
239**Return value**
240
241| Type                          | Description                |
242| ----------------------------- | ------------------- |
243| [OverlayManagerOptions](#overlaymanageroptions15) | Current parameters of **OverlayManager**.|
244
245**Example**
246
247<!--code_no_check-->
248```ts
249uiContext.getOverlayManagerOptions();
250```
251
252### animateTo
253
254animateTo(value: AnimateParam, event: () => void): void
255
256Applies a transition animation for state changes.
257
258**Atomic service API**: This API can be used in atomic services since API version 11.
259
260**System capability**: SystemCapability.ArkUI.ArkUI.Full
261
262**Parameters**
263
264| Name  | Type                                      | Mandatory  | Description                                   |
265| ----- | ---------------------------------------- | ---- | ------------------------------------- |
266| value | [AnimateParam](arkui-ts/ts-explicit-animation.md#animateparam) | Yes   | Animation settings.                          |
267| event | () => void                               | Yes   | Closure function that displays the animation. The system automatically inserts the transition animation if the state changes in the closure function.|
268
269**Example**
270
271```ts
272// xxx.ets
273@Entry
274@Component
275struct AnimateToExample {
276  @State widthSize: number = 250
277  @State heightSize: number = 100
278  @State rotateAngle: number = 0
279  private flag: boolean = true
280  uiContext: UIContext | undefined = undefined;
281
282  aboutToAppear() {
283    this.uiContext = this.getUIContext();
284    if (!this.uiContext) {
285      console.warn("no uiContext");
286      return;
287    }
288  }
289
290  build() {
291    Column() {
292      Button('change size')
293        .width(this.widthSize)
294        .height(this.heightSize)
295        .margin(30)
296        .onClick(() => {
297          if (this.flag) {
298            this.uiContext?.animateTo({
299              duration: 2000,
300              curve: Curve.EaseOut,
301              iterations: 3,
302              playMode: PlayMode.Normal,
303              onFinish: () => {
304                console.info('play end')
305              }
306            }, () => {
307              this.widthSize = 150
308              this.heightSize = 60
309            })
310          } else {
311            this.uiContext?.animateTo({}, () => {
312              this.widthSize = 250
313              this.heightSize = 100
314            })
315          }
316          this.flag = !this.flag
317        })
318      Button('stop rotating')
319        .margin(50)
320        .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
321        .onAppear(() => {
322          // The animation starts when the component appears.
323          this.uiContext?.animateTo({
324            duration: 1200,
325            curve: Curve.Friction,
326            delay: 500,
327            iterations: -1, // The value -1 indicates that the animation is played for an unlimited number of times.
328            playMode: PlayMode.Alternate,
329            expectedFrameRateRange: {
330              min: 10,
331              max: 120,
332              expected: 60,
333            }
334          }, () => {
335            this.rotateAngle = 90
336          })
337        })
338        .onClick(() => {
339          this.uiContext?.animateTo({ duration: 0 }, () => {
340            // The value of this.rotateAngle is 90 before the animation. In an animation with a duration of 0, changing the property stops any previous animations for that property and applies the new value immediately.
341            this.rotateAngle = 0
342          })
343        })
344    }.width('100%').margin({ top: 5 })
345  }
346}
347```
348
349### getSharedLocalStorage<sup>12+</sup>
350
351getSharedLocalStorage(): LocalStorage | undefined
352
353Obtains the **LocalStorage** instance shared by this stage.
354
355**Atomic service API**: This API can be used in atomic services since API version 12.
356
357**System capability**: SystemCapability.ArkUI.ArkUI.Full
358
359**Model restriction**: This API can be used only in the stage model.
360
361**Return value**
362
363| Type                            | Description               |
364| ------------------------------ | ----------------- |
365| [LocalStorage](arkui-ts/ts-state-management.md#localstorage9) \| undefined | **LocalStorage** instance if it exists; **undefined** if it does not exist.|
366
367**Example**
368
369```ts
370// EntryAbility.ets
371import { UIAbility } from '@kit.AbilityKit';
372import { window } from '@kit.ArkUI';
373
374export default class EntryAbility extends UIAbility {
375  storage: LocalStorage = new LocalStorage();
376
377  onWindowStageCreate(windowStage: window.WindowStage) {
378    windowStage.loadContent('pages/Index', this.storage);
379  }
380}
381```
382
383```ts
384// Index.ets
385
386@Entry
387@Component
388struct SharedLocalStorage {
389  localStorage = this.getUIContext().getSharedLocalStorage();
390
391  build() {
392    Row() {
393      Column() {
394        Button("Change Local Storage to 47")
395          .onClick(() => {
396            this.localStorage?.setOrCreate("propA", 47);
397          })
398        Button("Get Local Storage")
399          .onClick(() => {
400            console.info(`localStorage: ${this.localStorage?.get("propA")}`);
401          })
402      }
403      .width('100%')
404    }
405    .height('100%')
406  }
407}
408```
409
410### getHostContext<sup>12+</sup>
411
412getHostContext(): Context | undefined
413
414Obtains the context of this ability.
415
416**Atomic service API**: This API can be used in atomic services since API version 12.
417
418**System capability**: SystemCapability.ArkUI.ArkUI.Full
419
420**Model restriction**: This API can be used only in the stage model.
421
422**Return value**
423
424| Type| Description                            |
425| ------ | ------------------------------- |
426| [Context](#context12) \| undefined | Context of the ability. The context type depends on the ability type. For example, if this API is called on a page of the UIAbility, the return value type is UIAbilityContext; if this API is called on a page of the ExtensionAbility, the return value type is ExtensionContext. If the ability context does not exist, **undefined** is returned.|
427
428**Example**
429
430```ts
431@Entry
432@Component
433struct Index {
434  uiContext = this.getUIContext();
435
436  build() {
437    Row() {
438      Column() {
439        Text("cacheDir='"+this.uiContext?.getHostContext()?.cacheDir+"'").fontSize(25)
440        Text("bundleCodeDir='"+this.uiContext?.getHostContext()?.bundleCodeDir+"'").fontSize(25)
441      }
442      .width('100%')
443    }
444    .height('100%')
445  }
446}
447```
448
449### getFrameNodeById<sup>12+</sup>
450
451getFrameNodeById(id: string): FrameNode | null
452
453Obtains a FrameNode on the component tree based on the component ID.
454
455**Atomic service API**: This API can be used in atomic services since API version 12.
456
457**System capability**: SystemCapability.ArkUI.ArkUI.Full
458
459**Parameters**
460
461| Name  | Type                                      | Mandatory  | Description                                   |
462| ----- | ---------------------------------------- | ---- | ------------------------------------- |
463| id | string | Yes   | [Component ID](arkui-ts/ts-universal-attributes-component-id.md) of the target node.      |
464
465**Return value**
466
467| Type                                      | Description           |
468| ---------------------------------------- | ------------- |
469| [FrameNode](js-apis-arkui-frameNode.md)  \| null | FrameNode (if available) or null node.|
470
471> **NOTE**
472>
473> The **getFrameNodeById** API searches for a node with a specific ID by traversing the tree, which can lead to poor performance. To deliver better performance, use the [getAttachedFrameNodeById](#getattachedframenodebyid12) API.
474
475**Example**
476
477<!--code_no_check-->
478```ts
479uiContext.getFrameNodeById("TestNode")
480```
481
482### getAttachedFrameNodeById<sup>12+</sup>
483
484getAttachedFrameNodeById(id: string): FrameNode | null
485
486Obtains the entity node attached to the current window based on its component ID.
487
488**Atomic service API**: This API can be used in atomic services since API version 12.
489
490**System capability**: SystemCapability.ArkUI.ArkUI.Full
491
492**Parameters**
493
494| Name  | Type                                      | Mandatory  | Description                                   |
495| ----- | ---------------------------------------- | ---- | ------------------------------------- |
496| id | string | Yes   | [Component ID](arkui-ts/ts-universal-attributes-component-id.md) of the target node.                         |
497
498**Return value**
499
500| Type                                      | Description           |
501| ---------------------------------------- | ------------- |
502| [FrameNode](js-apis-arkui-frameNode.md)  \| null | FrameNode (if available) or null node.|
503
504> **NOTE**
505>
506> **getAttachedFrameNodeById** can only obtain nodes that are currently rendered on the screen.
507
508**Example**
509
510<!--code_no_check-->
511```ts
512uiContext.getAttachedFrameNodeById("TestNode")
513```
514
515### getFrameNodeByUniqueId<sup>12+</sup>
516
517getFrameNodeByUniqueId(id: number): FrameNode | null
518
519Obtains the entity node, FrameNode, of a component on the component tree using its **uniqueId**. The return value depends on the type of component associated with the **uniqueId**.
5201. If the **uniqueId** corresponds to a built-in component, the associated FrameNode is returned.
5212. If the **uniqueId** corresponds to a custom component: If the component has rendered content, its root node is returned, with the type __Common__; if the component has no rendered content, the FrameNode of its first child component is returned.
5223. If the **uniqueId** does not correspond to any component, **null** is returned.
523
524**Atomic service API**: This API can be used in atomic services since API version 12.
525
526**System capability**: SystemCapability.ArkUI.ArkUI.Full
527
528**Parameters**
529
530| Name  | Type                                      | Mandatory  | Description                                   |
531| ----- | ---------------------------------------- | ---- | ------------------------------------- |
532| id | number | Yes   | Unique ID of the target node.                         |
533
534**Return value**
535
536| Type                                      | Description           |
537| ---------------------------------------- | ------------- |
538| [FrameNode](js-apis-arkui-frameNode.md)  \| null | Entity node of the component or **null** if no matching component is found.|
539
540**Example**
541
542```ts
543import { UIContext, FrameNode } from '@kit.ArkUI';
544
545@Entry
546@Component
547struct MyComponent {
548  aboutToAppear() {
549    let uniqueId: number = this.getUniqueId();
550    let uiContext: UIContext = this.getUIContext();
551    if (uiContext) {
552      let node: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId);
553    }
554  }
555
556  build() {
557    // ...
558  }
559}
560```
561
562### getPageInfoByUniqueId<sup>12+</sup>
563
564getPageInfoByUniqueId(id: number): PageInfo
565
566Obtains the router or navigation destination page information corresponding to the node that matches the specified **uniqueId**.
5671. If the node that matches the specified **uniqueId** is in a page, the router information (**routerPageInfo**) is returned.
5682. If the node that matches the specified **uniqueId** is in a **NavDestination** component, the navigation destination page information (**navDestinationInfo**) is returned.
5693. If the node that matches the specified **uniqueId** does not have the corresponding router or navigation destination page information, **undefined** is returned.
5704. Modal dialog boxes are not contained within any pages. If the node that matches the specified **uniqueId** is in a modal dialog box, for example, on a modal page constructed by [CustomDialog](./arkui-ts/ts-methods-custom-dialog-box.md), [bindSheet](./arkui-ts/ts-universal-attributes-sheet-transition.md#bindsheet), or [bindContentCover](./arkui-ts/ts-universal-attributes-modal-transition.md#bindcontentcover), **undefined** is returned for **routerPageInfo**.
571
572**Atomic service API**: This API can be used in atomic services since API version 12.
573
574**System capability**: SystemCapability.ArkUI.ArkUI.Full
575
576**Parameters**
577
578| Name  | Type                                      | Mandatory  | Description                                   |
579| ----- | ---------------------------------------- | ---- | ------------------------------------- |
580| id | number | Yes   | Unique ID of the target node.                         |
581
582**Return value**
583
584| Type                                      | Description           |
585| ---------------------------------------- | ------------- |
586| [PageInfo](#pageinfo12) | Router or navigation destination page information corresponding to the specified node.|
587
588**Example**
589
590```ts
591import { UIContext, PageInfo } from '@kit.ArkUI';
592
593@Entry
594@Component
595struct PageInfoExample {
596  @Provide('pageInfos') pageInfos: NavPathStack = new NavPathStack();
597
598  build() {
599    Column() {
600      Navigation(this.pageInfos) {
601        NavDestination() {
602          MyComponent()
603        }
604      }.id('navigation')
605    }
606  }
607}
608
609@Component
610struct MyComponent {
611  @State content: string = '';
612
613  build() {
614    Column() {
615      Text('PageInfoExample')
616      Button('click').onClick(() => {
617        const uiContext: UIContext = this.getUIContext();
618        const uniqueId: number = this.getUniqueId();
619        const pageInfo: PageInfo = uiContext.getPageInfoByUniqueId(uniqueId);
620        console.info('pageInfo: ' + JSON.stringify(pageInfo));
621        console.info('navigationInfo: ' + JSON.stringify(uiContext.getNavigationInfoByUniqueId(uniqueId)));
622      })
623      TextArea({
624        text: this.content
625      })
626      .width('100%')
627      .height(100)
628    }
629    .width('100%')
630    .alignItems(HorizontalAlign.Center)
631  }
632}
633```
634
635### getNavigationInfoByUniqueId<sup>12+</sup>
636
637getNavigationInfoByUniqueId(id: number): observer.NavigationInfo | undefined
638
639Obtains the navigation information corresponding to the node that matches the specified **uniqueId**.
6401. If the node that matches the specified **uniqueId** is in a **Navigation** component, the navigation information is returned.
6412. If the node that matches the specified **uniqueId** does not have the corresponding navigation information, **undefined** is returned.
642
643**Atomic service API**: This API can be used in atomic services since API version 12.
644
645**System capability**: SystemCapability.ArkUI.ArkUI.Full
646
647**Parameters**
648
649| Name  | Type                                      | Mandatory  | Description                                   |
650| ----- | ---------------------------------------- | ---- | ------------------------------------- |
651| id | number | Yes   | Unique ID of the target node.                         |
652
653**Return value**
654
655| Type                                      | Description           |
656| ---------------------------------------- | ------------- |
657| observer.[NavigationInfo](js-apis-arkui-observer.md#navigationinfo12) \| undefined | Navigation information corresponding to the specified node.|
658
659**Example**
660
661See the example of [getPageInfoByUniqueId](#getpageinfobyuniqueid12).
662
663### showAlertDialog
664
665showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions): void
666
667Shows an alert dialog box.
668
669**Atomic service API**: This API can be used in atomic services since API version 11.
670
671**System capability**: SystemCapability.ArkUI.ArkUI.Full
672
673**Parameters**
674
675| Name    | Type                                      | Mandatory  | Description                 |
676| ------- | ---------------------------------------- | ---- | ------------------- |
677| options | [AlertDialogParamWithConfirm](arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm) \| [AlertDialogParamWithButtons](arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons) \| [AlertDialogParamWithOptions](arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithoptions10) | Yes   | Shows an **AlertDialog** component in the given settings.|
678
679
680**Example**
681
682<!--code_no_check-->
683```ts
684uiContext.showAlertDialog(
685  {
686    title: 'title',
687    message: 'text',
688    autoCancel: true,
689    alignment: DialogAlignment.Bottom,
690    offset: { dx: 0, dy: -20 },
691    gridCount: 3,
692    confirm: {
693      value: 'button',
694      action: () => {
695        console.info('Button-clicking callback')
696      }
697    },
698    cancel: () => {
699      console.info('Closed callbacks')
700    }
701  }
702)
703```
704
705### showActionSheet
706
707showActionSheet(value: ActionSheetOptions): void
708
709Shows an action sheet in the given settings.
710
711**Atomic service API**: This API can be used in atomic services since API version 11.
712
713**System capability**: SystemCapability.ArkUI.ArkUI.Full
714
715**Parameters**
716
717| Name| Type                                                        | Mandatory| Description                |
718| ------ | ------------------------------------------------------------ | ---- | -------------------- |
719| value  | [ActionSheetOptions](arkui-ts/ts-methods-action-sheet.md#actionsheetoptions) | Yes  | Parameters of the action sheet.|
720
721**Example**
722
723<!--code_no_check-->
724```ts
725uiContext.showActionSheet({
726  title: 'ActionSheet title',
727  message: 'message',
728  autoCancel: true,
729  confirm: {
730    value: 'Confirm button',
731    action: () => {
732      console.info('Get Alert Dialog handled')
733    }
734  },
735  cancel: () => {
736    console.info('actionSheet canceled')
737  },
738  alignment: DialogAlignment.Bottom,
739  offset: { dx: 0, dy: -10 },
740  sheets: [
741    {
742      title: 'apples',
743      action: () => {
744        console.info('apples')
745      }
746    },
747    {
748      title: 'bananas',
749      action: () => {
750        console.info('bananas')
751      }
752    },
753    {
754      title: 'pears',
755      action: () => {
756        console.info('pears')
757      }
758    }
759  ]
760})
761```
762
763### showDatePickerDialog
764
765showDatePickerDialog(options: DatePickerDialogOptions): void
766
767Shows a date picker dialog box in the given settings.
768
769**Atomic service API**: This API can be used in atomic services since API version 11.
770
771**System capability**: SystemCapability.ArkUI.ArkUI.Full
772
773**Parameters**
774
775| Name | Type                                                        | Mandatory| Description                          |
776| ------- | ------------------------------------------------------------ | ---- | ------------------------------ |
777| options | [DatePickerDialogOptions](arkui-ts/ts-methods-datepicker-dialog.md#datepickerdialogoptions) | Yes  | Parameters of the date picker dialog box.|
778
779**Example**
780
781<!--code_no_check-->
782```ts
783let selectedDate: Date = new Date("2010-1-1")
784uiContext.showDatePickerDialog({
785  start: new Date("2000-1-1"),
786  end: new Date("2100-12-31"),
787  selected: selectedDate,
788  onAccept: (value: DatePickerResult) => {
789    // Use the setFullYear method to set the date when the OK button is touched. In this way, when the date picker dialog box is displayed again, the selected date is the date last confirmed.
790    selectedDate.setFullYear(Number(value.year), Number(value.month), Number(value.day))
791    console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))
792  },
793  onCancel: () => {
794    console.info("DatePickerDialog:onCancel()")
795  },
796  onChange: (value: DatePickerResult) => {
797    console.info("DatePickerDialog:onChange()" + JSON.stringify(value))
798  }
799})
800```
801
802### showTimePickerDialog
803
804showTimePickerDialog(options: TimePickerDialogOptions): void
805
806Shows a time picker dialog box in the given settings.
807
808**Atomic service API**: This API can be used in atomic services since API version 11.
809
810**System capability**: SystemCapability.ArkUI.ArkUI.Full
811
812**Parameters**
813
814| Name | Type                                                        | Mandatory| Description                          |
815| ------- | ------------------------------------------------------------ | ---- | ------------------------------ |
816| options | [TimePickerDialogOptions](arkui-ts/ts-methods-timepicker-dialog.md#timepickerdialogoptions) | Yes  | Parameters of the time picker dialog box.|
817
818**Example**
819
820```ts
821// xxx.ets
822
823class SelectTime{
824  selectTime: Date = new Date('2020-12-25T08:30:00')
825  hours(h:number,m:number){
826    this.selectTime.setHours(h,m)
827  }
828}
829
830@Entry
831@Component
832struct TimePickerDialogExample {
833  @State selectTime: Date = new Date('2023-12-25T08:30:00');
834
835  build() {
836    Column() {
837      Button('showTimePickerDialog')
838        .margin(30)
839        .onClick(() => {
840          this.getUIContext().showTimePickerDialog({
841            selected: this.selectTime,
842            onAccept: (value: TimePickerResult) => {
843              // Set selectTime to the time when the OK button is clicked. In this way, when the dialog box is displayed again, the selected time is the time when the operation was confirmed last time.
844              let time = new SelectTime()
845              if(value.hour&&value.minute){
846                time.hours(value.hour, value.minute)
847              }
848              console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))
849            },
850            onCancel: () => {
851              console.info("TimePickerDialog:onCancel()")
852            },
853            onChange: (value: TimePickerResult) => {
854              console.info("TimePickerDialog:onChange()" + JSON.stringify(value))
855            }
856          })
857        })
858    }.width('100%').margin({ top: 5 })
859  }
860}
861```
862
863### showTextPickerDialog
864
865showTextPickerDialog(options: TextPickerDialogOptions): void
866
867Shows a text picker dialog box in the given settings.
868
869**Atomic service API**: This API can be used in atomic services since API version 11.
870
871**System capability**: SystemCapability.ArkUI.ArkUI.Full
872
873**Parameters**
874
875| Name | Type                                                        | Mandatory| Description                          |
876| ------- | ------------------------------------------------------------ | ---- | ------------------------------ |
877| options | [TextPickerDialogOptions](arkui-ts/ts-methods-textpicker-dialog.md#textpickerdialogoptions) | Yes  | Parameters of the text picker dialog box.|
878
879**Example**
880
881```ts
882// xxx.ets
883
884class SelectedValue{
885  select: number = 2
886  set(val:number){
887    this.select = val
888  }
889}
890class SelectedArray{
891  select: number[] = []
892  set(val:number[]){
893    this.select = val
894  }
895}
896@Entry
897@Component
898struct TextPickerDialogExample {
899  @State selectTime: Date = new Date('2023-12-25T08:30:00');
900  private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5']
901  private select : number  = 0;
902  build() {
903    Column() {
904      Button('showTextPickerDialog')
905        .margin(30)
906        .onClick(() => {
907          this.getUIContext().showTextPickerDialog({
908            range: this.fruits,
909            selected: this.select,
910            onAccept: (value: TextPickerResult) => {
911              // Set select to the index of the item selected when the OK button is touched. In this way, when the text picker dialog box is displayed again, the selected item is the one last confirmed.
912              let selectedVal = new SelectedValue()
913              let selectedArr = new SelectedArray()
914              if(value.index){
915                  value.index instanceof Array?selectedArr.set(value.index) : selectedVal.set(value.index)
916              }
917              console.info("TextPickerDialog:onAccept()" + JSON.stringify(value))
918            },
919            onCancel: () => {
920              console.info("TextPickerDialog:onCancel()")
921            },
922            onChange: (value: TextPickerResult) => {
923              console.info("TextPickerDialog:onChange()" + JSON.stringify(value))
924            }
925          })
926        })
927    }.width('100%').margin({ top: 5 })
928  }
929}
930```
931
932### createAnimator
933
934createAnimator(options: AnimatorOptions): AnimatorResult
935
936Creates an **Animator** object.
937
938**Atomic service API**: This API can be used in atomic services since API version 11.
939
940**System capability**: SystemCapability.ArkUI.ArkUI.Full
941
942**Parameters**
943
944| Name    | Type                                      | Mandatory  | Description     |
945| ------- | ---------------------------------------- | ---- | ------- |
946| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) | Yes   | Animator options.|
947
948**Return value**
949
950| Type                                      | Description           |
951| ---------------------------------------- | ------------- |
952| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator result.|
953
954
955**Error codes**
956
957For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
958
959| ID| Error Message|
960| ------- | -------- |
961| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
962
963**Example**
964
965```ts
966// EntryAbility.ets
967import { AnimatorOptions, window } from '@kit.ArkUI';
968import { hilog } from '@kit.PerformanceAnalysisKit';
969
970// used in UIAbility
971onWindowStageCreate(windowStage: window.WindowStage) {
972  // Main window is created, set main page for this ability
973  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
974  windowStage.loadContent('pages/Index', (err, data) => {
975    if (err.code) {
976      hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
977      return;
978    }
979    hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
980    let uiContext = windowStage.getMainWindowSync().getUIContext();
981    let options:AnimatorOptions = {
982      duration: 1500,
983      easing: "friction",
984      delay: 0,
985      fill: "forwards",
986      direction: "normal",
987      iterations: 3,
988      begin: 200.0,
989      end: 400.0
990    };
991    uiContext.createAnimator(options);
992  });
993}
994```
995
996### createAnimator<sup>18+</sup>
997
998createAnimator(options: AnimatorOptions | SimpleAnimatorOptions): AnimatorResult
999
1000Creates an **AnimatorResult** object for animations. Compared to the previous [createAnimator](#createanimator) API, this API adds support for the [SimpleAnimatorOptions](js-apis-animator.md#simpleanimatoroptions18) type.
1001
1002**Atomic service API**: This API can be used in atomic services since API version 18.
1003
1004**System capability**: SystemCapability.ArkUI.ArkUI.Full
1005
1006**Parameters**
1007
1008| Name    | Type                                      | Mandatory  | Description     |
1009| ------- | ---------------------------------------- | ---- | ------- |
1010| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) \| [SimpleAnimatorOptions](js-apis-animator.md#simpleanimatoroptions18) | Yes   | Animator options.|
1011
1012**Return value**
1013
1014| Type                                      | Description           |
1015| ---------------------------------------- | ------------- |
1016| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator result.|
1017
1018**Error codes**
1019
1020For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1021
1022| ID| Error Message|
1023| ------- | -------- |
1024| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
1025
1026**Example**
1027
1028```ts
1029import { SimpleAnimatorOptions, window } from '@kit.ArkUI';
1030import { hilog } from '@kit.PerformanceAnalysisKit';
1031
1032// used in UIAbility
1033onWindowStageCreate(windowStage: window.WindowStage) {
1034  // Main window is created, set main page for this ability
1035  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
1036  windowStage.loadContent('pages/Index', (err, data) => {
1037    if (err.code) {
1038      hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
1039      return;
1040    }
1041    hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
1042    let uiContext = windowStage.getMainWindowSync().getUIContext();
1043    let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).duration(2000);
1044    uiContext.createAnimator(options);
1045  });
1046}
1047```
1048
1049### runScopedTask
1050
1051runScopedTask(callback: () => void): void
1052
1053Executes the specified callback in this UI context.
1054
1055**Atomic service API**: This API can be used in atomic services since API version 11.
1056
1057**System capability**: SystemCapability.ArkUI.ArkUI.Full
1058
1059**Parameters**
1060
1061| Name     | Type        | Mandatory  | Description  |
1062| -------- | ---------- | ---- | ---- |
1063| callback | () => void | Yes   | Callback used to return the result.|
1064
1065**Example**
1066
1067<!--code_no_check-->
1068```ts
1069uiContext.runScopedTask(
1070  () => {
1071    console.info('Succeeded in runScopedTask');
1072  }
1073);
1074```
1075
1076### setKeyboardAvoidMode<sup>11+</sup>
1077
1078setKeyboardAvoidMode(value: KeyboardAvoidMode): void
1079
1080Sets the avoidance mode for the virtual keyboard.
1081
1082**Atomic service API**: This API can be used in atomic services since API version 11.
1083
1084**System capability**: SystemCapability.ArkUI.ArkUI.Full
1085
1086**Parameters**
1087
1088| Name     | Type        | Mandatory  | Description  |
1089| -------- | ---------- | ---- | ---- |
1090| value | [KeyboardAvoidMode](#keyboardavoidmode11)| Yes   | Avoidance mode for the virtual keyboard.<br>Default value: **KeyboardAvoidMode.OFFSET**|
1091
1092**Example**
1093
1094```ts
1095// EntryAbility.ets
1096import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI';
1097import { hilog } from '@kit.PerformanceAnalysisKit';
1098
1099onWindowStageCreate(windowStage: window.WindowStage) {
1100    // Main window is created, set main page for this ability
1101    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
1102
1103    windowStage.loadContent('pages/Index', (err, data) => {
1104      let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext();
1105      uiContext.setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE);
1106      if (err.code) {
1107        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
1108        return;
1109      }
1110      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
1111    });
1112  }
1113```
1114
1115### getKeyboardAvoidMode<sup>11+</sup>
1116
1117getKeyboardAvoidMode(): KeyboardAvoidMode
1118
1119Obtains the avoidance mode for the virtual keyboard.
1120
1121**Atomic service API**: This API can be used in atomic services since API version 11.
1122
1123**System capability**: SystemCapability.ArkUI.ArkUI.Full
1124
1125**Return value**
1126
1127| Type        | Description  |
1128| ---------- | ---- |
1129| [KeyboardAvoidMode](#keyboardavoidmode11)| Avoidance mode for the virtual keyboard.|
1130
1131**Example**
1132
1133```ts
1134// EntryAbility.ets
1135import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI';
1136import { hilog } from '@kit.PerformanceAnalysisKit';
1137
1138onWindowStageCreate(windowStage: window.WindowStage) {
1139    // Main window is created, set main page for this ability
1140    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
1141
1142    windowStage.loadContent('pages/Index', (err, data) => {
1143      let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext();
1144      let KeyboardAvoidMode = uiContext.getKeyboardAvoidMode();
1145      hilog.info(0x0000, "KeyboardAvoidMode:", JSON.stringify(KeyboardAvoidMode));
1146      if (err.code) {
1147        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
1148        return;
1149      }
1150      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
1151    });
1152  }
1153
1154```
1155
1156### getAtomicServiceBar<sup>11+</sup>
1157
1158getAtomicServiceBar(): Nullable\<AtomicServiceBar>
1159
1160Obtains an **AtomicServiceBar** object, which can be used to set the properties of the atomic service menu bar.
1161
1162**Atomic service API**: This API can be used in atomic services since API version 11.
1163
1164**System capability**: SystemCapability.ArkUI.ArkUI.Full
1165
1166**Return value**
1167
1168| Type                                             | Description                                                        |
1169| ------------------------------------------------- | ------------------------------------------------------------ |
1170| Nullable<[AtomicServiceBar](#atomicservicebar11)> | Returns the **AtomicServerBar** type if the service is an atomic service; returns **undefined** type otherwise.|
1171
1172**Example**
1173
1174```ts
1175// EntryAbility.ets
1176import { UIContext, AtomicServiceBar, window } from '@kit.ArkUI';
1177import { hilog } from '@kit.PerformanceAnalysisKit';
1178onWindowStageCreate(windowStage: window.WindowStage) {
1179  // Main window is created, set main page for this ability
1180  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
1181  windowStage.loadContent('pages/Index', (err, data) => {
1182    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
1183    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
1184    if (atomicServiceBar != undefined) {
1185      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
1186    } else {
1187      hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
1188    }
1189  });
1190}
1191```
1192### getDragController<sup>11+</sup>
1193
1194getDragController(): DragController
1195
1196Obtains the **DragController** object, which can be used to create and initiate dragging.
1197
1198**Atomic service API**: This API can be used in atomic services since API version 12.
1199
1200**System capability**: SystemCapability.ArkUI.ArkUI.Full
1201
1202**Return value**
1203
1204|Type|Description|
1205|----|----|
1206|[DragController](js-apis-arkui-dragController.md#dragController)| **DragController** object.|
1207
1208**Example**
1209
1210<!--code_no_check-->
1211```ts
1212uiContext.getDragController();
1213```
1214
1215### keyframeAnimateTo<sup>11+</sup>
1216
1217keyframeAnimateTo(param: KeyframeAnimateParam, keyframes: Array&lt;KeyframeState&gt;): void
1218
1219Generates a key frame animation. For details about how to use this API, see [keyframeAnimateTo](arkui-ts/ts-keyframeAnimateTo.md).
1220
1221**Atomic service API**: This API can be used in atomic services since API version 12.
1222
1223**System capability**: SystemCapability.ArkUI.ArkUI.Full
1224
1225**Parameters**
1226
1227| Name| Type                                             | Mandatory| Description                     |
1228| ------------ | ---------------------------------------------------- | ------- | ---------------------------- |
1229| param        | [KeyframeAnimateParam](arkui-ts/ts-keyframeAnimateTo.md#keyframeanimateparam) | Yes     | Overall animation parameter of the keyframe animation.    |
1230| keyframes    | Array&lt;[KeyframeState](arkui-ts/ts-keyframeAnimateTo.md#keyframestate)&gt;  | Yes     | States of all keyframes.           |
1231
1232### getFocusController<sup>12+</sup>
1233
1234getFocusController(): FocusController
1235
1236Obtains a [FocusController](js-apis-arkui-UIContext.md#focuscontroller12) object, which can be used to control the focus.
1237
1238**Atomic service API**: This API can be used in atomic services since API version 12.
1239
1240**System capability**: SystemCapability.ArkUI.ArkUI.Full
1241
1242**Return value**
1243
1244|Type|Description|
1245|----|----|
1246|[FocusController](js-apis-arkui-UIContext.md#focuscontroller12)| **FocusController** object.|
1247
1248**Example**
1249
1250<!--code_no_check-->
1251```ts
1252uiContext.getFocusController();
1253```
1254
1255### getFilteredInspectorTree<sup>12+</sup>
1256
1257getFilteredInspectorTree(filters?: Array\<string\>): string
1258
1259Obtains the component tree and component attributes.
1260
1261**Atomic service API**: This API can be used in atomic services since API version 12.
1262
1263**System capability**: SystemCapability.ArkUI.ArkUI.Full
1264
1265**Parameters**
1266
1267| Name | Type           | Mandatory| Description                                                        |
1268| ------- | --------------- | ---- | ------------------------------------------------------------ |
1269| filters | Array\<string\> | No  | List of component attributes used for filtering. Currently, only the following values are supported:<br>**"id"**: unique ID of the component.<br>**"src"**: source of the resource.<br>**"content"**: information or data contained in the element, component, or object.<br>**"editable"**: whether the component is editable.<br>**"scrollable"**: whether the component is scrollable.<br>**"selectable"**: whether the component is selectable.<br>**"focusable"**: whether the component is focusable.<br>**"focused"**: whether the component is currently focused.<br>Other values are used only in test scenarios.|
1270
1271**Return value**
1272
1273| Type  | Description                              |
1274| ------ | ---------------------------------- |
1275| string | JSON string of the component tree and component attributes.|
1276
1277**Error codes**
1278
1279For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1280
1281| ID| Error Message|
1282| ------- | -------- |
1283| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
1284
1285**Example**
1286
1287<!--code_no_check-->
1288```ts
1289uiContext.getFilteredInspectorTree(['id', 'src', 'content']);
1290```
1291
1292### getFilteredInspectorTreeById<sup>12+</sup>
1293
1294getFilteredInspectorTreeById(id: string, depth: number, filters?: Array\<string\>): string
1295
1296Obtains the attributes of the specified component and its child components.
1297
1298**Atomic service API**: This API can be used in atomic services since API version 12.
1299
1300**System capability**: SystemCapability.ArkUI.ArkUI.Full
1301
1302**Parameters**
1303
1304| Name | Type           | Mandatory| Description                                                        |
1305| ------- | --------------- | ---- | ------------------------------------------------------------ |
1306| id      | string          | Yes  | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.|
1307| depth   | number          | Yes  | Number of layers of child components. If the value is **0**, the attributes of the specified component and all its child components are obtained. If the value is **1**, only the attributes of the specified component are obtained. If the value is **2**, the attributes of the specified component and its level-1 child components are obtained. The rest can be deduced by analogy.|
1308| filters | Array\<string\> | No  | List of component attributes used for filtering. Currently, only the following values are supported:<br>**"id"**: unique ID of the component.<br>**"src"**: source of the resource.<br>**"content"**: information or data contained in the element, component, or object.<br>**"editable"**: whether the component is editable.<br>**"scrollable"**: whether the component is scrollable.<br>**"selectable"**: whether the component is selectable.<br>**"focusable"**: whether the component is focusable.<br>**"focused"**: whether the component is currently focused.<br>Other values are used only in test scenarios.|
1309
1310**Return value**
1311
1312| Type  | Description                                        |
1313| ------ | -------------------------------------------- |
1314| string | JSON string of the attributes of the specified component and its child components.|
1315
1316
1317**Error codes**
1318
1319For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
1320
1321| ID| Error Message|
1322| ------- | -------- |
1323| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
1324
1325**Example**
1326
1327<!--code_no_check-->
1328```ts
1329uiContext.getFilteredInspectorTreeById('testId', 0, ['id', 'src', 'content']);
1330```
1331
1332### getCursorController<sup>12+</sup>
1333
1334getCursorController(): CursorController
1335
1336Obtains a [CursorController](js-apis-arkui-UIContext.md#cursorcontroller12) object, which can be used to control the focus.
1337
1338**Atomic service API**: This API can be used in atomic services since API version 12.
1339
1340**System capability**: SystemCapability.ArkUI.ArkUI.Full
1341
1342**Return value**
1343
1344|Type|Description|
1345|----|----|
1346|[CursorController](js-apis-arkui-UIContext.md#cursorcontroller12)| **CursorController** object.|
1347
1348**Example**
1349
1350<!--code_no_check-->
1351```ts
1352uiContext.CursorController();
1353```
1354
1355### getContextMenuController<sup>12+</sup>
1356
1357getContextMenuController(): ContextMenuController
1358
1359Obtains a [ContextMenuController](#contextmenucontroller12) object, which can be used to control menus.
1360
1361**Atomic service API**: This API can be used in atomic services since API version 12.
1362
1363**System capability**: SystemCapability.ArkUI.ArkUI.Full
1364
1365**Return value**
1366
1367|Type|Description|
1368|----|----|
1369|[ContextMenuController](#contextmenucontroller12)| **ContextMenuController** object.|
1370
1371**Example**
1372
1373<!--code_no_check-->
1374```ts
1375uiContext.getContextMenuController();
1376```
1377
1378### getMeasureUtils<sup>12+</sup>
1379
1380getMeasureUtils(): MeasureUtils
1381
1382Obtains a **MeasureUtils** object for text calculation.
1383
1384**Atomic service API**: This API can be used in atomic services since API version 12.
1385
1386**System capability**: SystemCapability.ArkUI.ArkUI.Full
1387
1388**Return value**
1389
1390| Type  | Description                                        |
1391| ------ | -------------------------------------------- |
1392| [MeasureUtils](js-apis-arkui-UIContext.md#measureutils12) | Text metrics, such as text height and width.|
1393
1394**Example**
1395
1396<!--code_no_check-->
1397```ts
1398uiContext.getMeasureUtils();
1399```
1400
1401### getComponentSnapshot<sup>12+</sup>
1402
1403getComponentSnapshot(): ComponentSnapshot
1404
1405Obtains a **ComponentSnapshot** object, which can be used to obtain a component snapshot.
1406
1407**Atomic service API**: This API can be used in atomic services since API version 12.
1408
1409**System capability**: SystemCapability.ArkUI.ArkUI.Full
1410
1411**Return value**
1412
1413| Type                                                        | Description                       |
1414| ------------------------------------------------------------ | --------------------------- |
1415| [ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12) | **ComponentSnapshot** object.|
1416
1417**Example**
1418
1419<!--code_no_check-->
1420```ts
1421uiContext.getComponentSnapshot();
1422```
1423
1424### vp2px<sup>12+</sup>
1425
1426vp2px(value : number) : number
1427
1428Converts a value in units of vp to a value in units of px.
1429
1430**Atomic service API**: This API can be used in atomic services since API version 12.
1431
1432**System capability**: SystemCapability.ArkUI.ArkUI.Full
1433
1434**Parameters**
1435
1436| Name| Type  | Mandatory| Description                                  |
1437| ------ | ------ | ---- | -------------------------------------- |
1438| value | number | Yes  | Value to convert.<br>Value range: (-∞, +∞)|
1439
1440**Return value**
1441
1442| Type  | Description          |
1443| ------ | -------------- |
1444| number | Value after conversion.<br>Value range: (-∞, +∞)|
1445
1446**Example**
1447
1448<!--code_no_check-->
1449```ts
1450uiContext.vp2px(200);
1451```
1452
1453### px2vp<sup>12+</sup>
1454
1455px2vp(value : number) : number
1456
1457Converts a value in units of px to a value in units of vp.
1458
1459**Atomic service API**: This API can be used in atomic services since API version 12.
1460
1461**System capability**: SystemCapability.ArkUI.ArkUI.Full
1462
1463**Parameters**
1464
1465| Name| Type  | Mandatory| Description                                  |
1466| ------ | ------ | ---- | -------------------------------------- |
1467| value | number | Yes  | Value to convert.<br>Value range: (-∞, +∞)|
1468
1469**Return value**
1470
1471| Type  | Description          |
1472| ------ | -------------- |
1473| number | Value after conversion.<br>Value range: (-∞, +∞)|
1474
1475**Example**
1476
1477<!--code_no_check-->
1478```ts
1479uiContext.px2vp(200);
1480```
1481
1482### fp2px<sup>12+</sup>
1483
1484fp2px(value : number) : number
1485
1486Converts a value in units of fp to a value in units of px.
1487
1488**Atomic service API**: This API can be used in atomic services since API version 12.
1489
1490**System capability**: SystemCapability.ArkUI.ArkUI.Full
1491
1492**Parameters**
1493
1494| Name| Type  | Mandatory| Description                                  |
1495| ------ | ------ | ---- | -------------------------------------- |
1496| value | number | Yes  | Value to convert.<br>Value range: (-∞, +∞)|
1497
1498**Return value**
1499
1500| Type  | Description          |
1501| ------ | -------------- |
1502| number | Value after conversion.<br>Value range: (-∞, +∞)|
1503
1504**Example**
1505
1506<!--code_no_check-->
1507```ts
1508uiContext.fp2px(200);
1509```
1510
1511### px2fp<sup>12+</sup>
1512
1513px2fp(value : number) : number
1514
1515Converts a value in units of px to a value in units of fp.
1516
1517**Atomic service API**: This API can be used in atomic services since API version 12.
1518
1519**System capability**: SystemCapability.ArkUI.ArkUI.Full
1520
1521**Parameters**
1522
1523| Name| Type  | Mandatory| Description                                  |
1524| ------ | ------ | ---- | -------------------------------------- |
1525| value | number | Yes  | Value to convert.<br>Value range: (-∞, +∞)|
1526
1527**Return value**
1528
1529| Type  | Description          |
1530| ------ | -------------- |
1531| number | Value after conversion.<br>Value range: (-∞, +∞)|
1532
1533**Example**
1534
1535<!--code_no_check-->
1536```ts
1537uiContext.px2fp(200);
1538```
1539
1540### lpx2px<sup>12+</sup>
1541
1542lpx2px(value : number) : number
1543
1544Converts a value in units of lpx to a value in units of px.
1545
1546**Atomic service API**: This API can be used in atomic services since API version 12.
1547
1548**System capability**: SystemCapability.ArkUI.ArkUI.Full
1549
1550**Parameters**
1551
1552| Name| Type  | Mandatory| Description                                   |
1553| ------ | ------ | ---- | --------------------------------------- |
1554| value | number | Yes  | Value to convert.<br>Value range: (-∞, +∞)|
1555
1556**Return value**
1557
1558| Type  | Description          |
1559| ------ | -------------- |
1560| number | Value after conversion.<br>Value range: (-∞, +∞)|
1561
1562**Example**
1563
1564<!--code_no_check-->
1565```ts
1566uiContext.lpx2px(200);
1567```
1568
1569### px2lpx<sup>12+</sup>
1570
1571px2lpx(value : number) : number
1572
1573Converts a value in units of px to a value in units of lpx.
1574
1575**Atomic service API**: This API can be used in atomic services since API version 12.
1576
1577**System capability**: SystemCapability.ArkUI.ArkUI.Full
1578
1579**Parameters**
1580
1581| Name| Type  | Mandatory| Description                                   |
1582| ------ | ------ | ---- | --------------------------------------- |
1583| value | number | Yes  | Value to convert.<br>Value range: (-∞, +∞)|
1584
1585**Return value**
1586
1587| Type  | Description          |
1588| ------ | -------------- |
1589| number | Value after conversion.<br>Value range: (-∞, +∞)|
1590
1591**Example**
1592
1593<!--code_no_check-->
1594```ts
1595uiContext.px2lpx(200);
1596```
1597
1598### getWindowName<sup>12+</sup>
1599
1600getWindowName(): string | undefined
1601
1602Obtains the name of the window where this instance is located.
1603
1604**Atomic service API**: This API can be used in atomic services since API version 12.
1605
1606**System capability**: SystemCapability.ArkUI.ArkUI.Full
1607
1608**Return value**
1609
1610| Type  | Description                                        |
1611| ------ | -------------------------------------------- |
1612| string \| undefined | Name of the window where the current instance is located. If the window does not exist, **undefined** is returned.|
1613
1614**Example**
1615
1616```ts
1617import { window } from '@kit.ArkUI';
1618
1619@Entry
1620@Component
1621struct Index {
1622  @State message: string = 'Hello World'
1623
1624  aboutToAppear() {
1625    const windowName = this.getUIContext().getWindowName();
1626    console.info('WindowName ' + windowName);
1627    const currWindow = window.findWindow(windowName);
1628    const windowProperties = currWindow.getWindowProperties();
1629    console.info(`Window width ${windowProperties.windowRect.width}, height ${windowProperties.windowRect.height}`);
1630  }
1631
1632  build() {
1633    Row() {
1634      Column() {
1635        Text(this.message)
1636          .fontSize(50)
1637          .fontWeight(FontWeight.Bold)
1638      }
1639      .width('100%')
1640    }
1641    .height('100%')
1642  }
1643}
1644```
1645
1646### getWindowWidthBreakpoint<sup>13+</sup>
1647
1648getWindowWidthBreakpoint(): WidthBreakpoint
1649
1650Obtains the width breakpoint value of the window where this instance is located. The specific value is determined by the vp value of the window width. For details, see [WidthBreakpoint](./arkui-ts/ts-appendix-enums.md#widthbreakpoint13).
1651
1652**Atomic service API**: This API can be used in atomic services since API version 13.
1653
1654**System capability**: SystemCapability.ArkUI.ArkUI.Full
1655
1656**Return value**
1657
1658| Type  | Description                                        |
1659| ------ | -------------------------------------------- |
1660| [WidthBreakpoint](./arkui-ts/ts-appendix-enums.md#widthbreakpoint13) | Width breakpoint value of the window where the current instance is located. If the window width is 0 vp, **WIDTH_XS** is returned.|
1661
1662**Example**
1663
1664```ts
1665import { UIContext } from '@kit.ArkUI';
1666
1667@Entry
1668@Component
1669struct Index {
1670  @State message: string = 'Hello World';
1671
1672  build() {
1673    Row() {
1674      Column() {
1675        Text(this.message)
1676          .fontSize(30)
1677          .fontWeight(FontWeight.Bold)
1678        Button() {
1679          Text('test')
1680            .fontSize(30)
1681        }
1682        .onClick(() => {
1683          let uiContext: UIContext = this.getUIContext();
1684          let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint();
1685          let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint();
1686          console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`)
1687        })
1688      }
1689      .width('100%')
1690    }
1691    .height('100%')
1692  }
1693}
1694```
1695
1696### getWindowHeightBreakpoint<sup>13+</sup>
1697
1698getWindowHeightBreakpoint(): HeightBreakpoint
1699
1700Obtains the height breakpoint value of the window where this instance is located. The specific value is determined based on the window aspect ratio. For details, see [HeightBreakpoint](./arkui-ts/ts-appendix-enums.md#heightbreakpoint13).
1701
1702**Atomic service API**: This API can be used in atomic services since API version 13.
1703
1704**System capability**: SystemCapability.ArkUI.ArkUI.Full
1705
1706**Return value**
1707
1708| Type  | Description                                        |
1709| ------ | -------------------------------------------- |
1710| [HeightBreakpoint](./arkui-ts/ts-appendix-enums.md#heightbreakpoint13) | Height breakpoint value of the window where the current instance is located. If the window aspect ratio is 0, **HEIGHT_SM** is returned.|
1711
1712**Example**
1713
1714```ts
1715import { UIContext } from '@kit.ArkUI';
1716
1717@Entry
1718@Component
1719struct Index {
1720  @State message: string = 'Hello World';
1721
1722  build() {
1723    Row() {
1724      Column() {
1725        Text(this.message)
1726          .fontSize(30)
1727          .fontWeight(FontWeight.Bold)
1728        Button() {
1729          Text('test')
1730            .fontSize(30)
1731        }
1732        .onClick(() => {
1733          let uiContext: UIContext = this.getUIContext();
1734          let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint();
1735          let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint();
1736          console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`)
1737        })
1738      }
1739      .width('100%')
1740    }
1741    .height('100%')
1742  }
1743}
1744```
1745
1746### postFrameCallback<sup>12+</sup>
1747
1748postFrameCallback(frameCallback: FrameCallback): void
1749
1750Registers a callback that is executed when the next frame is rendered.
1751
1752**Atomic service API**: This API can be used in atomic services since API version 12.
1753
1754**System capability**: SystemCapability.ArkUI.ArkUI.Full
1755
1756**Parameters**
1757
1758| Name| Type  | Mandatory| Description                                   |
1759| ------ | ------ | ---- | --------------------------------------- |
1760| frameCallback | [FrameCallback](#framecallback12) | Yes  | Callback to be executed for the next frame.|
1761
1762**Example**
1763
1764```ts
1765import {FrameCallback } from '@kit.ArkUI';
1766
1767class MyFrameCallback extends FrameCallback {
1768  private tag: string;
1769
1770  constructor(tag: string) {
1771    super()
1772    this.tag = tag;
1773  }
1774
1775  onFrame(frameTimeNanos: number) {
1776    console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString());
1777  }
1778}
1779
1780@Entry
1781@Component
1782struct Index {
1783  build() {
1784    Row() {
1785      Button('Invoke postFrameCallback')
1786        .onClick(() => {
1787          this.getUIContext().postFrameCallback(new MyFrameCallback("normTask"));
1788        })
1789    }
1790  }
1791}
1792```
1793
1794### postDelayedFrameCallback<sup>12+</sup>
1795
1796postDelayedFrameCallback(frameCallback: FrameCallback, delayTime: number): void
1797
1798Registers a callback to be executed on the next frame after a delay.
1799
1800**Atomic service API**: This API can be used in atomic services since API version 12.
1801
1802**System capability**: SystemCapability.ArkUI.ArkUI.Full
1803
1804**Parameters**
1805
1806| Name| Type  | Mandatory| Description                                   |
1807| ------ | ------ | ---- | --------------------------------------- |
1808| frameCallback | [FrameCallback](#framecallback12) | Yes  | Callback to be executed for the next frame.|
1809| delayTime | number | Yes  | Delay time, in milliseconds. If a **null**, **undefined**, or value less than 0 is passed in, it will be treated as **0**.|
1810
1811**Example**
1812
1813```ts
1814import {FrameCallback } from '@kit.ArkUI';
1815
1816class MyFrameCallback extends FrameCallback {
1817  private tag: string;
1818
1819  constructor(tag: string) {
1820    super()
1821    this.tag = tag;
1822  }
1823
1824  onFrame(frameTimeNanos: number) {
1825    console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString());
1826  }
1827}
1828
1829@Entry
1830@Component
1831struct Index {
1832  build() {
1833    Row() {
1834      Button('Invoke postDelayedFrameCallback')
1835        .onClick(() => {
1836          this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5);
1837        })
1838    }
1839  }
1840}
1841```
1842
1843### requireDynamicSyncScene<sup>12+</sup>
1844
1845requireDynamicSyncScene(id: string): Array&lt;DynamicSyncScene&gt;
1846
1847Requests the dynamic sync scene of a component for customizing related frame rate configuration.
1848
1849**Atomic service API**: This API can be used in atomic services since API version 12.
1850
1851**System capability**: SystemCapability.ArkUI.ArkUI.Full
1852
1853**Parameters**
1854
1855| Name| Type  | Mandatory| Description                                   |
1856| ------ | ------ | ---- | --------------------------------------- |
1857| id | string | Yes   | [Component ID](arkui-ts/ts-universal-attributes-component-id.md) of the target node.|
1858
1859**Return value**
1860
1861| Type  | Description                                        |
1862| ------ | -------------------------------------------- |
1863| Array&lt;DynamicSyncScene&gt; | **DynamicSyncScene** object array.|
1864
1865**Example**
1866
1867<!--code_no_check-->
1868```ts
1869uiContext.DynamicSyncScene("dynamicSyncScene")
1870```
1871
1872### openBindSheet<sup>12+</sup>
1873
1874openBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions?: SheetOptions, targetId?: number): Promise&lt;void&gt;
1875
1876Creates a sheet whose content is as defined in **bindSheetContent** and displays the sheet. This API uses a promise to return the result.
1877
1878> **NOTE**
1879>
1880> 1. When calling this API, if you don't provide a valid value for **targetId**, you won't be able to set **SheetOptions.preferType** to **POPUP** or **SheetOptions.mode** to **EMBEDDED**.
1881>
1882> 2. Since [updateBindSheet](#updatebindsheet12) and [closeBindSheet](#closebindsheet12) depend on **bindSheetContent**, you need to maintain the passed **bindSheetContent** yourself.
1883>
1884> 3. Setting **SheetOptions.UIContext** is not supported.
1885>
1886
1887**Atomic service API**: This API can be used in atomic services since API version 12.
1888
1889**System capability**: SystemCapability.ArkUI.ArkUI.Full
1890
1891**Parameters**
1892
1893| Name    | Type                                      | Mandatory  | Description     |
1894| ------- | ---------------------------------------- | ---- | ------- |
1895| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content to display on the sheet.|
1896| sheetOptions | [SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions) | No   |   Style of the sheet.<br>**NOTE**<br>1. **SheetOptions.uiContext** cannot be set. Its value is fixed to the **UIContext** object of the current instance.<br>2. If **targetId** is not passed in, **SheetOptions.preferType** cannot be set to **POPUP**; if **POPUP** is set, it will be replaced with **CENTER**.<br>3. If **targetId** is not passed in, **SheetOptions.mode** cannot be set to **EMBEDDED**; the default mode is **OVERLAY**.<br>4. For the default values of other attributes, see [SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions).|
1897| targetId | number | No   |   ID of the component to be bound. If this parameter is not set, no component is bound.|
1898
1899**Return value**
1900
1901| Type                                      | Description     |
1902| ---------------------------------------- | ------- |
1903|   Promise&lt;void&gt;           |    Promise used to return the result.|
1904
1905**Error codes**
1906
1907For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Sheet Error Codes](errorcode-bindSheet.md).
1908
1909| ID | Error Message                              |
1910| ------ | ---------------------------------- |
1911| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
1912| 120001 | The bindSheetContent is incorrect. |
1913| 120002 | The bindSheetContent already exists. |
1914| 120004 | The targetId does not exist. |
1915| 120005 | The node of targetId is not in the component tree. |
1916| 120006 | The node of targetId is not a child of the page node or NavDestination node. |
1917
1918**Example**
1919
1920```ts
1921import { FrameNode, ComponentContent } from "@kit.ArkUI";
1922import { BusinessError } from '@kit.BasicServicesKit';
1923
1924class Params {
1925  text: string = ""
1926
1927  constructor(text: string) {
1928    this.text = text;
1929  }
1930}
1931
1932let contentNode: ComponentContent<Params>;
1933let gUIContext: UIContext;
1934
1935@Builder
1936function buildText(params: Params) {
1937  Column() {
1938    Text(params.text)
1939    Button('Update BindSheet')
1940      .fontSize(20)
1941      .onClick(() => {
1942        gUIContext.updateBindSheet(contentNode, {
1943          backgroundColor: Color.Pink,
1944        }, true)
1945          .then(() => {
1946            console.info('updateBindSheet success');
1947          })
1948          .catch((err: BusinessError) => {
1949            console.info('updateBindSheet error: ' + err.code + ' ' + err.message);
1950          })
1951      })
1952
1953    Button('Close BindSheet')
1954      .fontSize(20)
1955      .onClick(() => {
1956        gUIContext.closeBindSheet(contentNode)
1957          .then(() => {
1958            console.info('closeBindSheet success');
1959          })
1960          .catch((err: BusinessError) => {
1961            console.info('closeBindSheet error: ' + err.code + ' ' + err.message);
1962          })
1963      })
1964  }
1965}
1966
1967@Entry
1968@Component
1969struct UIContextBindSheet {
1970  @State message: string = 'BindSheet';
1971
1972  aboutToAppear() {
1973    gUIContext = this.getUIContext();
1974    contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message));
1975  }
1976
1977  build() {
1978    RelativeContainer() {
1979      Column() {
1980        Button('Open BindSheet')
1981          .fontSize(20)
1982          .onClick(() => {
1983            let uiContext = this.getUIContext();
1984            let uniqueId = this.getUniqueId();
1985            let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId);
1986            let targetId = frameNode?.getFirstChild()?.getUniqueId();
1987            uiContext.openBindSheet(contentNode, {
1988              height: SheetSize.MEDIUM,
1989              backgroundColor: Color.Green,
1990              title: { title: "Title", subtitle: "subtitle" }
1991            }, targetId)
1992              .then(() => {
1993                console.info('openBindSheet success');
1994              })
1995              .catch((err: BusinessError) => {
1996                console.info('openBindSheet error: ' + err.code + ' ' + err.message);
1997              })
1998          })
1999      }
2000    }
2001    .height('100%')
2002    .width('100%')
2003  }
2004}
2005```
2006
2007### updateBindSheet<sup>12+</sup>
2008
2009updateBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions: SheetOptions, partialUpdate?: boolean ): Promise&lt;void&gt;
2010
2011Updates the style of the sheet corresponding to the provided **bindSheetContent**. This API uses a promise to return the result.
2012
2013> **NOTE**
2014>
2015> **SheetOptions.UIContext**, **SheetOptions.mode**, and callback functions cannot be updated.
2016>
2017
2018**Atomic service API**: This API can be used in atomic services since API version 12.
2019
2020**System capability**: SystemCapability.ArkUI.ArkUI.Full
2021
2022**Parameters**
2023
2024| Name    | Type                                      | Mandatory  | Description     |
2025| ------- | ---------------------------------------- | ---- | ------- |
2026| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content to display on the sheet.|
2027| sheetOptions | [SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions) | Yes   |   Style of the sheet.<br>**NOTE**<br>**SheetOptions.UIContext** and **SheetOptions.mode** cannot be updated.|
2028| partialUpdate | boolean | No   |   Whether to update the sheet in incremental mode.<br>Default value: **false**<br>**NOTE**<br>1. **true**: incremental update, where the specified properties in **SheetOptions** are updated, and other properties stay at their current value.<br>2. **false**: full update, where all properties except those specified in **SheetOptions** are restored to default values.|
2029
2030**Return value**
2031
2032| Type                                      | Description     |
2033| ---------------------------------------- | ------- |
2034|   Promise&lt;void&gt;           |    Promise used to return the result.|
2035
2036**Error codes**
2037
2038For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Sheet Error Codes](errorcode-bindSheet.md).
2039
2040| ID | Error Message                              |
2041| ------ | ---------------------------------- |
2042| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
2043| 120001 | The bindSheetContent is incorrect. |
2044| 120003 | The bindSheetContent cannot be found. |
2045
2046**Example**
2047
2048```ts
2049import { FrameNode, ComponentContent } from "@kit.ArkUI";
2050import { BusinessError } from '@kit.BasicServicesKit';
2051
2052class Params {
2053  text: string = ""
2054
2055  constructor(text: string) {
2056    this.text = text;
2057  }
2058}
2059
2060let contentNode: ComponentContent<Params>;
2061let gUIContext: UIContext;
2062
2063@Builder
2064function buildText(params: Params) {
2065  Column() {
2066    Text(params.text)
2067    Button('Update BindSheet')
2068      .fontSize(20)
2069      .onClick(() => {
2070        gUIContext.updateBindSheet(contentNode, {
2071          backgroundColor: Color.Pink,
2072        }, true)
2073          .then(() => {
2074            console.info('updateBindSheet success');
2075          })
2076          .catch((err: BusinessError) => {
2077            console.info('updateBindSheet error: ' + err.code + ' ' + err.message);
2078          })
2079      })
2080
2081    Button('Close BindSheet')
2082      .fontSize(20)
2083      .onClick(() => {
2084        gUIContext.closeBindSheet(contentNode)
2085          .then(() => {
2086            console.info('closeBindSheet success');
2087          })
2088          .catch((err: BusinessError) => {
2089            console.info('closeBindSheet error: ' + err.code + ' ' + err.message);
2090          })
2091      })
2092  }
2093}
2094
2095@Entry
2096@Component
2097struct UIContextBindSheet {
2098  @State message: string = 'BindSheet';
2099
2100  aboutToAppear() {
2101    gUIContext = this.getUIContext();
2102    contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message));
2103  }
2104
2105  build() {
2106    RelativeContainer() {
2107      Column() {
2108        Button('Open BindSheet')
2109          .fontSize(20)
2110          .onClick(() => {
2111            let uiContext = this.getUIContext();
2112            let uniqueId = this.getUniqueId();
2113            let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId);
2114            let targetId = frameNode?.getFirstChild()?.getUniqueId();
2115            uiContext.openBindSheet(contentNode, {
2116              height: SheetSize.MEDIUM,
2117              backgroundColor: Color.Green,
2118              title: { title: "Title", subtitle: "subtitle" }
2119            }, targetId)
2120              .then(() => {
2121                console.info('openBindSheet success');
2122              })
2123              .catch((err: BusinessError) => {
2124                console.info('openBindSheet error: ' + err.code + ' ' + err.message);
2125              })
2126          })
2127      }
2128    }
2129    .height('100%')
2130    .width('100%')
2131  }
2132}
2133```
2134
2135### closeBindSheet<sup>12+</sup>
2136
2137closeBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>): Promise&lt;void&gt;
2138
2139Closes the sheet corresponding to **bindSheetContent**. This API uses a promise to return the result.
2140
2141> **NOTE**
2142>
2143> Closing a sheet using this API will not invoke the **shouldDismiss** callback.
2144>
2145
2146**Atomic service API**: This API can be used in atomic services since API version 12.
2147
2148**System capability**: SystemCapability.ArkUI.ArkUI.Full
2149
2150**Parameters**
2151
2152| Name    | Type                                      | Mandatory  | Description     |
2153| ------- | ---------------------------------------- | ---- | ------- |
2154| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content to display on the sheet.|
2155
2156**Return value**
2157
2158| Type                                      | Description     |
2159| ---------------------------------------- | ------- |
2160|   Promise&lt;void&gt;           |    Promise used to return the result.|
2161
2162**Error codes**
2163
2164For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Sheet Error Codes](errorcode-bindSheet.md).
2165
2166| ID | Error Message                              |
2167| ------ | ---------------------------------- |
2168| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
2169| 120001 | The bindSheetContent is incorrect. |
2170| 120003 | The bindSheetContent cannot be found. |
2171
2172**Example**
2173
2174```ts
2175import { FrameNode, ComponentContent } from "@kit.ArkUI";
2176import { BusinessError } from '@kit.BasicServicesKit';
2177
2178class Params {
2179  text: string = ""
2180
2181  constructor(text: string) {
2182    this.text = text;
2183  }
2184}
2185
2186let contentNode: ComponentContent<Params>;
2187let gUIContext: UIContext;
2188
2189@Builder
2190function buildText(params: Params) {
2191  Column() {
2192    Text(params.text)
2193    Button('Update BindSheet')
2194      .fontSize(20)
2195      .onClick(() => {
2196        gUIContext.updateBindSheet(contentNode, {
2197          backgroundColor: Color.Pink,
2198        }, true)
2199          .then(() => {
2200            console.info('updateBindSheet success');
2201          })
2202          .catch((err: BusinessError) => {
2203            console.info('updateBindSheet error: ' + err.code + ' ' + err.message);
2204          })
2205      })
2206
2207    Button('Close BindSheet')
2208      .fontSize(20)
2209      .onClick(() => {
2210        gUIContext.closeBindSheet(contentNode)
2211          .then(() => {
2212            console.info('closeBindSheet success');
2213          })
2214          .catch((err: BusinessError) => {
2215            console.info('closeBindSheet error: ' + err.code + ' ' + err.message);
2216          })
2217      })
2218  }
2219}
2220
2221@Entry
2222@Component
2223struct UIContextBindSheet {
2224  @State message: string = 'BindSheet';
2225
2226  aboutToAppear() {
2227    gUIContext = this.getUIContext();
2228    contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message));
2229  }
2230
2231  build() {
2232    RelativeContainer() {
2233      Column() {
2234        Button('Open BindSheet')
2235          .fontSize(20)
2236          .onClick(() => {
2237            let uiContext = this.getUIContext();
2238            let uniqueId = this.getUniqueId();
2239            let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId);
2240            let targetId = frameNode?.getFirstChild()?.getUniqueId();
2241            uiContext.openBindSheet(contentNode, {
2242              height: SheetSize.MEDIUM,
2243              backgroundColor: Color.Green,
2244              title: { title: "Title", subtitle: "subtitle" }
2245            }, targetId)
2246              .then(() => {
2247                console.info('openBindSheet success');
2248              })
2249              .catch((err: BusinessError) => {
2250                console.info('openBindSheet error: ' + err.code + ' ' + err.message);
2251              })
2252          })
2253      }
2254    }
2255    .height('100%')
2256    .width('100%')
2257  }
2258}
2259```
2260
2261### isFollowingSystemFontScale<sup>13+</sup>
2262
2263isFollowingSystemFontScale(): boolean
2264
2265Checks whether this UI context follows the system font scale settings.
2266
2267**Atomic service API**: This API can be used in atomic services since API version 13.
2268
2269**System capability**: SystemCapability.ArkUI.ArkUI.Full
2270
2271**Return value**
2272
2273| Type     | Description           |
2274|---------|---------------|
2275| boolean | Whether the current UI context follows the system font scale settings.|
2276
2277**Example**
2278
2279<!--code_no_check-->
2280```ts
2281uiContext.isFollowingSystemFontScale()
2282```
2283
2284### getMaxFontScale<sup>13+</sup>
2285
2286getMaxFontScale(): number
2287
2288Obtains the maximum font scale of this UI context.
2289
2290**Atomic service API**: This API can be used in atomic services since API version 13.
2291
2292**System capability**: SystemCapability.ArkUI.ArkUI.Full
2293
2294**Return value**
2295
2296| Type     | Description       |
2297|---------|-----------|
2298| number | Maximum font scale of the current UI context.|
2299
2300**Example**
2301
2302<!--code_no_check-->
2303```ts
2304uiContext.getMaxFontScale()
2305```
2306
2307### bindTabsToScrollable<sup>13+</sup>
2308
2309bindTabsToScrollable(tabsController: TabsController, scroller: Scroller): void;
2310
2311Binds a **Tabs** component with a scrollable container, which can be a [List](./arkui-ts/ts-container-list.md), [Scroll](./arkui-ts/ts-container-scroll.md), [Grid](./arkui-ts/ts-container-grid.md), or [WaterFlow](./arkui-ts/ts-container-waterflow.md) component. This way, scrolling the scrollable container triggers the display and hide animations of the tab bar for all **Tabs** components that are bound to it – scrolling up triggers the hide animation, and scrolling down triggers the show animation. A **TabsController** instance can be bound with multiple **Scroller** instances, and conversely, a **Scroller** instance can be bound with multiple **TabsController** instances.
2312
2313>  **NOTE**
2314>
2315>  When multiple scrollable containers are bound to the same **Tabs** component, scrolling any of the bound containers will trigger the appearance and disappearance animations of the tab bar. In addition, when any scrollable container reaches the bottom, the tab bar immediately triggers the appearance animation. Therefore, avoid scrolling multiple scrollable containers simultaneously whenever possible.
2316
2317**Atomic service API**: This API can be used in atomic services since API version 13.
2318
2319**System capability**: SystemCapability.ArkUI.ArkUI.Full
2320
2321**Parameters**
2322
2323| Name    | Type                                      | Mandatory  | Description     |
2324| ------- | ---------------------------------------- | ---- | ------- |
2325| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | Yes| Controller of the target **Tabs** component.|
2326| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target scrollable container.|
2327
2328**Example**
2329
2330```ts
2331@Entry
2332@Component
2333struct TabsExample {
2334  private arr: string[] = []
2335  private parentTabsController: TabsController = new TabsController()
2336  private childTabsController: TabsController = new TabsController()
2337  private listScroller: Scroller = new Scroller()
2338  private parentScroller: Scroller = new Scroller()
2339  private childScroller: Scroller = new Scroller()
2340
2341  aboutToAppear(): void {
2342    for (let i = 0; i < 20; i++) {
2343      this.arr.push(i.toString())
2344    }
2345    let context = this.getUIContext()
2346    context.bindTabsToScrollable(this.parentTabsController, this.listScroller)
2347    context.bindTabsToScrollable(this.childTabsController, this.listScroller)
2348    context.bindTabsToNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller)
2349  }
2350
2351  aboutToDisappear(): void {
2352    let context = this.getUIContext()
2353    context.unbindTabsFromScrollable(this.parentTabsController, this.listScroller)
2354    context.unbindTabsFromScrollable(this.childTabsController, this.listScroller)
2355    context.unbindTabsFromNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller)
2356  }
2357
2358  build() {
2359    Tabs({ barPosition: BarPosition.End, controller: this.parentTabsController }) {
2360      TabContent() {
2361        Tabs({ controller: this.childTabsController }) {
2362          TabContent() {
2363            List({ space: 20, initialIndex: 0, scroller: this.listScroller }) {
2364              ForEach(this.arr, (item: string) => {
2365                ListItem() {
2366                  Text(item)
2367                    .width('100%')
2368                    .height(100)
2369                    .fontSize(16)
2370                    .textAlign(TextAlign.Center)
2371                    .borderRadius(10)
2372                    .backgroundColor(Color.Gray)
2373                }
2374              }, (item: string) => item)
2375            }
2376            .scrollBar(BarState.Off)
2377            .width('90%')
2378            .height('100%')
2379            .contentStartOffset(56)
2380            .contentEndOffset(52)
2381          }.tabBar(SubTabBarStyle.of('Top tab'))
2382        }
2383        .width('100%')
2384        .height('100%')
2385        .barOverlap (true) // Make the tab bar overlap the TabContent component. This means that when the tab bar is hidden upwards or downwards, the area it occupies will not appear empty.
2386        .clip (true) // Clip any child components that extend beyond the Tabs component's boundaries, preventing accidental touches on the tab bar when it is hidden.
2387      }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), 'Scroller linked with TabsControllers'))
2388
2389      TabContent() {
2390        Scroll(this.parentScroller) {
2391            List({ space: 20, initialIndex: 0, scroller: this.childScroller }) {
2392              ForEach(this.arr, (item: string) => {
2393                ListItem() {
2394                  Text(item)
2395                    .width('100%')
2396                    .height(100)
2397                    .fontSize(16)
2398                    .textAlign(TextAlign.Center)
2399                    .borderRadius(10)
2400                    .backgroundColor(Color.Gray)
2401                }
2402              }, (item: string) => item)
2403            }
2404            .scrollBar(BarState.Off)
2405            .width('90%')
2406            .height('100%')
2407            .contentEndOffset(52)
2408            .nestedScroll({ scrollForward: NestedScrollMode.SELF_FIRST, scrollBackward: NestedScrollMode.SELF_FIRST })
2409        }
2410        .width('100%')
2411        .height('100%')
2412        .scrollBar(BarState.Off)
2413        .scrollable(ScrollDirection.Vertical)
2414        .edgeEffect(EdgeEffect.Spring)
2415      }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), 'Nested Scroller linked with TabsController'))
2416    }
2417    .width('100%')
2418    .height('100%')
2419    .barOverlap (true) // Make the tab bar overlap the TabContent component. This means that when the tab bar is hidden upwards or downwards, the area it occupies will not appear empty.
2420    .clip (true) // Clip any child components that extend beyond the Tabs component's boundaries, preventing accidental touches on the tab bar when it is hidden.
2421  }
2422}
2423```
2424
2425![bindTabsToScrollable](figures/bindTabsToScrollable.gif)
2426
2427### unbindTabsFromScrollable<sup>13+</sup>
2428
2429unbindTabsFromScrollable(tabsController: TabsController, scroller: Scroller): void;
2430
2431Unbinds a **Tabs** component from a scrollable container.
2432
2433**Atomic service API**: This API can be used in atomic services since API version 13.
2434
2435**System capability**: SystemCapability.ArkUI.ArkUI.Full
2436
2437**Parameters**
2438
2439| Name    | Type                                      | Mandatory  | Description     |
2440| ------- | ---------------------------------------- | ---- | ------- |
2441| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | Yes| Controller of the target **Tabs** component.|
2442| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target scrollable container.|
2443
2444**Example**
2445
2446See the example for [bindTabsToScrollable](#bindtabstoscrollable13).
2447
2448### bindTabsToNestedScrollable<sup>13+</sup>
2449
2450bindTabsToNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void;
2451
2452Binds a **Tabs** component with a nested scrollable container, which can be a [List](./arkui-ts/ts-container-list.md), [Scroll](./arkui-ts/ts-container-scroll.md), [Grid](./arkui-ts/ts-container-grid.md), or [WaterFlow](./arkui-ts/ts-container-waterflow.md) component. This way, scrolling the parent or child component triggers the display and hide animations of the tab bar for all **Tabs** components that are bound to it – scrolling up triggers the hide animation, and scrolling down triggers the show animation. A **TabsController** instance can be bound with multiple nested **Scroller** instances, and conversely, a nested **Scroller** instance can be bound with multiple **TabsController** instances.
2453
2454**Atomic service API**: This API can be used in atomic services since API version 13.
2455
2456**System capability**: SystemCapability.ArkUI.ArkUI.Full
2457
2458**Parameters**
2459
2460| Name    | Type                                      | Mandatory  | Description     |
2461| ------- | ---------------------------------------- | ---- | ------- |
2462| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | Yes| Controller of the target **Tabs** component.|
2463| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target parent scrollable container.|
2464| childScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target child scrollable container, which is a nested child component of the component corresponding to **parentScroller**.|
2465
2466**Example**
2467
2468See the example for [bindTabsToScrollable](#bindtabstoscrollable13).
2469
2470### unbindTabsFromNestedScrollable<sup>13+</sup>
2471
2472unbindTabsFromNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void;
2473
2474Unbinds a **Tabs** component from a nested scrollable container.
2475
2476**Atomic service API**: This API can be used in atomic services since API version 13.
2477
2478**System capability**: SystemCapability.ArkUI.ArkUI.Full
2479
2480**Parameters**
2481
2482| Name    | Type                                      | Mandatory  | Description     |
2483| ------- | ---------------------------------------- | ---- | ------- |
2484| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | Yes| Controller of the target **Tabs** component.|
2485| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target parent scrollable container.|
2486| childScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target child scrollable container, which is a nested child component of the component corresponding to **parentScroller**.|
2487
2488**Example**
2489
2490See the example for [bindTabsToScrollable](#bindtabstoscrollable13).
2491
2492### enableSwipeBack<sup>18+</sup>
2493
2494enableSwipeBack(enabled: Optional\<boolean\>): void
2495
2496Sets whether to enable the horizontal swipe-to-go-back gesture within the application.
2497
2498**Atomic service API**: This API can be used in atomic services since API version 18.
2499
2500**System capability**: SystemCapability.ArkUI.ArkUI.Circle
2501
2502**Parameters**
2503
2504| Name    | Type   | Mandatory  | Description     |
2505| --- | --- | --- | --- |
2506| isEnabled | boolean | Yes| Whether to enable the horizontal swipe-to-go-back gesture.<br>Default value: **true**|
2507
2508**Example**
2509
2510```js
2511@Entry
2512@Component
2513struct Index {
2514  @State isEnable: boolean = true;
2515
2516  build() {
2517    RelativeContainer() {
2518      Button(`enable swipe back: ${this.isEnable}`).onClick(() => {
2519        this.isEnable = !this.isEnable;
2520        this.getUIContext().enableSwipeBack(this.isEnable);
2521      })
2522    }
2523    .height('100%')
2524    .width('100%')
2525  }
2526}
2527```
2528
2529### getTextMenuController<sup>16+</sup>
2530
2531getTextMenuController(): TextMenuController
2532
2533Obtains a [TextMenuController](#textmenucontroller16) object, which can be used to control the context menu on selection.
2534
2535**Atomic service API**: This API can be used in atomic services since API version 16.
2536
2537**System capability**: SystemCapability.ArkUI.ArkUI.Full
2538
2539**Return value**
2540
2541|Type|Description|
2542|----|----|
2543|[TextMenuController](#textmenucontroller16)| Obtained **TextMenuController** object.|
2544
2545**Example**
2546
2547See the example for the [TextMenuController](#textmenucontroller16) API .
2548
2549### createUIContextWithoutWindow<sup>18+</sup>
2550
2551static createUIContextWithoutWindow(context: common.UIAbilityContext | common.ExtensionContext) : UIContext | undefined
2552
2553Creates a UI instance that does not depend on a window and returns its UI context. The created UI instance is a singleton.
2554
2555> **NOTE**
2556>
2557> The returned UI context can only be used to create [custom nodes](../../ui/arkts-user-defined-node.md). It cannot be used for other UI operations.
2558
2559**Atomic service API**: This API can be used in atomic services since API version 18.
2560
2561**System capability**: SystemCapability.ArkUI.ArkUI.Full
2562
2563**Parameters**
2564
2565| Name | Type                                    | Mandatory| Description       |
2566| ------- | ---------------------------------------- | ---- | ----------- |
2567| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) \| common.[ExtensionContext](../apis-ability-kit/js-apis-inner-application-extensionContext.md) | Yes   | Context corresponding to [UIAbility](../apis-ability-kit/js-apis-app-ability-uiAbility.md) or [ExtensionAbility](../apis-ability-kit/js-apis-app-ability-extensionAbility.md).|
2568
2569**Return value**
2570
2571|Type|Description|
2572|----|----|
2573| UIContext \| undefined | Context of the created UI instance, or **undefined** if creation fails.|
2574
2575**Error codes**
2576
2577For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [UI Context Error Codes](errorcode-uicontext.md).
2578
2579| ID | Error Message                       |
2580| ------ | ---------------------------------- |
2581| 401    | Parameter error. Possible causes: <br> 1. The number of parameters is incorrect.<br> 2. Invalid parameter type of context. |
2582| 100001 | Internal error. |
2583
2584
2585**Example**
2586```ts
2587import { UIContext } from '@kit.ArkUI';
2588
2589export default class EntryAbility extends UIAbility {
2590  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
2591    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
2592    let uiContext : UIContext | undefined = UIContext.createUIContextWithoutWindow(this.context);
2593  }
2594
2595  // ......
2596}
2597```
2598
2599### destroyUIContextWithoutWindow<sup>18+</sup>
2600
2601static destroyUIContextWithoutWindow(): void
2602
2603Destroys the UI instance created using [createUIContextWithoutWindow](#createuicontextwithoutwindow18).
2604
2605**Atomic service API**: This API can be used in atomic services since API version 18.
2606
2607**System capability**: SystemCapability.ArkUI.ArkUI.Full
2608
2609**Example**
2610```ts
2611UIContext.destroyUIContextWithoutWindow();
2612```
2613
2614### dispatchKeyEvent<sup>15+</sup>
2615
2616dispatchKeyEvent(node: number | string, event: KeyEvent): boolean
2617
2618Dispatches a key event to the specified component. To ensure predictable behavior, the target component must be within the subtree of the dispatching component.
2619
2620**Atomic service API**: This API can be used in atomic services since API version 15.
2621
2622**System capability**: SystemCapability.ArkUI.ArkUI.Full
2623
2624| Name| Type                         | Mandatory| Description              |
2625| ------ | ----------------------------- | ---- | ------------------ |
2626| node  | number \| string | Yes  | ID or unique ID of the target component.|
2627| event  |[KeyEvent](./arkui-ts/ts-universal-events-key.md#keyevent) | Yes  | **KeyEvent** object.|
2628
2629**Example**
2630
2631```ts
2632@Entry
2633@Component
2634struct Index {
2635  build() {
2636    Row() {
2637      Row() {
2638        Button('Button1').id('Button1').onKeyEvent((event) => {
2639          console.log("Button1");
2640          return true
2641        })
2642        Button('Button2').id('Button2').onKeyEvent((event) => {
2643          console.log("Button2");
2644          return true
2645        })
2646      }
2647      .width('100%')
2648      .height('100%')
2649      .id('Row1')
2650      .onKeyEventDispatch((event) => {
2651        let context = this.getUIContext();
2652        context.getFocusController().requestFocus('Button1');
2653        return context.dispatchKeyEvent('Button1', event);
2654      })
2655
2656    }
2657    .height('100%')
2658    .width('100%')
2659    .onKeyEventDispatch((event) => {
2660      if (event.type == KeyType.Down) {
2661        let context = this.getUIContext();
2662        context.getFocusController().requestFocus('Row1');
2663        return context.dispatchKeyEvent('Row1', event);
2664      }
2665      return true;
2666    })
2667  }
2668}
2669```
2670## Font
2671
2672In the following API examples, you must first use [getFont()](#getfont) in **UIContext** to obtain a **Font** instance, and then call the APIs using the obtained instance.
2673
2674### registerFont
2675
2676registerFont(options: font.FontOptions): void
2677
2678Registers a custom font with the font manager.
2679
2680**Atomic service API**: This API can be used in atomic services since API version 11.
2681
2682**System capability**: SystemCapability.ArkUI.ArkUI.Full
2683
2684**Parameters**
2685
2686| Name    | Type                                      | Mandatory  | Description         |
2687| ------- | ---------------------------------------- | ---- | ----------- |
2688| options | [font.FontOptions](js-apis-font.md#fontoptions) | Yes   | Information about the custom font to register.|
2689
2690**Example**
2691
2692<!--code_no_check-->
2693```ts
2694import { Font } from '@kit.ArkUI';
2695
2696let font:Font = uiContext.getFont();
2697font.registerFont({
2698  familyName: 'medium',
2699  familySrc: '/font/medium.ttf'
2700});
2701```
2702### getSystemFontList
2703
2704getSystemFontList(): Array\<string>
2705
2706Obtains the list of supported fonts.
2707
2708**Atomic service API**: This API can be used in atomic services since API version 11.
2709
2710**System capability**: SystemCapability.ArkUI.ArkUI.Full
2711
2712**Return value**
2713
2714| Type            | Description       |
2715| -------------- | --------- |
2716| Array\<string> | List of supported fonts.|
2717
2718>  **NOTE**
2719>
2720>  This API takes effect only on 2-in-1 devices.
2721
2722**Example**
2723
2724<!--code_no_check-->
2725```ts
2726import { Font } from '@kit.ArkUI';
2727
2728let font:Font|undefined = uiContext.getFont();
2729if(font){
2730  font.getSystemFontList()
2731}
2732```
2733
2734### getFontByName
2735
2736getFontByName(fontName: string): font.FontInfo
2737
2738Obtains information about a system font based on the font name.
2739
2740**Atomic service API**: This API can be used in atomic services since API version 11.
2741
2742**System capability**: SystemCapability.ArkUI.ArkUI.Full
2743
2744**Parameters**
2745
2746| Name     | Type    | Mandatory  | Description     |
2747| -------- | ------ | ---- | ------- |
2748| fontName | string | Yes   | System font name.|
2749
2750**Return value**
2751
2752| Type                                     | Description          |
2753| ----------------------------------------- | -------------- |
2754| [font.FontInfo](js-apis-font.md#fontinfo) | Information about the system font.|
2755
2756**Example**
2757
2758<!--code_no_check-->
2759```ts
2760import { Font } from '@kit.ArkUI';
2761
2762let font:Font|undefined = uiContext.getFont();
2763if(font){
2764  font.getFontByName('Sans Italic')
2765}
2766```
2767
2768## Context<sup>12+</sup>
2769
2770type Context = common.Context
2771
2772Defines the context of the current ability.
2773
2774**Atomic service API**: This API can be used in atomic services since API version 12.
2775
2776**System capability**: SystemCapability.Ability.AbilityRuntime.Core
2777
2778**Model restriction**: This API can be used only in the stage model.
2779
2780| Type|Description  |
2781| ------ | ------------------- |
2782| [common.Context](../apis-ability-kit/js-apis-app-ability-common.md#context) |Context object associated with the current ability.|
2783
2784## ComponentUtils
2785
2786In the following API examples, you must first use [getComponentUtils()](#getcomponentutils) in **UIContext** to obtain a **ComponentUtils** instance, and then call the APIs using the obtained instance.
2787
2788### getRectangleById
2789
2790getRectangleById(id: string): componentUtils.ComponentInfo
2791
2792Obtains the size, position, translation, scaling, rotation, and affine matrix information of the specified component.
2793
2794**Atomic service API**: This API can be used in atomic services since API version 11.
2795
2796**System capability**: SystemCapability.ArkUI.ArkUI.Full
2797
2798**Parameters**
2799
2800| Name | Type    | Mandatory  | Description       |
2801| ---- | ------ | ---- | --------- |
2802| id   | string | Yes   | Unique component ID.|
2803
2804**Return value**
2805
2806| Type                                                        | Description                                            |
2807| ------------------------------------------------------------ | ------------------------------------------------ |
2808| [componentUtils.ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | Size, position, translation, scaling, rotation, and affine matrix information of the component.|
2809
2810**Error codes**
2811
2812For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
2813
2814| ID | Error Message               |
2815| ------ | ------------------- |
2816| 100001 | UI execution context not found. |
2817
2818**Example**
2819
2820<!--code_no_check-->
2821```ts
2822import { ComponentUtils } from '@kit.ArkUI';
2823
2824let componentUtils:ComponentUtils = uiContext.getComponentUtils();
2825let modePosition = componentUtils.getRectangleById("onClick");
2826let localOffsetWidth = modePosition.size.width;
2827let localOffsetHeight = modePosition.size.height;
2828```
2829
2830## UIInspector
2831
2832In the following API examples, you must first use [getUIInspector()](#getuiinspector) in **UIContext** to obtain a **UIInspector** instance, and then call the APIs using the obtained instance.
2833
2834### createComponentObserver
2835
2836createComponentObserver(id: string): inspector.ComponentObserver
2837
2838Registers a callback for layout and rendering completion notifications for a specific component.
2839
2840**Atomic service API**: This API can be used in atomic services since API version 11.
2841
2842**System capability**: SystemCapability.ArkUI.ArkUI.Full
2843
2844**Parameters**
2845
2846| Name | Type    | Mandatory  | Description     |
2847| ---- | ------ | ---- | ------- |
2848| id   | string | Yes   | ID of the target component, set using the universal attributes [id](./arkui-ts/ts-universal-attributes-component-id.md#id) or [key](./arkui-ts/ts-universal-attributes-component-id.md#key12).|
2849
2850**Return value**
2851
2852| Type                                                        | Description                                              |
2853| ------------------------------------------------------------ | -------------------------------------------------- |
2854| [inspector.ComponentObserver](js-apis-arkui-inspector.md#componentobserver) | Component observer, which is used to register or unregister listeners for completion of component layout or drawing.|
2855
2856**Example**
2857
2858<!--code_no_check-->
2859```ts
2860import { UIInspector } from '@kit.ArkUI';
2861
2862let inspector: UIInspector = uiContext.getUIInspector();
2863let listener = inspector.createComponentObserver('COMPONENT_ID');
2864```
2865
2866## PageInfo<sup>12+</sup>
2867Represents the page information of the router or navigation destination. If there is no related page information, **undefined** is returned.
2868
2869**Atomic service API**: This API can be used in atomic services since API version 12.
2870
2871**System capability**: SystemCapability.ArkUI.ArkUI.Full
2872
2873| Name| Type| Mandatory| Description|
2874| -------- | -------- | -------- | -------- |
2875| routerPageInfo | observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo) | No| Router information.|
2876| navDestinationInfo | observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo) | No| Navigation destination information.|
2877
2878## UIObserver<sup>11+</sup>
2879
2880In the following API examples, you must first use [getUIObserver()](#getuiobserver11) in **UIContext** to obtain a **UIObserver** instance, and then call the APIs using the obtained instance.
2881
2882### on('navDestinationUpdate')<sup>11+</sup>
2883
2884on(type: 'navDestinationUpdate', callback: Callback\<observer.NavDestinationInfo\>): void
2885
2886Subscribes to status changes of this **NavDestination** component.
2887
2888**Atomic service API**: This API can be used in atomic services since API version 12.
2889
2890**System capability**: SystemCapability.ArkUI.ArkUI.Full
2891
2892**Parameters**
2893
2894| Name  | Type                                                 | Mandatory| Description                                                        |
2895| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
2896| type     | string                                                | Yes  | Event type. The value is fixed at **'navDestinationUpdate'**, which indicates the state change event of the **NavDestination** component.|
2897| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | Yes  | Callback used to return the current state of the **NavDestination** component.                |
2898
2899**Example**
2900
2901<!--code_no_check-->
2902```ts
2903// Index.ets
2904// Example usage of uiObserver.on('navDestinationUpdate', callback)
2905// uiObserver.off('navDestinationUpdate', callback)
2906
2907@Component
2908struct PageOne {
2909  build() {
2910    NavDestination() {
2911      Text("pageOne")
2912    }.title("pageOne")
2913  }
2914}
2915
2916@Entry
2917@Component
2918struct Index {
2919  private stack: NavPathStack = new NavPathStack();
2920
2921  @Builder
2922  PageBuilder(name: string) {
2923    PageOne()
2924  }
2925
2926  aboutToAppear() {
2927    this.getUIContext().getUIObserver().on('navDestinationUpdate', (info) => {
2928      console.info('NavDestination state update', JSON.stringify(info));
2929    });
2930  }
2931
2932  aboutToDisappear() {
2933    this.getUIContext().getUIObserver().off('navDestinationUpdate');
2934  }
2935
2936  build() {
2937    Column() {
2938      Navigation(this.stack) {
2939        Button("push").onClick(() => {
2940          this.stack.pushPath({ name: "pageOne" });
2941        })
2942      }
2943      .title("Navigation")
2944      .navDestination(this.PageBuilder)
2945    }
2946    .width('100%')
2947    .height('100%')
2948  }
2949}
2950```
2951
2952### off('navDestinationUpdate')<sup>11+</sup>
2953
2954off(type: 'navDestinationUpdate', callback?: Callback\<observer.NavDestinationInfo\>): void
2955
2956Unsubscribes from state changes of this **NavDestination** component.
2957
2958**Atomic service API**: This API can be used in atomic services since API version 12.
2959
2960**System capability**: SystemCapability.ArkUI.ArkUI.Full
2961
2962**Parameters**
2963
2964| Name  | Type                                                 | Mandatory| Description                                                        |
2965| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
2966| type     | string                                                | Yes  | Event type. The value is fixed at **'navDestinationUpdate'**, which indicates the state change event of the **NavDestination** component.|
2967| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | No  | Callback used to return the current state of the **NavDestination** component.                |
2968
2969**Example**
2970
2971See the example for [uiObserver.on('navDestinationUpdate')](#onnavdestinationupdate11).
2972
2973### on('navDestinationUpdate')<sup>11+</sup>
2974
2975on(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback: Callback\<observer.NavDestinationInfo\>): void
2976
2977Subscribes to state changes of this **NavDestination** component.
2978
2979**Atomic service API**: This API can be used in atomic services since API version 12.
2980
2981**System capability**: SystemCapability.ArkUI.ArkUI.Full
2982
2983**Parameters**
2984
2985| Name  | Type                                                        | Mandatory| Description                                                        |
2986| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2987| type     | string                                                       | Yes  | Event type. The value is fixed at **'navDestinationUpdate'**, which indicates the state change event of the **NavDestination** component.|
2988| options  | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | Yes  | ID of the target **NavDestination** component.                                  |
2989| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\>        | Yes  | Callback used to return the current state of the **NavDestination** component.                |
2990
2991**Example**
2992
2993<!--code_no_check-->
2994```ts
2995// Index.ets
2996// Example usage of uiObserver.on('navDestinationUpdate', navigationId, callback)
2997// uiObserver.off('navDestinationUpdate', navigationId, callback)
2998@Component
2999struct PageOne {
3000  build() {
3001    NavDestination() {
3002      Text("pageOne")
3003    }.title("pageOne")
3004  }
3005}
3006
3007@Entry
3008@Component
3009struct Index {
3010  private stack: NavPathStack = new NavPathStack();
3011
3012  @Builder
3013  PageBuilder(name: string) {
3014    PageOne()
3015  }
3016
3017  aboutToAppear() {
3018    this.getUIContext().getUIObserver().on('navDestinationUpdate', { navigationId: "testId" }, (info) => {
3019      console.info('NavDestination state update', JSON.stringify(info));
3020    });
3021  }
3022
3023  aboutToDisappear() {
3024    this.getUIContext().getUIObserver().off('navDestinationUpdate', { navigationId: "testId" });
3025  }
3026
3027  build() {
3028    Column() {
3029      Navigation(this.stack) {
3030        Button("push").onClick(() => {
3031          this.stack.pushPath({ name: "pageOne" });
3032        })
3033      }
3034      .id("testId")
3035      .title("Navigation")
3036      .navDestination(this.PageBuilder)
3037    }
3038    .width('100%')
3039    .height('100%')
3040  }
3041}
3042```
3043
3044### off('navDestinationUpdate')<sup>11+</sup>
3045
3046off(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback?: Callback\<observer.NavDestinationInfo\>): void
3047
3048Unsubscribes from state changes of the **NavDestination** component.
3049
3050**Atomic service API**: This API can be used in atomic services since API version 12.
3051
3052**System capability**: SystemCapability.ArkUI.ArkUI.Full
3053
3054**Parameters**
3055
3056| Name  | Type                                                        | Mandatory| Description                                                        |
3057| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3058| type     | string                                                       | Yes  | Event type. The value is fixed at **'navDestinationUpdate'**, which indicates the state change event of the **NavDestination** component.|
3059| options  | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | Yes  | ID of the target **NavDestination** component.                                  |
3060| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\>        | No  | Callback used to return the current state of the **NavDestination** component.                |
3061
3062**Example**
3063
3064See the example for [uiObserver.on('navDestinationUpdate')](#onnavdestinationupdate11-1).
3065
3066### on('scrollEvent')<sup>12+</sup>
3067
3068on(type: 'scrollEvent', callback: Callback\<observer.ScrollEventInfo\>): void
3069
3070Subscribes to the start and end of a scroll event.
3071
3072**Atomic service API**: This API can be used in atomic services since API version 12.
3073
3074**System capability**: SystemCapability.ArkUI.ArkUI.Full
3075
3076**Parameters**
3077
3078| Name  | Type                                                 | Mandatory| Description                                                        |
3079| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
3080| type     | string                                                | Yes  | Event type. The value **'scrollEvent'** indicates the start and end of a scroll event.     |
3081| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\> | Yes  | Callback used to return the Callback used to return the information about the scroll event.  |
3082
3083**Example**
3084
3085See [offscrollevent Example](#offscrollevent12-1).
3086
3087### off('scrollEvent')<sup>12+</sup>
3088
3089off(type: 'scrollEvent', callback?: Callback\<observer.ScrollEventInfo\>): void
3090
3091Unsubscribes from the start and end of a scroll event.
3092
3093**Atomic service API**: This API can be used in atomic services since API version 12.
3094
3095**System capability**: SystemCapability.ArkUI.ArkUI.Full
3096
3097**Parameters**
3098
3099| Name  | Type                                                 | Mandatory| Description                                                        |
3100| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
3101| type     | string                                                | Yes  | Event type. The value **'scrollEvent'** indicates the start and end of a scroll event.     |
3102| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\> | No  | Callback used to return the Callback used to return the information about the scroll event.  |
3103
3104**Example**
3105
3106See [offscrollevent Example](#offscrollevent12-1).
3107
3108### on('scrollEvent')<sup>12+</sup>
3109
3110on(type: 'scrollEvent', options: observer.ObserverOptions, callback: Callback\<observer.ScrollEventInfo\>): void
3111
3112Subscribes to the start and end of a scroll event.
3113
3114**Atomic service API**: This API can be used in atomic services since API version 12.
3115
3116**System capability**: SystemCapability.ArkUI.ArkUI.Full
3117
3118**Parameters**
3119
3120| Name  | Type                                                        | Mandatory| Description                                                        |
3121| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3122| type     | string                                                       | Yes  | Event type. The value **'scrollEvent'** indicates the start and end of a scroll event.|
3123| options  | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | Yes  | Observer options, including the ID of the target scrollable component.                   |
3124| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\>        | Yes  | Callback used to return the Callback used to return the information about the scroll event.                |
3125
3126**Example**
3127
3128See [offscrollevent Example](#offscrollevent12-1).
3129
3130### off('scrollEvent')<sup>12+</sup>
3131
3132off(type: 'scrollEvent', options: observer.ObserverOptions, callback?: Callback\<observer.ScrollEventInfo\>): void
3133
3134Unsubscribes from the start and end of a scroll event.
3135
3136**Atomic service API**: This API can be used in atomic services since API version 12.
3137
3138**System capability**: SystemCapability.ArkUI.ArkUI.Full
3139
3140**Parameters**
3141
3142| Name  | Type                                                        | Mandatory| Description                                                        |
3143| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3144| type     | string                                                       | Yes  | Event type. The value **'scrollEvent'** indicates the start and end of a scroll event.|
3145| options  | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | Yes  | Observer options, including the ID of the target scrollable component.                   |
3146| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\>        | No  | Callback used to return the Callback used to return the information about the scroll event.                |
3147
3148**Example**
3149
3150```ts
3151import { UIObserver } from '@kit.ArkUI'
3152
3153@Entry
3154@Component
3155struct Index {
3156  scroller: Scroller = new Scroller()
3157  observer: UIObserver = new UIObserver()
3158  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7]
3159
3160  build() {
3161    Row() {
3162      Column() {
3163        Scroll(this.scroller) {
3164          Column() {
3165            ForEach(this.arr, (item: number) => {
3166              Text(item.toString())
3167                .width('90%')
3168                .height(150)
3169                .backgroundColor(0xFFFFFF)
3170                .borderRadius(15)
3171                .fontSize(16)
3172                .textAlign(TextAlign.Center)
3173                .margin({ top: 10 })
3174            }, (item: string) => item)
3175          }.width('100%')
3176        }
3177        .id("testId")
3178        .height('80%')
3179      }
3180      .width('100%')
3181
3182      Row() {
3183        Button('UIObserver on')
3184          .onClick(() => {
3185            this.observer.on('scrollEvent', (info) => {
3186              console.info('scrollEventInfo', JSON.stringify(info));
3187            });
3188          })
3189        Button('UIObserver off')
3190          .onClick(() => {
3191            this.observer.off('scrollEvent');
3192          })
3193      }
3194
3195      Row() {
3196        Button('UIObserverWithId on')
3197          .onClick(() => {
3198            this.observer.on('scrollEvent', { id:"testId" }, (info) => {
3199              console.info('scrollEventInfo', JSON.stringify(info));
3200            });
3201          })
3202        Button('UIObserverWithId off')
3203          .onClick(() => {
3204            this.observer.off('scrollEvent', { id:"testId" });
3205          })
3206      }
3207    }
3208    .height('100%')
3209  }
3210}
3211```
3212
3213### on('routerPageUpdate')<sup>11+</sup>
3214
3215on(type: 'routerPageUpdate', callback: Callback\<observer.RouterPageInfo\>): void
3216
3217Subscribes to state changes of the page in the router.
3218
3219**Atomic service API**: This API can be used in atomic services since API version 12.
3220
3221**System capability**: SystemCapability.ArkUI.ArkUI.Full
3222
3223**Parameters**
3224
3225| Name  | Type                                                        | Mandatory| Description                                                        |
3226| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3227| type     | string                                                       | Yes  | Event type. The value is fixed at **'routerPageUpdate'**, which indicates the state change event of the page in the router.|
3228| callback | Callback\<observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo)\>        | Yes  | Callback used to return the If **pageInfo** is passed, the current page state is returned.                |
3229
3230**Example**
3231
3232```ts
3233import { UIContext, UIObserver } from '@kit.ArkUI';
3234
3235let observer:UIObserver = this.getUIContext().getUIObserver();
3236observer.on('routerPageUpdate', (info) => {
3237    console.info('RouterPage state updated, called by ' + `${info.name}`);
3238});
3239```
3240
3241### off('routerPageUpdate')<sup>11+</sup>
3242
3243off(type: 'routerPageUpdate', callback?: Callback\<observer.RouterPageInfo\>): void
3244
3245Unsubscribes to state changes of the page in the router.
3246
3247**Atomic service API**: This API can be used in atomic services since API version 12.
3248
3249**System capability**: SystemCapability.ArkUI.ArkUI.Full
3250
3251**Parameters**
3252
3253| Name  | Type                                                        | Mandatory| Description                                                        |
3254| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3255| type     | string                                                       | Yes  | Event type. The value is fixed at **'routerPageUpdate'**, which indicates the state change event of the page in the router.|
3256| callback | Callback\<observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo)\>        | No  | Callback to be unregistered.                |
3257
3258**Example**
3259
3260```ts
3261import { UIContext, UIObserver } from '@kit.ArkUI';
3262
3263let observer:UIObserver = this.getUIContext().getUIObserver();
3264function callBackFunc(info:observer.RouterPageInfo) {};
3265// callBackFunc is defined and used before
3266observer.off('routerPageUpdate', callBackFunc);
3267```
3268
3269### on('densityUpdate')<sup>12+</sup>
3270
3271on(type: 'densityUpdate', callback: Callback\<observer.DensityInfo\>): void
3272
3273Subscribes to the pixel density changes of the screen.
3274
3275**Atomic service API**: This API can be used in atomic services since API version 12.
3276
3277**System capability**: SystemCapability.ArkUI.ArkUI.Full
3278
3279**Parameters**
3280
3281| Name  | Type                                                        | Mandatory| Description                                                        |
3282| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3283| type     | string                                                       | Yes  | Event type. The value **'densityUpdate'** indicates the pixel density changes of the screen.|
3284| callback | Callback\<observer.[DensityInfo](./js-apis-arkui-observer.md#densityinfo12)\>        | Yes  | Callback used to return the screen pixel density after the change.                |
3285
3286```ts
3287import { uiObserver } from '@kit.ArkUI';
3288
3289@Entry
3290@Component
3291struct Index {
3292  @State density: number = 0;
3293  @State message: string = 'No listener registered'
3294
3295  densityUpdateCallback = (info: uiObserver.DensityInfo) => {
3296    this.density = info.density;
3297    this.message = 'DPI after change:' + this.density.toString();
3298  }
3299
3300  build() {
3301    Column() {
3302      Text(this.message)
3303        .fontSize(24)
3304        .fontWeight(FontWeight.Bold)
3305      Button('Subscribe to Screen Pixel Density Changes')
3306        .onClick(() => {
3307          this.message = 'Listener registered'
3308          this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback);
3309        })
3310    }
3311  }
3312}
3313```
3314
3315### off('densityUpdate')<sup>12+</sup>
3316
3317off(type: 'densityUpdate', callback?: Callback\<observer.DensityInfo\>): void
3318
3319Unsubscribes from the pixel density changes of the screen.
3320
3321**Atomic service API**: This API can be used in atomic services since API version 12.
3322
3323**System capability**: SystemCapability.ArkUI.ArkUI.Full
3324
3325**Parameters**
3326
3327| Name  | Type                                                                | Mandatory| Description                                                                                        |
3328| -------- | -------------------------------------------------------------------- | ---- | -------------------------------------------------------------------------------------------- |
3329| type     | string                                                               | Yes  | Event type. The value **'densityUpdate'** indicates the pixel density changes of the screen.                                       |
3330| callback | Callback\<observer.[DensityInfo](./js-apis-arkui-observer.md#densityinfo12)\> | No  | Callback to be unregistered. If this parameter is not specified, this API unregisters all callbacks for the **densityUpdate** event under the current UI context.|
3331
3332```ts
3333import { uiObserver } from '@kit.ArkUI';
3334
3335@Entry
3336@Component
3337struct Index {
3338  @State density: number = 0;
3339  @State message: string = 'No listener registered'
3340
3341  densityUpdateCallback = (info: uiObserver.DensityInfo) => {
3342    this.density = info.density;
3343    this.message = 'DPI after change:' + this.density.toString();
3344  }
3345
3346  build() {
3347    Column() {
3348      Text(this.message)
3349        .fontSize(24)
3350        .fontWeight(FontWeight.Bold)
3351      Button('Subscribe to Screen Pixel Density Changes')
3352        .margin({ bottom: 10 })
3353        .onClick(() => {
3354          this.message = 'Listener registered'
3355          this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback);
3356        })
3357      Button('Unsubscribe from Screen Pixel Density Changes')
3358        .onClick(() => {
3359          this.message = 'Listener not registered'
3360          this.getUIContext().getUIObserver().off('densityUpdate', this.densityUpdateCallback);
3361        })
3362    }
3363  }
3364}
3365```
3366
3367### on('willDraw')<sup>12+</sup>
3368
3369on(type: 'willDraw', callback: Callback\<void\>): void
3370
3371Subscribes to the dispatch of drawing instructions in each frame.
3372
3373**Atomic service API**: This API can be used in atomic services since API version 12.
3374
3375**System capability**: SystemCapability.ArkUI.ArkUI.Full
3376
3377**Parameters**
3378
3379| Name  | Type                                                        | Mandatory| Description                                                        |
3380| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3381| type     | string                                                       | Yes  | Event event. The value **'willDraw'** indicates whether drawing is about to occur.|
3382| callback | Callback\<void\>        | Yes  | Callback used to return the result.                |
3383
3384```ts
3385import { uiObserver } from '@kit.ArkUI';
3386
3387@Entry
3388@Component
3389struct Index {
3390  willDrawCallback = () => {
3391    console.info("willDraw instruction dispatched.")
3392  }
3393  build() {
3394    Column() {
3395      Button('Subscribe to Drawing Instruction Dispatch')
3396        .onClick(() => {
3397          this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback);
3398        })
3399    }
3400  }
3401}
3402```
3403
3404### off('willDraw')<sup>12+</sup>
3405
3406off(type: 'willDraw', callback?: Callback\<void\>): void
3407
3408Unsubscribes from the dispatch of drawing instructions in each frame.
3409
3410**Atomic service API**: This API can be used in atomic services since API version 12.
3411
3412**System capability**: SystemCapability.ArkUI.ArkUI.Full
3413
3414**Parameters**
3415
3416| Name  | Type                                                        | Mandatory| Description                                                        |
3417| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3418| type     | string                                                       | Yes  | Event event. The value **'willDraw'** indicates whether drawing is about to occur.|
3419| callback | Callback\<void\>        | No  | Callback to be unregistered.                 |
3420
3421```ts
3422import { uiObserver } from '@kit.ArkUI';
3423
3424@Entry
3425@Component
3426struct Index {
3427  willDrawCallback = () => {
3428    console.info("willDraw instruction dispatched.")
3429  }
3430
3431  build() {
3432    Column() {
3433      Button('Subscribe to Drawing Instruction Dispatch')
3434        .margin({ bottom: 10 })
3435        .onClick(() => {
3436          this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback);
3437        })
3438      Button('Unsubscribe from Drawing Instruction Dispatch')
3439        .onClick(() => {
3440          this.getUIContext().getUIObserver().off('willDraw', this.willDrawCallback);
3441        })
3442    }
3443  }
3444}
3445```
3446
3447### on('didLayout')<sup>12+</sup>
3448
3449on(type: 'didLayout', callback: Callback\<void\>): void
3450
3451Subscribes to layout completion status in each frame.
3452
3453**Atomic service API**: This API can be used in atomic services since API version 12.
3454
3455**System capability**: SystemCapability.ArkUI.ArkUI.Full
3456
3457**Parameters**
3458
3459| Name  | Type                                                        | Mandatory| Description                                                        |
3460| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3461| type     | string                                                       | Yes  | Event type. The value **'didLayout'** indicates whether the layout has been completed.|
3462| callback | Callback\<void\>        | Yes  | Callback used to return the result.                |
3463
3464```ts
3465import { uiObserver } from '@kit.ArkUI';
3466
3467@Entry
3468@Component
3469struct Index {
3470  didLayoutCallback = () => {
3471    console.info("Layout completed.");
3472  }
3473  build() {
3474    Column() {
3475      Button('Subscribe to Layout Completion')
3476        .onClick(() => {
3477          this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback);
3478        })
3479    }
3480  }
3481}
3482```
3483
3484### off('didLayout')<sup>12+</sup>
3485
3486off(type: 'didLayout', callback?: Callback\<void\>): void
3487
3488Unsubscribes from layout completion status in each frame.
3489
3490**Atomic service API**: This API can be used in atomic services since API version 12.
3491
3492**System capability**: SystemCapability.ArkUI.ArkUI.Full
3493
3494**Parameters**
3495
3496| Name  | Type                                                        | Mandatory| Description                                                        |
3497| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3498| type     | string                                                       | Yes  | Event event. The value **'didLayout'** indicates whether the layout has been completed.|
3499| callback | Callback\<void\>        | No  | Callback to be unregistered.                 |
3500
3501```ts
3502import { uiObserver } from '@kit.ArkUI';
3503
3504@Entry
3505@Component
3506struct Index {
3507  didLayoutCallback = () => {
3508    console.info("Layout completed.")
3509  }
3510
3511  build() {
3512    Column() {
3513      Button('Subscribe to Layout Completion')
3514        .margin({ bottom: 10 })
3515        .onClick(() => {
3516          this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback);
3517        })
3518      Button('Unsubscribe from Layout Completion')
3519        .onClick(() => {
3520          this.getUIContext().getUIObserver().off('didLayout', this.didLayoutCallback);
3521        })
3522    }
3523  }
3524}
3525```
3526
3527### on('navDestinationSwitch')<sup>12+</sup>
3528
3529on(type: 'navDestinationSwitch', callback: Callback\<observer.NavDestinationSwitchInfo\>): void
3530
3531Subscribes to the page switching event of the **Navigation** component.
3532
3533**Atomic service API**: This API can be used in atomic services since API version 12.
3534
3535**System capability**: SystemCapability.ArkUI.ArkUI.Full
3536
3537**Parameters**
3538
3539| Name  | Type                                                        | Mandatory| Description                                                        |
3540| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3541| type     | string                                                       | Yes  | Event type. The value **'navDestinationSwitch'** indicates the page switching event of the **Navigation** component.|
3542| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\>        | Yes  | Callback used to return the information about the page switching event.                |
3543
3544**Example**
3545
3546```ts
3547// Index.ets
3548// UIObserver.on('navDestinationSwitch', callback) demo
3549// UIObserver.off('navDestinationSwitch', callback)
3550import { uiObserver } from '@kit.ArkUI';
3551
3552@Component
3553struct PageOne {
3554  build() {
3555    NavDestination() {
3556      Text("pageOne")
3557    }.title("pageOne")
3558  }
3559}
3560
3561function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) {
3562  console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`)
3563}
3564
3565@Entry
3566@Component
3567struct Index {
3568  private stack: NavPathStack = new NavPathStack();
3569
3570  @Builder
3571  PageBuilder(name: string) {
3572    PageOne()
3573  }
3574
3575  aboutToAppear() {
3576    let obs = this.getUIContext().getUIObserver();
3577    obs.on('navDestinationSwitch', callBackFunc);
3578  }
3579
3580  aboutToDisappear() {
3581    let obs = this.getUIContext().getUIObserver();
3582    obs.off('navDestinationSwitch', callBackFunc);
3583  }
3584
3585  build() {
3586    Column() {
3587      Navigation(this.stack) {
3588        Button("push").onClick(() => {
3589          this.stack.pushPath({name: "pageOne"});
3590        })
3591      }
3592      .title("Navigation")
3593      .navDestination(this.PageBuilder)
3594    }
3595    .width('100%')
3596    .height('100%')
3597  }
3598}
3599```
3600
3601### off('navDestinationSwitch')<sup>12+</sup>
3602
3603off(type: 'navDestinationSwitch', callback?: Callback\<observer.NavDestinationSwitchInfo\>): void
3604
3605Unsubscribes from the page switching event of the **Navigation** component.
3606
3607**Atomic service API**: This API can be used in atomic services since API version 12.
3608
3609**System capability**: SystemCapability.ArkUI.ArkUI.Full
3610
3611**Parameters**
3612
3613| Name  | Type                                                        | Mandatory| Description                                                        |
3614| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3615| type     | string                                                       | Yes  | Event type. The value **'navDestinationSwitch'** indicates the page switching event of the **Navigation** component.|
3616| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\>        | No  | Callback to be unregistered.                |
3617
3618For the sample code, see the sample code of the **UIObserver.on('navDestinationSwitch')** API.
3619
3620### on('navDestinationSwitch')<sup>12+</sup>
3621
3622on(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback: Callback\<observer.NavDestinationSwitchInfo\>): void
3623
3624Subscribes to the page switching event of the **Navigation** component.
3625
3626**Atomic service API**: This API can be used in atomic services since API version 12.
3627
3628**System capability**: SystemCapability.ArkUI.ArkUI.Full
3629
3630**Parameters**
3631
3632| Name  | Type                                                        | Mandatory| Description                                                        |
3633| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3634| type     | string                                                       | Yes  | Event type. The value **'navDestinationSwitch'** indicates the page switching event of the **Navigation** component.|
3635| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12)        | Yes  | Observer options.  |
3636| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\>        | Yes  | Callback used to return the information about the page switching event.                |
3637
3638**Example**
3639
3640```ts
3641// Index.ets
3642// Demo UIObserver.on('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback)
3643// UIObserver.off('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback)
3644import { uiObserver } from '@kit.ArkUI';
3645
3646@Component
3647struct PageOne {
3648  build() {
3649    NavDestination() {
3650      Text("pageOne")
3651    }.title("pageOne")
3652  }
3653}
3654
3655function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) {
3656  console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`)
3657}
3658
3659@Entry
3660@Component
3661struct Index {
3662  private stack: NavPathStack = new NavPathStack();
3663
3664  @Builder
3665  PageBuilder(name: string) {
3666    PageOne()
3667  }
3668
3669  aboutToAppear() {
3670    let obs = this.getUIContext().getUIObserver();
3671    obs.on('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc)
3672  }
3673
3674  aboutToDisappear() {
3675    let obs = this.getUIContext().getUIObserver();
3676    obs.off('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc)
3677  }
3678
3679  build() {
3680    Column() {
3681      Navigation(this.stack) {
3682        Button("push").onClick(() => {
3683          this.stack.pushPath({name: "pageOne"});
3684        })
3685      }
3686      .id("myNavId")
3687      .title("Navigation")
3688      .navDestination(this.PageBuilder)
3689    }
3690    .width('100%')
3691    .height('100%')
3692  }
3693}
3694```
3695
3696### off('navDestinationSwitch')<sup>12+</sup>
3697
3698off(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback?: Callback\<observer.NavDestinationSwitchInfo\>): void
3699
3700Unsubscribes from the page switching event of the **Navigation** component.
3701
3702**Atomic service API**: This API can be used in atomic services since API version 12.
3703
3704**System capability**: SystemCapability.ArkUI.ArkUI.Full
3705
3706**Parameters**
3707
3708| Name  | Type                                                        | Mandatory| Description                                                        |
3709| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3710| type     | string                                                       | Yes  | Event type. The value **'navDestinationSwitch'** indicates the page switching event of the **Navigation** component.|
3711| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12)        | Yes  | Observer options.  |
3712| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\>        | No  | Callback to be unregistered.                |
3713
3714For the sample code, see the sample code of the **UIObserver.on('navDestinationSwitch')** API.
3715
3716### on('willClick')<sup>12+</sup>
3717
3718on(type: 'willClick', callback: GestureEventListenerCallback): void
3719
3720Subscribes to the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3721
3722**Atomic service API**: This API can be used in atomic services since API version 12.
3723
3724**System capability**: SystemCapability.ArkUI.ArkUI.Full
3725
3726**Parameters**
3727
3728| Name  | Type                                                        | Mandatory| Description                                                        |
3729| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3730| type     | string                                                       | Yes  | Event type. The value **'willClick'** indicates the dispatch of click event instructions. The registered callback is triggered when the click event is about to occur.|
3731| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | Yes  | Callback used to return the **GestureEvent** object of the click event and the FrameNode of the component. |
3732
3733**Example**
3734
3735```ts
3736// Used in page components.
3737import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3738
3739// callback is a callback defined by you.
3740let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
3741let observer: UIObserver = this.getUIContext().getUIObserver();
3742observer.on('willClick', callback);
3743```
3744
3745### off('willClick')<sup>12+</sup>
3746
3747off(type: 'willClick', callback?: GestureEventListenerCallback): void
3748
3749Unsubscribes from the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3750
3751**Atomic service API**: This API can be used in atomic services since API version 12.
3752
3753**System capability**: SystemCapability.ArkUI.ArkUI.Full
3754
3755**Parameters**
3756
3757| Name  | Type                                                        | Mandatory| Description                                                 |
3758| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
3759| type     | string                                                       | Yes  | Event type. The value **'willClick'** indicates the dispatch of click event instructions.|
3760| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | No  | Callback to be unregistered.                               |
3761
3762**Example**
3763
3764```ts
3765// Used in page components.
3766import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3767
3768// callback is a callback defined by you.
3769let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
3770let observer: UIObserver = this.getUIContext().getUIObserver();
3771observer.off('willClick', callback);
3772```
3773
3774### on('didClick')<sup>12+</sup>
3775
3776on(type: 'didClick', callback: GestureEventListenerCallback): void
3777
3778Subscribes to the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3779
3780**Atomic service API**: This API can be used in atomic services since API version 12.
3781
3782**System capability**: SystemCapability.ArkUI.ArkUI.Full
3783
3784**Parameters**
3785
3786| Name  | Type                                                        | Mandatory| Description                                                        |
3787| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3788| type     | string                                                       | Yes  | Event type. The value **'didClick'** indicates the dispatch of click event instructions. The registered callback is triggered after the click event is about to occur.|
3789| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | Yes  | Callback used to return the **GestureEvent** object of the click event and the FrameNode of the component. |
3790
3791**Example**
3792
3793```ts
3794// Used in page components.
3795import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3796
3797// callback is a callback defined by you.
3798let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
3799let observer: UIObserver = this.getUIContext().getUIObserver();
3800observer.on('didClick', callback);
3801```
3802
3803### off('didClick')<sup>12+</sup>
3804
3805off(type: 'didClick', callback?: GestureEventListenerCallback): void
3806
3807Unsubscribes from the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3808
3809**Atomic service API**: This API can be used in atomic services since API version 12.
3810
3811**System capability**: SystemCapability.ArkUI.ArkUI.Full
3812
3813**Parameters**
3814
3815| Name  | Type                                                        | Mandatory| Description                                                |
3816| -------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------- |
3817| type     | string                                                       | Yes  | Event type. The value **'didClick'** indicates the dispatch of click event instructions.|
3818| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | No  | Callback to be unregistered.                              |
3819
3820**Example**
3821
3822```ts
3823// Used in page components.
3824import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3825
3826// callback is a callback defined by you.
3827let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
3828let observer: UIObserver = this.getUIContext().getUIObserver();
3829observer.off('didClick', callback);
3830```
3831
3832### on('willClick')<sup>12+</sup>
3833
3834on(type: 'willClick', callback: ClickEventListenerCallback): void
3835
3836Subscribes to the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3837
3838**Atomic service API**: This API can be used in atomic services since API version 12.
3839
3840**System capability**: SystemCapability.ArkUI.ArkUI.Full
3841
3842**Parameters**
3843
3844| Name  | Type                                                       | Mandatory| Description                                                        |
3845| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
3846| type     | string                                                      | Yes  | Event type. The value **'willClick'** indicates the dispatch of click event instructions. The registered callback is triggered when the click event is about to occur.|
3847| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | Yes  | Callback used to return the **ClickEvent** object and the FrameNode of the component.   |
3848
3849**Example**
3850
3851```ts
3852// Used in page components.
3853import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3854
3855// callback is a callback defined by you.
3856let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
3857let observer: UIObserver = this.getUIContext().getUIObserver();
3858observer.on('willClick', callback);
3859```
3860
3861### off('willClick')<sup>12+</sup>
3862
3863off(type: 'willClick', callback?: ClickEventListenerCallback): void
3864
3865Unsubscribes from the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3866
3867**Atomic service API**: This API can be used in atomic services since API version 12.
3868
3869**System capability**: SystemCapability.ArkUI.ArkUI.Full
3870
3871**Parameters**
3872
3873| Name  | Type                                                       | Mandatory| Description                                                 |
3874| -------- | ----------------------------------------------------------- | ---- | ----------------------------------------------------- |
3875| type     | string                                                      | Yes  | Event type. The value **'willClick'** indicates the dispatch of click event instructions.|
3876| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | No  | Callback to be unregistered.                               |
3877
3878**Example**
3879
3880```ts
3881// Used in page components.
3882import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3883
3884// callback is a callback defined by you.
3885let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
3886let observer: UIObserver = this.getUIContext().getUIObserver();
3887observer.off('willClick', callback);
3888```
3889
3890### on('didClick')<sup>12+</sup>
3891
3892on(type: 'didClick', callback: ClickEventListenerCallback): void
3893
3894Subscribes to the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3895
3896**Atomic service API**: This API can be used in atomic services since API version 12.
3897
3898**System capability**: SystemCapability.ArkUI.ArkUI.Full
3899
3900**Parameters**
3901
3902| Name  | Type                                                       | Mandatory| Description                                                        |
3903| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
3904| type     | string                                                      | Yes  | Event type. The value **'didClick'** indicates the dispatch of click event instructions. The registered callback is triggered after the click event is about to occur.|
3905| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | Yes  | Callback used to return the **ClickEvent** object and the FrameNode of the component.   |
3906
3907**Example**
3908
3909```ts
3910// Used in page components.
3911import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3912
3913// callback is a callback defined by you.
3914let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
3915let observer: UIObserver = this.getUIContext().getUIObserver();
3916observer.on('didClick', callback);
3917```
3918
3919### off('didClick')<sup>12+</sup>
3920
3921off(type: 'didClick', callback?: ClickEventListenerCallback): void
3922
3923Unsubscribes from the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3924
3925**Atomic service API**: This API can be used in atomic services since API version 12.
3926
3927**System capability**: SystemCapability.ArkUI.ArkUI.Full
3928
3929**Parameters**
3930
3931| Name  | Type                                                       | Mandatory| Description                                                |
3932| -------- | ----------------------------------------------------------- | ---- | ---------------------------------------------------- |
3933| type     | string                                                      | Yes  | Event type. The value **'didClick'** indicates the dispatch of click event instructions.|
3934| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | No  | Callback to be unregistered.                              |
3935
3936**Example**
3937
3938```ts
3939// Used in page components.
3940import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3941
3942// callback is a callback defined by you.
3943let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
3944let observer: UIObserver = this.getUIContext().getUIObserver();
3945observer.off('didClick', callback);
3946```
3947
3948### on('tabContentUpdate')<sup>12+</sup>
3949
3950on(type: 'tabContentUpdate', callback: Callback\<observer.TabContentInfo\>): void
3951
3952Subscribes to the **TabContent** switching event.
3953
3954**Atomic service API**: This API can be used in atomic services since API version 12.
3955
3956**System capability**: SystemCapability.ArkUI.ArkUI.Full
3957
3958**Parameters**
3959
3960| Name  | Type                                                        | Mandatory| Description                                                        |
3961| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3962| type     | string                                                       | Yes  | Event type. The value **'tabContentUpdate'** indicates the **TabContent** switching event.|
3963| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | Yes  | Callback used to return the information about the **TabContent** switching event.|
3964
3965**Example**
3966
3967```ts
3968import { uiObserver } from '@kit.ArkUI';
3969
3970function callbackFunc(info: uiObserver.TabContentInfo) {
3971  console.info('tabContentUpdate', JSON.stringify(info));
3972}
3973
3974@Entry
3975@Component
3976struct TabsExample {
3977
3978  aboutToAppear(): void {
3979    let observer = this.getUIContext().getUIObserver();
3980    observer.on('tabContentUpdate', callbackFunc);
3981  }
3982
3983  aboutToDisappear(): void {
3984    let observer = this.getUIContext().getUIObserver();
3985    observer.off('tabContentUpdate', callbackFunc);
3986  }
3987
3988  build() {
3989    Column() {
3990      Tabs() {
3991        TabContent() {
3992          Column().width('100%').height('100%').backgroundColor('#00CB87')
3993        }.tabBar('green').id('tabContentId0')
3994
3995        TabContent() {
3996          Column().width('100%').height('100%').backgroundColor('#007DFF')
3997        }.tabBar('blue').id('tabContentId1')
3998
3999        TabContent() {
4000          Column().width('100%').height('100%').backgroundColor('#FFBF00')
4001        }.tabBar('yellow').id('tabContentId2')
4002
4003        TabContent() {
4004          Column().width('100%').height('100%').backgroundColor('#E67C92')
4005        }.tabBar('pink').id('tabContentId3')
4006      }
4007      .width(360)
4008      .height(296)
4009      .backgroundColor('#F1F3F5')
4010      .id('tabsId')
4011    }.width('100%')
4012  }
4013}
4014```
4015
4016### off('tabContentUpdate')<sup>12+</sup>
4017
4018off(type: 'tabContentUpdate', callback?: Callback\<observer.TabContentInfo\>): void
4019
4020Unsubscribes from the **TabContent** switching event.
4021
4022**Atomic service API**: This API can be used in atomic services since API version 12.
4023
4024**System capability**: SystemCapability.ArkUI.ArkUI.Full
4025
4026**Parameters**
4027
4028| Name  | Type                                                        | Mandatory| Description                                                        |
4029| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
4030| type     | string                                                       | Yes  | Event type. The value **'tabContentUpdate'** indicates the **TabContent** switching event.|
4031| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | No  | Callback to be unregistered.|
4032
4033**Example**
4034
4035See the example of [on('tabContentUpdate')](#ontabcontentupdate12).
4036
4037### on('tabContentUpdate')<sup>12+</sup>
4038
4039on(type: 'tabContentUpdate', options: observer.ObserverOptions, callback: Callback\<observer.TabContentInfo\>): void
4040
4041Subscribes to the **TabContent** switching event.
4042
4043**Atomic service API**: This API can be used in atomic services since API version 12.
4044
4045**System capability**: SystemCapability.ArkUI.ArkUI.Full
4046
4047**Parameters**
4048
4049| Name  | Type                                                        | Mandatory| Description                                                        |
4050| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
4051| type     | string                                                       | Yes  | Event type. The value **'tabContentUpdate'** indicates the **TabContent** switching event.|
4052| options  | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | Yes  | ID of the target **Tabs** component.|
4053| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | Yes  | Callback used to return the information about the **TabContent** switching event.|
4054
4055**Example**
4056
4057```ts
4058import { uiObserver } from '@kit.ArkUI';
4059
4060function callbackFunc(info: uiObserver.TabContentInfo) {
4061  console.info('tabContentUpdate', JSON.stringify(info));
4062}
4063
4064@Entry
4065@Component
4066struct TabsExample {
4067
4068  aboutToAppear(): void {
4069    let observer = this.getUIContext().getUIObserver();
4070    observer.on('tabContentUpdate', { id: 'tabsId' }, callbackFunc);
4071  }
4072
4073  aboutToDisappear(): void {
4074    let observer = this.getUIContext().getUIObserver();
4075    observer.off('tabContentUpdate', { id: 'tabsId' }, callbackFunc);
4076  }
4077
4078  build() {
4079    Column() {
4080      Tabs() {
4081        TabContent() {
4082          Column().width('100%').height('100%').backgroundColor('#00CB87')
4083        }.tabBar('green').id('tabContentId0')
4084
4085        TabContent() {
4086          Column().width('100%').height('100%').backgroundColor('#007DFF')
4087        }.tabBar('blue').id('tabContentId1')
4088
4089        TabContent() {
4090          Column().width('100%').height('100%').backgroundColor('#FFBF00')
4091        }.tabBar('yellow').id('tabContentId2')
4092
4093        TabContent() {
4094          Column().width('100%').height('100%').backgroundColor('#E67C92')
4095        }.tabBar('pink').id('tabContentId3')
4096      }
4097      .width(360)
4098      .height(296)
4099      .backgroundColor('#F1F3F5')
4100      .id('tabsId')
4101    }.width('100%')
4102  }
4103}
4104```
4105
4106### off('tabContentUpdate')<sup>12+</sup>
4107
4108off(type: 'tabContentUpdate', options: observer.ObserverOptions, callback?: Callback\<observer.TabContentInfo\>): void
4109
4110Unsubscribes from the **TabContent** switching event.
4111
4112**Atomic service API**: This API can be used in atomic services since API version 12.
4113
4114**System capability**: SystemCapability.ArkUI.ArkUI.Full
4115
4116**Parameters**
4117
4118| Name  | Type                                                        | Mandatory| Description                                                        |
4119| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
4120| type     | string                                                       | Yes  | Event type. The value **'tabContentUpdate'** indicates the **TabContent** switching event.|
4121| options  | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | Yes  | ID of the target **Tabs** component.|
4122| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | No  | Callback to be unregistered.|
4123
4124**Example**
4125
4126See the example of [on('tabContentUpdate')](#ontabcontentupdate12-1).
4127
4128### on('beforePanStart')<sup>18+</sup>
4129
4130on(type: 'beforePanStart', callback: PanListenerCallback): void
4131
4132Subscribes to the [onActionStart](arkui-ts/ts-basic-gestures-pangesture.md#events) event for the pan gesture, executing the callback before the **onActionStart** event is triggered. It works for finger swiping, mouse dragging, mouse wheel scrolling, and touchpad movements, but not for screen reader touch mode.
4133
4134**Atomic service API**: This API can be used in atomic services since API version 18.
4135
4136**System capability**: SystemCapability.ArkUI.ArkUI.Full
4137
4138**Parameters**
4139
4140| Name  | Type                                                       | Mandatory| Description                                                        |
4141| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
4142| type     | string                                                      | Yes  | Event type. The value is fixed at **'beforePanStart'**, which triggers the callback before the **onActionStart** event of the pan gesture.|
4143| callback | [PanListenerCallback](#panlistenercallback18) | Yes  | Callback used to return the **GestureEvent** and **GestureRecognizer** of the pan gesture event and the FrameNode of the component.  |
4144
4145**Example**
4146
4147```ts
4148// Used in page components.
4149import { uiObserver } from '@kit.ArkUI';
4150import router from '@ohos.router';
4151
4152let TEST_TAG: string = 'node'
4153
4154function callbackFunc() {
4155  console.info('on == beforePanStart');
4156}
4157
4158function afterPanCallBack() {
4159  console.info('on == afterPanStart')
4160}
4161
4162function beforeEndCallBack() {
4163  console.info('on == beforeEnd')
4164}
4165
4166function afterEndCallBack() {
4167  console.info('on == afterEnd')
4168}
4169
4170function beforeStartCallBack() {
4171  console.info('bxq on == beforeStartCallBack')
4172}
4173
4174function panGestureCallBack(event: GestureEvent, current: GestureRecognizer, node?: FrameNode) {
4175  TEST_TAG = 'panGestureEvent';
4176  console.info('===' + TEST_TAG + '=== event.repeat is ' + event.repeat);
4177  console.info('===' + TEST_TAG + '=== event target is ' + event.target.id);
4178  TEST_TAG = 'panGestureCurrent';
4179  console.info('===' + TEST_TAG + '=== current.getTag() is ' + current.getTag());
4180  TEST_TAG = 'panGestureNode';
4181  console.info('===' + TEST_TAG + '=== node?.getId() is ' + node?.getId());
4182}
4183
4184
4185@Entry
4186@Component
4187struct PanExample {
4188  @State offsetX: number = 0
4189  @State offsetY: number = 0
4190  @State positionX: number = 0
4191  @State positionY: number = 0
4192  private panOption: PanGestureOptions = new PanGestureOptions({direction: PanDirection.All })
4193
4194  aboutToAppear(): void {
4195    let observer = this.getUIContext().getUIObserver();
4196    observer.on('beforePanStart', callbackFunc);
4197    observer.on('beforePanStart', panGestureCallBack);
4198    observer.on('beforePanStart', beforeStartCallBack);
4199    observer.on('afterPanStart', afterPanCallBack);
4200    observer.on('beforePanEnd', beforeEndCallBack);
4201    observer.on('afterPanEnd', afterEndCallBack)
4202  }
4203
4204  aboutToDisappear(): void {
4205    let observer = this.getUIContext().getUIObserver();
4206    observer.off('beforePanStart', callbackFunc);
4207    observer.off('beforePanStart');
4208    observer.off('afterPanStart', afterPanCallBack);
4209    observer.off('beforePanEnd');
4210    observer.off('afterPanEnd');
4211  }
4212  build() {
4213    Column(){
4214      Column(){
4215        Text('PanGesture :\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY)
4216      }
4217      .height(200)
4218      .width(300)
4219      .padding(20)
4220      .border({ width: 3 })
4221      .margin(50)
4222      .translate({ x: this.offsetX, y: this.offsetY, z: 0 })
4223      .id('columnOuter')
4224      .gesture(
4225        PanGesture(this.panOption)
4226          .onActionStart((event: GestureEvent) => {
4227            console.info('Pan start')
4228          })
4229          .onActionUpdate((event: GestureEvent) => {
4230            if (event) {
4231              this.offsetX = this.positionX + event.offsetX
4232              this.offsetY = this.positionY + event.offsetY
4233            }
4234          })
4235          .onActionEnd((event: GestureEvent) => {
4236            this.positionX = this.offsetX
4237            this.positionY = this.offsetY
4238            console.info('Pan end')
4239            }))
4240          }
4241  }
4242}
4243```
4244
4245### off('beforePanStart')<sup>18+</sup>
4246
4247off(type: 'beforePanStart', callback?: PanListenerCallback): void
4248
4249Unsubscribes from the [onActionStart](arkui-ts/ts-basic-gestures-pangesture.md#events) for the pan gesture. This cancels the callback that is set to be executed before the **onActionStart** event of the pan gesture.
4250
4251**Atomic service API**: This API can be used in atomic services since API version 18.
4252
4253**System capability**: SystemCapability.ArkUI.ArkUI.Full
4254
4255**Parameters**
4256
4257| Name  | Type                                                       | Mandatory| Description                                                |
4258| -------- | ----------------------------------------------------------- | ---- | ---------------------------------------------------- |
4259| type     | string                                                      | Yes  | Event type. The value is fixed at **'beforePanStart'**.|
4260| callback | [PanListenerCallback](#panlistenercallback18) | No  | Callback to be unregistered.                              |
4261
4262**Example**
4263
4264```ts
4265// Used in page components.
4266import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
4267
4268// callback is a callback defined by you.
4269let callback = (event: GestureEvent, current: GestureRecognizer, node?: FrameNode) => {};
4270let observer: UIObserver = this.getUIContext().getUIObserver();
4271observer.off('beforePanStart', callback);
4272```
4273
4274### on('afterPanStart')<sup>18+</sup>
4275
4276on(type: 'afterPanStart', callback: PanListenerCallback): void
4277
4278Subscribes to the [onActionStart](arkui-ts/ts-basic-gestures-pangesture.md#events) event for the pan gesture, executing the callback after the **afterPanStart** event is triggered. It works for finger swiping, mouse dragging, mouse wheel scrolling, and touchpad movements, but not for screen reader touch mode.
4279
4280**Atomic service API**: This API can be used in atomic services since API version 18.
4281
4282**System capability**: SystemCapability.ArkUI.ArkUI.Full
4283
4284**Parameters**
4285
4286| Name  | Type                                                       | Mandatory| Description                                                        |
4287| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
4288| type     | string                                                      | Yes  | Event type. The value is fixed at **'afterPanStart'**, which triggers the callback after the **onActionStart** event of the pan gesture.|
4289| callback | [PanListenerCallback](#panlistenercallback18) | Yes  | Callback used to return the **GestureEvent** and **GestureRecognizer** of the pan gesture event and the FrameNode of the component.  |
4290
4291**Example**
4292
4293See the example for [on('beforePanStart')](#onbeforepanstart18).
4294
4295### off('afterPanStart')<sup>18+</sup>
4296
4297off(type: 'afterPanStart', callback?: PanListenerCallback): void
4298
4299Unsubscribes from the [onActionStart](arkui-ts/ts-basic-gestures-pangesture.md#events) for the pan gesture. This cancels the callback that is set to be executed after the **onActionStart** event of the pan gesture.
4300
4301**Atomic service API**: This API can be used in atomic services since API version 18.
4302
4303**System capability**: SystemCapability.ArkUI.ArkUI.Full
4304
4305**Parameters**
4306
4307| Name  | Type                                                       | Mandatory| Description                                                |
4308| -------- | ----------------------------------------------------------- | ---- | ---------------------------------------------------- |
4309| type     | string                                                      | Yes  | Event type. The value is fixed at **'afterPanStart'**.|
4310| callback | [PanListenerCallback](#panlistenercallback18) | No  | Callback to be unregistered.                              |
4311
4312**Example**
4313
4314See the example for [on('beforePanStart')](#onbeforepanstart18).
4315
4316### on('beforePanEnd')<sup>18+</sup>
4317
4318on(type: 'beforePanEnd', callback: PanListenerCallback): void
4319
4320Subscribes to the [onActionEnd](arkui-ts/ts-basic-gestures-pangesture.md#events) event for the pan gesture, executing the callback before the **onActionEnd** event is triggered. It works for finger swiping, mouse dragging, mouse wheel scrolling, and touchpad movements, but not for screen reader touch mode.
4321
4322**Atomic service API**: This API can be used in atomic services since API version 18.
4323
4324**System capability**: SystemCapability.ArkUI.ArkUI.Full
4325
4326**Parameters**
4327
4328| Name  | Type                                                       | Mandatory| Description                                                        |
4329| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
4330| type     | string                                                      | Yes  | Event type. The value is fixed at **'beforePanEnd'**, which triggers the callback before the **onActionEnd** event of the pan gesture.|
4331| callback | [PanListenerCallback](#panlistenercallback18) | Yes  | Callback used to return the **GestureEvent** and **GestureRecognizer** of the pan gesture event and the FrameNode of the component.  |
4332
4333**Example**
4334
4335See the example for [on('beforePanStart')](#onbeforepanstart18).
4336
4337### off('beforePanEnd')<sup>18+</sup>
4338
4339off(type: 'beforePanEnd', callback?: PanListenerCallback): void
4340
4341Unsubscribes from the [onActionEnd](arkui-ts/ts-basic-gestures-pangesture.md#events) for the pan gesture. This cancels the callback that is set to be executed before the **onActionEnd** event of the pan gesture.
4342
4343**Atomic service API**: This API can be used in atomic services since API version 18.
4344
4345**System capability**: SystemCapability.ArkUI.ArkUI.Full
4346
4347**Parameters**
4348
4349| Name  | Type                                                       | Mandatory| Description                                                |
4350| -------- | ----------------------------------------------------------- | ---- | ---------------------------------------------------- |
4351| type     | string                                                      | Yes  | Event type. The value is fixed at **'beforePanEnd'**.|
4352| callback | [PanListenerCallback](#panlistenercallback18) | No  | Callback to be unregistered.                              |
4353
4354**Example**
4355
4356See the example for [on('beforePanStart')](#onbeforepanstart18).
4357
4358### on('afterPanEnd')<sup>18+</sup>
4359
4360on(type: 'afterPanEnd', callback: PanListenerCallback): void
4361
4362Subscribes to the [onActionEnd](arkui-ts/ts-basic-gestures-pangesture.md#events) event for the pan gesture, executing the callback after the **onActionEnd** event is triggered. It works for finger swiping, mouse dragging, mouse wheel scrolling, and touchpad movements, but not for screen reader touch mode.
4363
4364**Atomic service API**: This API can be used in atomic services since API version 18.
4365
4366**System capability**: SystemCapability.ArkUI.ArkUI.Full
4367
4368**Parameters**
4369
4370| Name  | Type                                                       | Mandatory| Description                                                        |
4371| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
4372| type     | string                                                      | Yes  | Event type. The value is fixed at **'beforePanEnd'**, which triggers the callback after the **onActionEnd** event of the pan gesture.|
4373| callback | [PanListenerCallback](#panlistenercallback18) | Yes  | Callback used to return the **GestureEvent** and **GestureRecognizer** of the pan gesture event and the FrameNode of the component.  |
4374
4375**Example**
4376
4377See the example for [on('beforePanStart')](#onbeforepanstart18).
4378
4379### off('afterPanEnd')<sup>18+</sup>
4380
4381off(type: 'afterPanEnd', callback?: PanListenerCallback): void
4382
4383Unsubscribes from the [onActionEnd](arkui-ts/ts-basic-gestures-pangesture.md#events) for the pan gesture. This cancels the callback that is set to be executed after the **onActionEnd** event of the pan gesture.
4384
4385**Atomic service API**: This API can be used in atomic services since API version 18.
4386
4387**System capability**: SystemCapability.ArkUI.ArkUI.Full
4388
4389**Parameters**
4390
4391| Name  | Type                                                       | Mandatory| Description                                                |
4392| -------- | ----------------------------------------------------------- | ---- | ---------------------------------------------------- |
4393| type     | string                                                      | Yes  | Event type. The value is fixed at **'afterPanEnd'**.|
4394| callback | [PanListenerCallback](#panlistenercallback18) | No  | Callback to be unregistered.                              |
4395
4396**Example**
4397
4398See the example for [on('beforePanStart')](#onbeforepanstart18).
4399
4400
4401## PanListenerCallback<sup>18+</sup>
4402type PanListenerCallback = (event: GestureEvent, current: GestureRecognizer, node?: FrameNode) => void
4403
4404Defines a callback for pan gesture events.
4405
4406**Atomic service API**: This API can be used in atomic services since API version 18.
4407
4408**System capability**: SystemCapability.ArkUI.ArkUI.Full
4409
4410**Parameters**
4411
4412| Name | Type             | Mandatory| Description                               |
4413| ------- | ----------------- | ---- | --------------------------------- |
4414| event   | [GestureEvent](../apis-arkui/arkui-ts/ts-gesture-settings.md#gestureevent)     | Yes  | Information about the gesture event that triggers the callback.  |
4415| current | [GestureRecognizer](arkui-ts/ts-gesture-blocking-enhancement.md#gesturerecognizer) | Yes  | Information about the gesture recognizer that detects the event. |
4416| node    | [FrameNode](js-apis-arkui-frameNode.md#framenode)         | No  | Component bound to the gesture event.|
4417
4418## GestureEventListenerCallback<sup>12+</sup>
4419type GestureEventListenerCallback = (event: GestureEvent, node?: FrameNode) => void
4420
4421Defines a callback for gesture events in ArkTS.
4422
4423**Atomic service API**: This API can be used in atomic services since API version 12.
4424
4425**System capability**: SystemCapability.ArkUI.ArkUI.Full
4426
4427**Parameters**
4428
4429| Name | Type  | Mandatory| Description                         |
4430| ------- | ------ | ---- | --------------------------- |
4431| event | [GestureEvent](../apis-arkui/arkui-ts/ts-gesture-settings.md#gestureevent)| Yes| Information about the gesture event that triggers the callback.|
4432| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | No| Component bound to the gesture event.|
4433
4434## ClickEventListenerCallback<sup>12+</sup>
4435type ClickEventListenerCallback = (event: ClickEvent, node?: FrameNode) => void
4436
4437Defines a callback for click events in ArkTS.
4438
4439**Atomic service API**: This API can be used in atomic services since API version 12.
4440
4441**System capability**: SystemCapability.ArkUI.ArkUI.Full
4442
4443**Parameters**
4444
4445| Name | Type  | Mandatory| Description                         |
4446| ------- | ------ | ---- | --------------------------- |
4447| event | [ClickEvent](../apis-arkui/arkui-ts/ts-universal-events-click.md#clickevent)| Yes| Information about the click event that triggers the callback.|
4448| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | No| Component bound to the click event.|
4449
4450## MediaQuery
4451
4452In the following API examples, you must first use [getMediaQuery()](#getmediaquery) in **UIContext** to obtain a **MediaQuery** instance, and then call the APIs using the obtained instance.
4453
4454### matchMediaSync
4455
4456matchMediaSync(condition: string): mediaQuery.MediaQueryListener
4457
4458Sets the media query criteria and returns the corresponding listening handle.
4459
4460**Atomic service API**: This API can be used in atomic services since API version 11.
4461
4462**System capability**: SystemCapability.ArkUI.ArkUI.Full
4463
4464**Parameters**
4465
4466| Name      | Type    | Mandatory  | Description                                      |
4467| --------- | ------ | ---- | ---------------------------------------- |
4468| condition | string | Yes   | Media query condition. For details, see [Syntax](../../ui/arkts-layout-development-media-query.md#syntax).|
4469
4470**Return value**
4471
4472| Type                                                        | Description                                        |
4473| ------------------------------------------------------------ | -------------------------------------------- |
4474| [mediaQuery.MediaQueryListener](js-apis-mediaquery.md#mediaquerylistener) | Listening handle to a media event, which is used to register or unregister the listening callback.|
4475
4476**Example**
4477
4478<!--code_no_check-->
4479```ts
4480import { MediaQuery } from '@kit.ArkUI';
4481
4482let mediaquery: MediaQuery = uiContext.getMediaQuery();
4483let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events.
4484```
4485
4486## Router
4487
4488In the following API examples, you must first use [getRouter()](#getrouter) in **UIContext** to obtain a **Router** instance, and then call the APIs using the obtained instance.
4489
4490### pushUrl
4491
4492pushUrl(options: router.RouterOptions): Promise&lt;void&gt;
4493
4494Navigates to a specified page in the application. This API uses a promise to return the result.
4495
4496**Atomic service API**: This API can be used in atomic services since API version 11.
4497
4498**System capability**: SystemCapability.ArkUI.ArkUI.Full
4499
4500**Parameters**
4501
4502| Name    | Type                                      | Mandatory  | Description       |
4503| ------- | ---------------------------------------- | ---- | --------- |
4504| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Page routing parameters.|
4505
4506**Return value**
4507
4508| Type                 | Description     |
4509| ------------------- | ------- |
4510| Promise&lt;void&gt; | Promise used to return the result.|
4511
4512**Error codes**
4513
4514For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4515
4516| ID | Error Message                              |
4517| ------ | ---------------------------------- |
4518| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4519| 100001 | Internal error. |
4520| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist.           |
4521| 100003 | Page stack error. Too many pages are pushed.  |
4522
4523**Example**
4524
4525```ts
4526import { BusinessError } from '@kit.BasicServicesKit'
4527
4528@Entry
4529@Component
4530struct Index {
4531  async routePage() {
4532    this.getUIContext().getRouter().pushUrl({
4533        url: 'pages/routerpage2',
4534        params: {
4535          data1: 'message',
4536          data2: {
4537            data3: [123, 456, 789]
4538          }
4539        }
4540      })
4541      .then(() => {
4542        console.info('succeeded')
4543      })
4544      .catch((error: BusinessError) => {
4545        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
4546      })
4547  }
4548
4549  build() {
4550    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4551      Button() {
4552        Text('next page')
4553          .fontSize(25)
4554          .fontWeight(FontWeight.Bold)
4555      }.type(ButtonType.Capsule)
4556      .margin({ top: 20 })
4557      .backgroundColor('#ccc')
4558      .onClick(() => {
4559        this.routePage()
4560      })
4561    }
4562    .width('100%')
4563    .height('100%')
4564  }
4565}
4566```
4567
4568### pushUrl
4569
4570pushUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;): void
4571
4572Navigates to a specified page in the application.
4573
4574**Atomic service API**: This API can be used in atomic services since API version 11.
4575
4576**System capability**: SystemCapability.ArkUI.ArkUI.Full
4577
4578**Parameters**
4579
4580| Name     | Type                                      | Mandatory  | Description       |
4581| -------- | ---------------------------------------- | ---- | --------- |
4582| options  | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Page routing parameters.|
4583| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.  |
4584
4585**Error codes**
4586
4587For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4588
4589| ID | Error Message                              |
4590| ------ | ---------------------------------- |
4591| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4592| 100001 | Internal error. |
4593| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist.           |
4594| 100003 | Page stack error. Too many pages are pushed.  |
4595
4596**Example**
4597
4598```ts
4599import { BusinessError } from '@kit.BasicServicesKit'
4600
4601@Entry
4602@Component
4603struct Index {
4604  async routePage() {
4605    this.getUIContext().getRouter().pushUrl({
4606      url: 'pages/routerpage2',
4607      params: {
4608        data1: 'message',
4609        data2: {
4610          data3: [123, 456, 789]
4611        }
4612      }
4613    }, (err: Error) => {
4614      if (err) {
4615        let message = (err as BusinessError).message;
4616        let code = (err as BusinessError).code;
4617        console.error(`pushUrl failed, code is ${code}, message is ${message}`);
4618        return;
4619      }
4620      console.info('pushUrl success');
4621    })
4622  }
4623
4624  build() {
4625    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4626      Button() {
4627        Text('next page')
4628          .fontSize(25)
4629          .fontWeight(FontWeight.Bold)
4630      }.type(ButtonType.Capsule)
4631      .margin({ top: 20 })
4632      .backgroundColor('#ccc')
4633      .onClick(() => {
4634        this.routePage()
4635      })
4636    }
4637    .width('100%')
4638    .height('100%')
4639  }
4640}
4641```
4642
4643### pushUrl
4644
4645pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
4646
4647Navigates to a specified page in the application. This API uses a promise to return the result.
4648
4649**Atomic service API**: This API can be used in atomic services since API version 11.
4650
4651**System capability**: SystemCapability.ArkUI.ArkUI.Full
4652
4653**Parameters**
4654
4655| Name    | Type                                      | Mandatory  | Description        |
4656| ------- | ---------------------------------------- | ---- | ---------- |
4657| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Page routing parameters. |
4658| mode    | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
4659
4660**Return value**
4661
4662| Type                 | Description     |
4663| ------------------- | ------- |
4664| Promise&lt;void&gt; | Promise used to return the result.|
4665
4666**Error codes**
4667
4668For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4669
4670| ID | Error Message                              |
4671| ------ | ---------------------------------- |
4672| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4673| 100001 | Internal error. |
4674| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist.           |
4675| 100003 | Page stack error. Too many pages are pushed.  |
4676
4677**Example**
4678
4679```ts
4680import { router } from '@kit.ArkUI';
4681import { BusinessError } from '@kit.BasicServicesKit'
4682
4683class RouterTmp {
4684  Standard: router.RouterMode = router.RouterMode.Standard
4685}
4686
4687let rtm: RouterTmp = new RouterTmp()
4688
4689@Entry
4690@Component
4691struct Index {
4692  async routePage() {
4693    this.getUIContext().getRouter().pushUrl({
4694        url: 'pages/routerpage2',
4695        params: {
4696          data1: 'message',
4697          data2: {
4698            data3: [123, 456, 789]
4699          }
4700        }
4701      }, rtm.Standard)
4702      .then(() => {
4703        console.info('succeeded')
4704      })
4705      .catch((error: BusinessError) => {
4706        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
4707      })
4708  }
4709
4710  build() {
4711    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4712      Button() {
4713        Text('next page')
4714          .fontSize(25)
4715          .fontWeight(FontWeight.Bold)
4716      }.type(ButtonType.Capsule)
4717      .margin({ top: 20 })
4718      .backgroundColor('#ccc')
4719      .onClick(() => {
4720        this.routePage()
4721      })
4722    }
4723    .width('100%')
4724    .height('100%')
4725  }
4726}
4727```
4728
4729### pushUrl
4730
4731pushUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
4732
4733Navigates to a specified page in the application.
4734
4735**Atomic service API**: This API can be used in atomic services since API version 11.
4736
4737**System capability**: SystemCapability.ArkUI.ArkUI.Full
4738
4739**Parameters**
4740
4741| Name     | Type                                      | Mandatory  | Description        |
4742| -------- | ---------------------------------------- | ---- | ---------- |
4743| options  | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Page routing parameters. |
4744| mode     | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
4745| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.   |
4746
4747**Error codes**
4748
4749For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4750
4751| ID | Error Message                              |
4752| ------ | ---------------------------------- |
4753| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4754| 100001 | Internal error. |
4755| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist.           |
4756| 100003 | Page stack error. Too many pages are pushed.  |
4757
4758**Example**
4759
4760```ts
4761import { router } from '@kit.ArkUI';
4762import { BusinessError } from '@kit.BasicServicesKit'
4763
4764class RouterTmp {
4765  Standard: router.RouterMode = router.RouterMode.Standard
4766}
4767
4768let rtm: RouterTmp = new RouterTmp()
4769
4770@Entry
4771@Component
4772struct Index {
4773  async routePage() {
4774    this.getUIContext().getRouter().pushUrl({
4775      url: 'pages/routerpage2',
4776      params: {
4777        data1: 'message',
4778        data2: {
4779          data3: [123, 456, 789]
4780        }
4781      }
4782    }, rtm.Standard, (err) => {
4783      if (err) {
4784        let message = (err as BusinessError).message;
4785        let code = (err as BusinessError).code;
4786        console.error(`pushUrl failed, code is ${code}, message is ${message}`);
4787        return;
4788      }
4789      console.info('pushUrl success');
4790    })
4791  }
4792
4793  build() {
4794    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4795      Button() {
4796        Text('next page')
4797          .fontSize(25)
4798          .fontWeight(FontWeight.Bold)
4799      }.type(ButtonType.Capsule)
4800      .margin({ top: 20 })
4801      .backgroundColor('#ccc')
4802      .onClick(() => {
4803        this.routePage()
4804      })
4805    }
4806    .width('100%')
4807    .height('100%')
4808  }
4809}
4810```
4811
4812### replaceUrl
4813
4814replaceUrl(options: router.RouterOptions): Promise&lt;void&gt;
4815
4816Replaces the current page with another one in the application and destroys the current page. This API uses a promise to return the result.
4817
4818**Atomic service API**: This API can be used in atomic services since API version 11.
4819
4820**System capability**: SystemCapability.ArkUI.ArkUI.Full
4821
4822**Parameters**
4823
4824| Name    | Type                                      | Mandatory  | Description       |
4825| ------- | ---------------------------------------- | ---- | --------- |
4826| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Description of the new page.|
4827
4828**Return value**
4829
4830| Type                 | Description     |
4831| ------------------- | ------- |
4832| Promise&lt;void&gt; | Promise used to return the result.|
4833
4834**Error codes**
4835
4836For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4837
4838| ID | Error Message                                    |
4839| ------ | ---------------------------------------- |
4840| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4841| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
4842| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist.                 |
4843
4844**Example**
4845
4846```ts
4847import { BusinessError } from '@kit.BasicServicesKit'
4848
4849@Entry
4850@Component
4851struct Index {
4852  async routePage() {
4853    this.getUIContext().getRouter().replaceUrl({
4854        url: 'pages/detail',
4855        params: {
4856          data1: 'message'
4857        }
4858      })
4859      .then(() => {
4860        console.info('succeeded')
4861      })
4862      .catch((error: BusinessError) => {
4863        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
4864      })
4865  }
4866
4867  build() {
4868    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4869      Button() {
4870        Text('next page')
4871          .fontSize(25)
4872          .fontWeight(FontWeight.Bold)
4873      }.type(ButtonType.Capsule)
4874      .margin({ top: 20 })
4875      .backgroundColor('#ccc')
4876      .onClick(() => {
4877        this.routePage()
4878      })
4879    }
4880    .width('100%')
4881    .height('100%')
4882  }
4883}
4884```
4885
4886### replaceUrl
4887
4888replaceUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;): void
4889
4890Replaces the current page with another one in the application and destroys the current page.
4891
4892**Atomic service API**: This API can be used in atomic services since API version 11.
4893
4894**System capability**: SystemCapability.ArkUI.ArkUI.Full
4895
4896**Parameters**
4897
4898| Name     | Type                                      | Mandatory  | Description       |
4899| -------- | ---------------------------------------- | ---- | --------- |
4900| options  | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Description of the new page.|
4901| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.  |
4902
4903**Error codes**
4904
4905For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4906
4907| ID | Error Message                                    |
4908| ------ | ---------------------------------------- |
4909| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4910| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
4911| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. |
4912
4913**Example**
4914
4915```ts
4916import { BusinessError } from '@kit.BasicServicesKit'
4917
4918@Entry
4919@Component
4920struct Index {
4921  async routePage() {
4922    this.getUIContext().getRouter().replaceUrl({
4923      url: 'pages/detail',
4924      params: {
4925        data1: 'message'
4926      }
4927    }, (err: Error) => {
4928      if (err) {
4929        let message = (err as BusinessError).message;
4930        let code = (err as BusinessError).code;
4931        console.error(`replaceUrl failed, code is ${code}, message is ${message}`);
4932        return;
4933      }
4934      console.info('replaceUrl success');
4935    })
4936  }
4937
4938  build() {
4939    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4940      Button() {
4941        Text('next page')
4942          .fontSize(25)
4943          .fontWeight(FontWeight.Bold)
4944      }.type(ButtonType.Capsule)
4945      .margin({ top: 20 })
4946      .backgroundColor('#ccc')
4947      .onClick(() => {
4948        this.routePage()
4949      })
4950    }
4951    .width('100%')
4952    .height('100%')
4953  }
4954}
4955```
4956
4957### replaceUrl
4958
4959replaceUrl(options: router.RouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
4960
4961Replaces the current page with another one in the application and destroys the current page. This API uses a promise to return the result.
4962
4963**Atomic service API**: This API can be used in atomic services since API version 11.
4964
4965**System capability**: SystemCapability.ArkUI.ArkUI.Full
4966
4967**Parameters**
4968
4969| Name    | Type                                      | Mandatory  | Description        |
4970| ------- | ---------------------------------------- | ---- | ---------- |
4971| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Description of the new page. |
4972| mode    | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
4973
4974**Return value**
4975
4976| Type                 | Description     |
4977| ------------------- | ------- |
4978| Promise&lt;void&gt; | Promise used to return the result.|
4979
4980**Error codes**
4981
4982For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4983
4984| ID | Error Message                                    |
4985| ------ | ---------------------------------------- |
4986| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4987| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. |
4988| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist.                 |
4989
4990**Example**
4991
4992```ts
4993import { router } from '@kit.ArkUI';
4994import { BusinessError } from '@kit.BasicServicesKit'
4995
4996class RouterTmp {
4997  Standard: router.RouterMode = router.RouterMode.Standard
4998}
4999
5000let rtm: RouterTmp = new RouterTmp()
5001
5002@Entry
5003@Component
5004struct Index {
5005  async routePage() {
5006    this.getUIContext().getRouter().replaceUrl({
5007        url: 'pages/detail',
5008        params: {
5009          data1: 'message'
5010        }
5011      }, rtm.Standard)
5012      .then(() => {
5013        console.info('succeeded')
5014      })
5015      .catch((error: BusinessError) => {
5016        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
5017      })
5018  }
5019
5020  build() {
5021    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5022      Button() {
5023        Text('next page')
5024          .fontSize(25)
5025          .fontWeight(FontWeight.Bold)
5026      }.type(ButtonType.Capsule)
5027      .margin({ top: 20 })
5028      .backgroundColor('#ccc')
5029      .onClick(() => {
5030        this.routePage()
5031      })
5032    }
5033    .width('100%')
5034    .height('100%')
5035  }
5036}
5037```
5038
5039### replaceUrl
5040
5041replaceUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
5042
5043Replaces the current page with another one in the application and destroys the current page.
5044
5045**Atomic service API**: This API can be used in atomic services since API version 11.
5046
5047**System capability**: SystemCapability.ArkUI.ArkUI.Full
5048
5049**Parameters**
5050
5051| Name     | Type                                      | Mandatory  | Description        |
5052| -------- | ---------------------------------------- | ---- | ---------- |
5053| options  | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Description of the new page. |
5054| mode     | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
5055| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.   |
5056
5057**Error codes**
5058
5059For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5060
5061| ID | Error Message                                    |
5062| ------ | ---------------------------------------- |
5063| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5064| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
5065| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist.               |
5066
5067**Example**
5068
5069```ts
5070import { router } from '@kit.ArkUI';
5071import { BusinessError } from '@kit.BasicServicesKit';
5072
5073class RouterTmp {
5074  Standard: router.RouterMode = router.RouterMode.Standard
5075}
5076
5077let rtm: RouterTmp = new RouterTmp()
5078
5079@Entry
5080@Component
5081struct Index {
5082  async routePage() {
5083    this.getUIContext().getRouter().replaceUrl({
5084      url: 'pages/detail',
5085      params: {
5086        data1: 'message'
5087      }
5088    }, rtm.Standard, (err: Error) => {
5089      if (err) {
5090        let message = (err as BusinessError).message;
5091        let code = (err as BusinessError).code;
5092        console.error(`replaceUrl failed, code is ${code}, message is ${message}`);
5093        return;
5094      }
5095      console.info('replaceUrl success');
5096    });
5097  }
5098
5099  build() {
5100    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5101      Button() {
5102        Text('next page')
5103          .fontSize(25)
5104          .fontWeight(FontWeight.Bold)
5105      }.type(ButtonType.Capsule)
5106      .margin({ top: 20 })
5107      .backgroundColor('#ccc')
5108      .onClick(() => {
5109        this.routePage()
5110      })
5111    }
5112    .width('100%')
5113    .height('100%')
5114  }
5115}
5116```
5117
5118### pushNamedRoute
5119
5120pushNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt;
5121
5122Navigates to a page using the named route. This API uses a promise to return the result.
5123
5124**Atomic service API**: This API can be used in atomic services since API version 11.
5125
5126**System capability**: SystemCapability.ArkUI.ArkUI.Full
5127
5128**Parameters**
5129
5130| Name    | Type                                      | Mandatory  | Description       |
5131| ------- | ---------------------------------------- | ---- | --------- |
5132| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Page routing parameters.|
5133
5134**Return value**
5135
5136| Type                 | Description     |
5137| ------------------- | ------- |
5138| Promise&lt;void&gt; | Promise used to return the result.|
5139
5140**Error codes**
5141
5142For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5143
5144| ID | Error Message                              |
5145| ------ | ---------------------------------- |
5146| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5147| 100001 | Internal error. |
5148| 100003 | Page stack error. Too many pages are pushed.  |
5149| 100004 | Named route error. The named route does not exist.   |
5150
5151**Example**
5152
5153```ts
5154import { BusinessError } from '@kit.BasicServicesKit'
5155
5156@Entry
5157@Component
5158struct Index {
5159  async routePage() {
5160    this.getUIContext().getRouter().pushNamedRoute({
5161        name: 'myPage',
5162        params: {
5163          data1: 'message',
5164          data2: {
5165            data3: [123, 456, 789]
5166          }
5167        }
5168      })
5169      .then(() => {
5170        console.info('succeeded')
5171      })
5172      .catch((error: BusinessError) => {
5173        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
5174      })
5175  }
5176
5177  build() {
5178    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5179      Button() {
5180        Text('next page')
5181          .fontSize(25)
5182          .fontWeight(FontWeight.Bold)
5183      }.type(ButtonType.Capsule)
5184      .margin({ top: 20 })
5185      .backgroundColor('#ccc')
5186      .onClick(() => {
5187        this.routePage()
5188      })
5189    }
5190    .width('100%')
5191    .height('100%')
5192  }
5193}
5194```
5195
5196### pushNamedRoute
5197
5198pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt;void&gt;): void
5199
5200Navigates to a page using the named route. This API uses a promise to return the result.
5201
5202**Atomic service API**: This API can be used in atomic services since API version 11.
5203
5204**System capability**: SystemCapability.ArkUI.ArkUI.Full
5205
5206**Parameters**
5207
5208| Name     | Type                                      | Mandatory  | Description       |
5209| -------- | ---------------------------------------- | ---- | --------- |
5210| options  | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Page routing parameters.|
5211| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.  |
5212
5213**Error codes**
5214
5215For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5216
5217| ID | Error Message                              |
5218| ------ | ---------------------------------- |
5219| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5220| 100001 | Internal error. |
5221| 100003 | Page stack error. Too many pages are pushed.  |
5222| 100004 | Named route error. The named route does not exist.  |
5223
5224**Example**
5225
5226```ts
5227import { BusinessError } from '@kit.BasicServicesKit';
5228
5229@Entry
5230@Component
5231struct Index {
5232  async routePage() {
5233    this.getUIContext().getRouter().pushNamedRoute({
5234      name: 'myPage',
5235      params: {
5236        data1: 'message',
5237        data2: {
5238          data3: [123, 456, 789]
5239        }
5240      }
5241    }, (err: Error) => {
5242      if (err) {
5243        let message = (err as BusinessError).message;
5244        let code = (err as BusinessError).code;
5245        console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
5246        return;
5247      }
5248      console.info('pushNamedRoute success');
5249    })
5250  }
5251
5252  build() {
5253    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5254      Button() {
5255        Text('next page')
5256          .fontSize(25)
5257          .fontWeight(FontWeight.Bold)
5258      }.type(ButtonType.Capsule)
5259      .margin({ top: 20 })
5260      .backgroundColor('#ccc')
5261      .onClick(() => {
5262        this.routePage()
5263      })
5264    }
5265    .width('100%')
5266    .height('100%')
5267  }
5268}
5269```
5270### pushNamedRoute
5271
5272pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
5273
5274Navigates to a page using the named route. This API uses a promise to return the result.
5275
5276**Atomic service API**: This API can be used in atomic services since API version 11.
5277
5278**System capability**: SystemCapability.ArkUI.ArkUI.Full
5279
5280**Parameters**
5281
5282| Name    | Type                                      | Mandatory  | Description        |
5283| ------- | ---------------------------------------- | ---- | ---------- |
5284| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Page routing parameters. |
5285| mode    | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
5286
5287**Return value**
5288
5289| Type                 | Description     |
5290| ------------------- | ------- |
5291| Promise&lt;void&gt; | Promise used to return the result.|
5292
5293**Error codes**
5294
5295For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5296
5297| ID | Error Message                              |
5298| ------ | ---------------------------------- |
5299| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5300| 100001 | Internal error. |
5301| 100003 | Page stack error. Too many pages are pushed.  |
5302| 100004 | Named route error. The named route does not exist.  |
5303
5304**Example**
5305
5306```ts
5307import { router } from '@kit.ArkUI';
5308import { BusinessError } from '@kit.BasicServicesKit';
5309
5310class RouterTmp{
5311  Standard:router.RouterMode = router.RouterMode.Standard
5312}
5313let rtm:RouterTmp = new RouterTmp()
5314
5315@Entry
5316@Component
5317struct Index {
5318  async routePage() {
5319    this.getUIContext().getRouter().pushNamedRoute({
5320        name: 'myPage',
5321        params: {
5322          data1: 'message',
5323          data2: {
5324            data3: [123, 456, 789]
5325          }
5326        }
5327      }, rtm.Standard)
5328      .then(() => {
5329        console.info('succeeded')
5330      })
5331      .catch((error: BusinessError) => {
5332        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
5333      })
5334  }
5335
5336  build() {
5337    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5338      Button() {
5339        Text('next page')
5340          .fontSize(25)
5341          .fontWeight(FontWeight.Bold)
5342      }.type(ButtonType.Capsule)
5343      .margin({ top: 20 })
5344      .backgroundColor('#ccc')
5345      .onClick(() => {
5346        this.routePage()
5347      })
5348    }
5349    .width('100%')
5350    .height('100%')
5351  }
5352}
5353```
5354
5355### pushNamedRoute
5356
5357pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
5358
5359Navigates to a page using the named route. This API uses a promise to return the result.
5360
5361**Atomic service API**: This API can be used in atomic services since API version 11.
5362
5363**System capability**: SystemCapability.ArkUI.ArkUI.Full
5364
5365**Parameters**
5366
5367| Name     | Type                                      | Mandatory  | Description        |
5368| -------- | ---------------------------------------- | ---- | ---------- |
5369| options  | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Page routing parameters. |
5370| mode     | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
5371| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.   |
5372
5373**Error codes**
5374
5375For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5376
5377| ID | Error Message                              |
5378| ------ | ---------------------------------- |
5379| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5380| 100001 | Internal error. |
5381| 100003 | Page stack error. Too many pages are pushed.  |
5382| 100004 | Named route error. The named route does not exist.   |
5383
5384**Example**
5385
5386```ts
5387import { router } from '@kit.ArkUI';
5388import { BusinessError } from '@kit.BasicServicesKit';
5389
5390class RouterTmp {
5391  Standard: router.RouterMode = router.RouterMode.Standard
5392}
5393
5394let rtm: RouterTmp = new RouterTmp()
5395
5396@Entry
5397@Component
5398struct Index {
5399  async routePage() {
5400    this.getUIContext().getRouter().pushNamedRoute({
5401      name: 'myPage',
5402      params: {
5403        data1: 'message',
5404        data2: {
5405          data3: [123, 456, 789]
5406        }
5407      }
5408    }, rtm.Standard, (err: Error) => {
5409      if (err) {
5410        let message = (err as BusinessError).message;
5411        let code = (err as BusinessError).code;
5412        console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
5413        return;
5414      }
5415      console.info('pushNamedRoute success');
5416    })
5417  }
5418
5419  build() {
5420    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5421      Button() {
5422        Text('next page')
5423          .fontSize(25)
5424          .fontWeight(FontWeight.Bold)
5425      }.type(ButtonType.Capsule)
5426      .margin({ top: 20 })
5427      .backgroundColor('#ccc')
5428      .onClick(() => {
5429        this.routePage()
5430      })
5431    }
5432    .width('100%')
5433    .height('100%')
5434  }
5435}
5436```
5437
5438### replaceNamedRoute
5439
5440replaceNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt;
5441
5442Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.
5443
5444**Atomic service API**: This API can be used in atomic services since API version 11.
5445
5446**System capability**: SystemCapability.ArkUI.ArkUI.Full
5447
5448**Parameters**
5449
5450| Name    | Type                                      | Mandatory  | Description       |
5451| ------- | ---------------------------------------- | ---- | --------- |
5452| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Description of the new page.|
5453
5454**Return value**
5455
5456| Type                 | Description     |
5457| ------------------- | ------- |
5458| Promise&lt;void&gt; | Promise used to return the result.|
5459
5460**Error codes**
5461
5462For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5463
5464| ID | Error Message                                    |
5465| ------ | ---------------------------------------- |
5466| 401      | if the number of parameters is less than 1 or the type of the url parameter is not string. |
5467| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
5468| 100004 | Named route error. The named route does not exist.        |
5469
5470**Example**
5471
5472```ts
5473import { BusinessError } from '@kit.BasicServicesKit';
5474
5475@Entry
5476@Component
5477struct Index {
5478  async routePage() {
5479    this.getUIContext().getRouter().replaceNamedRoute({
5480        name: 'myPage',
5481        params: {
5482          data1: 'message'
5483        }
5484      })
5485      .then(() => {
5486        console.info('succeeded')
5487      })
5488      .catch((error: BusinessError) => {
5489        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
5490      })
5491  }
5492
5493  build() {
5494    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5495      Button() {
5496        Text('next page')
5497          .fontSize(25)
5498          .fontWeight(FontWeight.Bold)
5499      }.type(ButtonType.Capsule)
5500      .margin({ top: 20 })
5501      .backgroundColor('#ccc')
5502      .onClick(() => {
5503        this.routePage()
5504      })
5505    }
5506    .width('100%')
5507    .height('100%')
5508  }
5509}
5510```
5511
5512### replaceNamedRoute
5513
5514replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt;void&gt;): void
5515
5516Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.
5517
5518**Atomic service API**: This API can be used in atomic services since API version 11.
5519
5520**System capability**: SystemCapability.ArkUI.ArkUI.Full
5521
5522**Parameters**
5523
5524| Name     | Type                                      | Mandatory  | Description       |
5525| -------- | ---------------------------------------- | ---- | --------- |
5526| options  | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Description of the new page.|
5527| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.  |
5528
5529**Error codes**
5530
5531For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5532
5533| ID | Error Message                                    |
5534| ------ | ---------------------------------------- |
5535| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5536| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
5537| 100004 | Named route error. The named route does not exist.         |
5538
5539**Example**
5540
5541```ts
5542import { BusinessError } from '@kit.BasicServicesKit';
5543
5544@Entry
5545@Component
5546struct Index {
5547  async routePage() {
5548    this.getUIContext().getRouter().replaceNamedRoute({
5549      name: 'myPage',
5550      params: {
5551        data1: 'message'
5552      }
5553    }, (err: Error) => {
5554      if (err) {
5555        let message = (err as BusinessError).message;
5556        let code = (err as BusinessError).code;
5557        console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`);
5558        return;
5559      }
5560      console.info('replaceNamedRoute success');
5561    })
5562  }
5563
5564  build() {
5565    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5566      Button() {
5567        Text('next page')
5568          .fontSize(25)
5569          .fontWeight(FontWeight.Bold)
5570      }.type(ButtonType.Capsule)
5571      .margin({ top: 20 })
5572      .backgroundColor('#ccc')
5573      .onClick(() => {
5574        this.routePage()
5575      })
5576    }
5577    .width('100%')
5578    .height('100%')
5579  }
5580}
5581```
5582
5583### replaceNamedRoute
5584
5585replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
5586
5587Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.
5588
5589**Atomic service API**: This API can be used in atomic services since API version 11.
5590
5591**System capability**: SystemCapability.ArkUI.ArkUI.Full
5592
5593**Parameters**
5594
5595| Name    | Type                                      | Mandatory  | Description        |
5596| ------- | ---------------------------------------- | ---- | ---------- |
5597| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Description of the new page. |
5598| mode    | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
5599
5600
5601**Return value**
5602
5603| Type                 | Description     |
5604| ------------------- | ------- |
5605| Promise&lt;void&gt; | Promise used to return the result.|
5606
5607**Error codes**
5608
5609For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5610
5611| ID | Error Message                                    |
5612| ------ | ---------------------------------------- |
5613| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5614| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. |
5615| 100004 | Named route error. The named route does not exist.       |
5616
5617**Example**
5618
5619```ts
5620import { router } from '@kit.ArkUI';
5621import { BusinessError } from '@kit.BasicServicesKit';
5622
5623class RouterTmp {
5624  Standard: router.RouterMode = router.RouterMode.Standard
5625}
5626
5627let rtm: RouterTmp = new RouterTmp()
5628
5629@Entry
5630@Component
5631struct Index {
5632  async routePage() {
5633    this.getUIContext().getRouter().replaceNamedRoute({
5634        name: 'myPage',
5635        params: {
5636          data1: 'message'
5637        }
5638      }, rtm.Standard)
5639      .then(() => {
5640        console.info('succeeded')
5641      })
5642      .catch((error: BusinessError) => {
5643        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
5644      })
5645  }
5646
5647  build() {
5648    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5649      Button() {
5650        Text('next page')
5651          .fontSize(25)
5652          .fontWeight(FontWeight.Bold)
5653      }.type(ButtonType.Capsule)
5654      .margin({ top: 20 })
5655      .backgroundColor('#ccc')
5656      .onClick(() => {
5657        this.routePage()
5658      })
5659    }
5660    .width('100%')
5661    .height('100%')
5662  }
5663}
5664```
5665
5666### replaceNamedRoute
5667
5668replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
5669
5670Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.
5671
5672**Atomic service API**: This API can be used in atomic services since API version 11.
5673
5674**System capability**: SystemCapability.ArkUI.ArkUI.Full
5675
5676**Parameters**
5677
5678| Name     | Type                                      | Mandatory  | Description        |
5679| -------- | ---------------------------------------- | ---- | ---------- |
5680| options  | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Description of the new page. |
5681| mode     | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
5682| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.   |
5683
5684**Error codes**
5685
5686For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5687
5688| ID | Error Message                                    |
5689| ------ | ---------------------------------------- |
5690| 401      | if the number of parameters is less than 1 or the type of the url parameter is not string. |
5691| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
5692| 100004 | Named route error. The named route does not exist.        |
5693
5694**Example**
5695
5696```ts
5697import { router } from '@kit.ArkUI';
5698import { BusinessError } from '@kit.BasicServicesKit';
5699
5700class RouterTmp {
5701  Standard: router.RouterMode = router.RouterMode.Standard
5702}
5703
5704let rtm: RouterTmp = new RouterTmp()
5705
5706@Entry
5707@Component
5708struct Index {
5709  async routePage() {
5710    this.getUIContext().getRouter().replaceNamedRoute({
5711      name: 'myPage',
5712      params: {
5713        data1: 'message'
5714      }
5715    }, rtm.Standard, (err: Error) => {
5716      if (err) {
5717        let message = (err as BusinessError).message;
5718        let code = (err as BusinessError).code;
5719        console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`);
5720        return;
5721      }
5722      console.info('replaceNamedRoute success');
5723    })
5724  }
5725
5726  build() {
5727    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5728      Button() {
5729        Text('next page')
5730          .fontSize(25)
5731          .fontWeight(FontWeight.Bold)
5732      }.type(ButtonType.Capsule)
5733      .margin({ top: 20 })
5734      .backgroundColor('#ccc')
5735      .onClick(() => {
5736        this.routePage()
5737      })
5738    }
5739    .width('100%')
5740    .height('100%')
5741  }
5742}
5743```
5744
5745### back
5746
5747back(options?: router.RouterOptions ): void
5748
5749Returns to the previous page or a specified page.
5750
5751**Atomic service API**: This API can be used in atomic services since API version 11.
5752
5753**System capability**: SystemCapability.ArkUI.ArkUI.Full
5754
5755**Parameters**
5756
5757| Name    | Type                                      | Mandatory  | Description                                      |
5758| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
5759| options | [router.RouterOptions](js-apis-router.md#routeroptions) | No   | Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If no URL is set, the application returns to the previous page, and the page is not rebuilt. The page in the page stack is not reclaimed. It will be reclaimed after being popped up.|
5760
5761**Example**
5762
5763```ts
5764import { Router } from '@kit.ArkUI';
5765let router: Router = uiContext.getRouter();
5766router.back({url:'pages/detail'});
5767```
5768
5769### back<sup>12+</sup>
5770
5771back(index: number, params?: Object): void;
5772
5773Returns to the specified page.
5774
5775**Atomic service API**: This API can be used in atomic services since API version 12.
5776
5777**System capability**: SystemCapability.ArkUI.ArkUI.Full
5778
5779**Parameters**
5780
5781| Name    | Type                             | Mandatory  | Description        |
5782| ------- | ------------------------------- | ---- | ---------- |
5783| index | number | Yes   | Index of the target page to navigate to. |
5784| params    | Object      | No   | Parameters carried when returning to the page.|
5785
5786**Example**
5787
5788```ts
5789import { Router } from '@kit.ArkUI';
5790
5791let router: Router = uiContext.getRouter();
5792router.back(1);
5793```
5794
5795```ts
5796import { Router } from '@kit.ArkUI';
5797
5798let router: Router = uiContext.getRouter();
5799router.back(1, {info:'From Home'}); // Returning with parameters.
5800```
5801
5802### clear
5803
5804clear(): void
5805
5806Clears all historical pages in the stack and retains only the current page at the top of the stack.
5807
5808**Atomic service API**: This API can be used in atomic services since API version 11.
5809
5810**System capability**: SystemCapability.ArkUI.ArkUI.Full
5811
5812**Example**
5813
5814```ts
5815import { Router } from '@kit.ArkUI';
5816
5817let router: Router = uiContext.getRouter();
5818router.clear();
5819```
5820
5821### getLength
5822
5823getLength(): string
5824
5825Obtains the number of pages in the current stack.
5826
5827**Atomic service API**: This API can be used in atomic services since API version 11.
5828
5829**System capability**: SystemCapability.ArkUI.ArkUI.Full
5830
5831**Return value**
5832
5833| Type    | Description                |
5834| ------ | ------------------ |
5835| string | Number of pages in the stack. The maximum value is **32**.|
5836
5837**Example**
5838
5839```ts
5840import { Router } from '@kit.ArkUI';
5841
5842let router: Router = uiContext.getRouter();
5843let size = router.getLength();
5844console.info('pages stack size = ' + size);
5845```
5846
5847### getState
5848
5849getState(): router.RouterState
5850
5851Obtains state information about the current page.
5852
5853**Atomic service API**: This API can be used in atomic services since API version 11.
5854
5855**System capability**: SystemCapability.ArkUI.ArkUI.Full
5856
5857**Return value**
5858
5859| Type                                      | Description     |
5860| ---------------------------------------- | ------- |
5861| router.[RouterState](js-apis-router.md#routerstate) | Page routing state.|
5862
5863**Example**
5864
5865<!--code_no_check-->
5866```ts
5867import { Router } from '@kit.ArkUI';
5868
5869let router: Router = uiContext.getRouter();
5870let page = router.getState();
5871console.info('current index = ' + page.index);
5872console.info('current name = ' + page.name);
5873console.info('current path = ' + page.path);
5874```
5875
5876### getStateByIndex<sup>12+</sup>
5877
5878getStateByIndex(index: number): router.RouterState | undefined
5879
5880Obtains the status information about a page by its index.
5881
5882**Atomic service API**: This API can be used in atomic services since API version 12.
5883
5884**System capability**: SystemCapability.ArkUI.ArkUI.Full
5885
5886**Parameters**
5887
5888| Name    | Type                             | Mandatory  | Description        |
5889| ------- | ------------------------------- | ---- | ---------- |
5890| index    | number | Yes  | Index of the target page. |
5891
5892**Return value**
5893
5894| Type                         | Description     |
5895| --------------------------- | ------- |
5896| router.[RouterState](js-apis-router.md#outerstate) \| undefined | State information about the target page. **undefined** if the specified index does not exist.|
5897
5898**Example**
5899
5900<!--code_no_check-->
5901```ts
5902import { Router } from '@kit.ArkUI';
5903
5904let router: Router = uiContext.getRouter();
5905let options: router.RouterState | undefined = router.getStateByIndex(1);
5906if (options != undefined) {
5907  console.info('index = ' + options.index);
5908  console.info('name = ' + options.name);
5909  console.info('path = ' + options.path);
5910  console.info('params = ' + options.params);
5911}
5912```
5913### getStateByUrl<sup>12+</sup>
5914
5915getStateByUrl(url: string): Array<router.[RouterState](js-apis-router.md#outerstate)>
5916
5917Obtains the status information about a page by its URL.
5918
5919**Atomic service API**: This API can be used in atomic services since API version 12.
5920
5921**System capability**: SystemCapability.ArkUI.ArkUI.Full
5922
5923**Parameters**
5924
5925| Name    | Type                             | Mandatory  | Description        |
5926| ------- | ------------------------------- | ---- | ---------- |
5927| url    | string | Yes  | URL of the target page. |
5928
5929**Return value**
5930
5931| Type                         | Description     |
5932| --------------------------- | ------- |
5933| Array<router.[RouterState](js-apis-router.md#outerstate)> | Page routing state.|
5934
5935**Example**
5936
5937<!--code_no_check-->
5938```ts
5939import { Router } from '@kit.ArkUI';
5940let router: Router = uiContext.getRouter();
5941let options:Array<router.RouterState> = router.getStateByUrl('pages/index');
5942for (let i: number = 0; i < options.length; i++) {
5943  console.info('index = ' + options[i].index);
5944  console.info('name = ' + options[i].name);
5945  console.info('path = ' + options[i].path);
5946  console.info('params = ' + options[i].params);
5947}
5948```
5949
5950### showAlertBeforeBackPage
5951
5952showAlertBeforeBackPage(options: router.EnableAlertOptions): void
5953
5954Enables the display of a confirm dialog box before returning to the previous page.
5955
5956**Atomic service API**: This API can be used in atomic services since API version 11.
5957
5958**System capability**: SystemCapability.ArkUI.ArkUI.Full
5959
5960**Parameters**
5961
5962| Name    | Type                                      | Mandatory  | Description       |
5963| ------- | ---------------------------------------- | ---- | --------- |
5964| options | [router.EnableAlertOptions](js-apis-router.md#enablealertoptions) | Yes   | Description of the dialog box.|
5965
5966**Error codes**
5967
5968For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5969
5970| ID | Error Message                              |
5971| ------ | ---------------------------------- |
5972| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5973| 100001 | Internal error. |
5974
5975**Example**
5976
5977<!--code_no_check-->
5978```ts
5979import { Router } from '@kit.ArkUI';
5980import { BusinessError } from '@kit.BasicServicesKit';
5981
5982let router: Router = uiContext.getRouter();
5983try {
5984  router.showAlertBeforeBackPage({
5985    message: 'Message Info'
5986  });
5987} catch(error) {
5988  let message = (error as BusinessError).message;
5989  let code = (error as BusinessError).code;
5990  console.error(`showAlertBeforeBackPage failed, code is ${code}, message is ${message}`);
5991}
5992```
5993
5994### hideAlertBeforeBackPage
5995
5996hideAlertBeforeBackPage(): void
5997
5998Disables the display of a confirm dialog box before returning to the previous page.
5999
6000**Atomic service API**: This API can be used in atomic services since API version 11.
6001
6002**System capability**: SystemCapability.ArkUI.ArkUI.Full
6003
6004**Example**
6005
6006<!--code_no_check-->
6007```ts
6008import { Router } from '@kit.ArkUI';
6009
6010let router: Router = uiContext.getRouter();
6011router.hideAlertBeforeBackPage();
6012```
6013
6014### getParams
6015
6016getParams(): Object
6017
6018Obtains the parameters passed from the page that initiates redirection to the current page.
6019
6020**Atomic service API**: This API can be used in atomic services since API version 11.
6021
6022**System capability**: SystemCapability.ArkUI.ArkUI.Full
6023
6024**Return value**
6025
6026| Type    | Description               |
6027| ------ | ----------------- |
6028| Object | Parameters passed from the page that initiates redirection to the current page.|
6029
6030**Example**
6031
6032<!--code_no_check-->
6033
6034```ts
6035import { Router } from '@kit.ArkUI';
6036
6037let router: Router = uiContext.getRouter();
6038router.getParams();
6039```
6040
6041## CustomBuilderWithId<sup>18+</sup>
6042
6043type CustomBuilderWithId = (id: number) =&gt; void
6044
6045The **CustomBuilderWithId** type is used as a parameter for component attribute methods to customize the UI description and generate custom components by specifying the component ID.
6046
6047**Atomic service API**: This API can be used in atomic services since API version 18.
6048
6049**System capability**: SystemCapability.ArkUI.ArkUI.Full
6050
6051**Parameters**
6052
6053| Name| Type| Mandatory| Description|
6054| -------- | -------- | -------- | -------- |
6055| id | number | Yes| Component ID.|
6056
6057## TargetInfo<sup>18+</sup>
6058
6059Specifies the target node for component binding.
6060
6061**Atomic service API**: This API can be used in atomic services since API version 18.
6062
6063**System capability**: SystemCapability.ArkUI.ArkUI.Full
6064
6065**Parameters**
6066
6067| Name| Type| Mandatory| Description|
6068| -------- | -------- | -------- | -------- |
6069| id | string \| number | Yes| Target node for binding popups or menus.<br>**NOTE**<br>1. When **id** is a number, it corresponds to the component's **UniqueID**, whose uniqueness is guaranteed by the system.<br>2. When **id** is a string, it corresponds to the component specified by the universal attribute [id](arkui-ts/ts-universal-attributes-component-id.md#id). You must ensure the uniqueness of this ID, although there may be multiple instances.|
6070| componentId | number | No| Unique ID of the custom component where the target node is located. When the above **id** is specified as a string, this property can be used to narrow down the scope, helping you ensure the uniqueness of **id: string** within a certain range.|
6071
6072## PromptAction
6073
6074In the following API examples, you must first use [getPromptAction()](#getpromptaction) in **UIContext** to obtain a **PromptAction** instance, and then call the APIs using the obtained instance.
6075
6076### showToast
6077
6078showToast(options: promptAction.ShowToastOptions): void
6079
6080Shows a toast in the given settings.
6081
6082**Atomic service API**: This API can be used in atomic services since API version 11.
6083
6084**System capability**: SystemCapability.ArkUI.ArkUI.Full
6085
6086**Parameters**
6087
6088| Name    | Type                                      | Mandatory  | Description     |
6089| ------- | ---------------------------------------- | ---- | ------- |
6090| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | Yes   | Toast options.|
6091
6092**Error codes**
6093
6094For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6095
6096| ID | Error Message                              |
6097| ------ | ---------------------------------- |
6098| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6099| 100001 | Internal error. |
6100
6101**Example**
6102
6103<!--code_no_check-->
6104```ts
6105import { PromptAction } from '@kit.ArkUI';
6106import { BusinessError } from '@kit.BasicServicesKit';
6107
6108let promptAction: PromptAction = uiContext.getPromptAction();
6109try {
6110  promptAction.showToast({
6111    message: 'Message Info',
6112    duration: 2000
6113  });
6114} catch (error) {
6115  let message = (error as BusinessError).message;
6116  let code = (error as BusinessError).code;
6117  console.error(`showToast args error code is ${code}, message is ${message}`);
6118};
6119```
6120
6121### openToast<sup>18+</sup>
6122
6123openToast(options: ShowToastOptions): Promise&lt;number&gt;
6124
6125**Atomic service API**: This API can be used in atomic services since API version 18.
6126
6127**System capability**: SystemCapability.ArkUI.ArkUI.Full
6128
6129**Parameters**
6130
6131| Name | Type                                                        | Mandatory| Description          |
6132| ------- | ------------------------------------------------------------ | ---- | -------------- |
6133| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | Yes  | Toast options.|
6134
6135**Return value**
6136
6137| Type            | Description                                |
6138| ---------------- | ------------------------------------ |
6139| Promise&lt;number&gt; | ID of the toast, which is required in **closeToast**.|
6140
6141**Error codes**
6142
6143For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6144
6145| ID| Error Message                                                    |
6146| -------- | ------------------------------------------------------------ |
6147| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
6148| 100001   | Internal error.                                              |
6149
6150**Example**
6151
6152```ts
6153import { PromptAction } from '@kit.ArkUI';
6154import { BusinessError } from '@kit.BasicServicesKit';
6155
6156@Entry
6157@Component
6158struct toastExample {
6159  @State toastId: number = 0;
6160  promptAction: PromptAction = this.getUIContext().getPromptAction()
6161
6162  build() {
6163    Column() {
6164      Button('Open Toast')
6165        .height(100)
6166        .onClick(() => {
6167          this.promptAction.openToast({
6168            message: 'Toast Massage',
6169            duration: 10000,
6170          }).then((toastId: number) => {
6171            this.toastId = toastId;
6172          })
6173            .catch((error: BusinessError) => {
6174              console.error(`openToast error code is ${error.code}, message is ${error.message}`)
6175            })
6176        })
6177      Blank().height(50);
6178      Button('Close Toast')
6179        .height(100)
6180        .onClick(() => {
6181          try {
6182            this.promptAction.closeToast(this.toastId);
6183          } catch (error) {
6184            let message = (error as BusinessError).message;
6185            let code = (error as BusinessError).code;
6186            console.error(`CloseToast error code is ${code}, message is ${message}`);
6187          };
6188        })
6189    }.height('100%').width('100%').justifyContent(FlexAlign.Center)
6190  }
6191}
6192```
6193
6194### closeToast<sup>18+</sup>
6195
6196closeToast(toastId: number): void
6197
6198**Atomic service API**: This API can be used in atomic services since API version 18.
6199
6200**System capability**: SystemCapability.ArkUI.ArkUI.Full
6201
6202**Parameters**
6203
6204| Name | Type  | Mandatory| Description                         |
6205| ------- | ------ | ---- | ----------------------------- |
6206| toastId | number | Yes  | ID of the toast to close, which is returned by **openToast**.|
6207
6208**Error codes**
6209
6210For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6211
6212| ID| Error Message                                                    |
6213| -------- | ------------------------------------------------------------ |
6214| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
6215| 100001   | Internal error.                                              |
6216
6217**Example**
6218
6219See the example for [openToaset18](#opentoast18).
6220
6221### showDialog
6222
6223showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback&lt;promptAction.ShowDialogSuccessResponse&gt;): void
6224
6225Shows a dialog box in the given settings. This API uses an asynchronous callback to return the result.
6226
6227**Atomic service API**: This API can be used in atomic services since API version 11.
6228
6229**System capability**: SystemCapability.ArkUI.ArkUI.Full
6230
6231**Parameters**
6232
6233| Name     | Type                                      | Mandatory  | Description          |
6234| -------- | ---------------------------------------- | ---- | ------------ |
6235| options  | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes   | Dialog box options.|
6236| callback | AsyncCallback&lt;[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)&gt; | Yes   | Callback used to return the dialog box response result.  |
6237
6238**Error codes**
6239
6240For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6241
6242| ID | Error Message                              |
6243| ------ | ---------------------------------- |
6244| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6245| 100001 | Internal error. |
6246
6247**Example**
6248
6249<!--code_no_check-->
6250
6251```ts
6252import { PromptAction } from '@kit.ArkUI';
6253import { BusinessError } from '@kit.BasicServicesKit';
6254
6255let promptAction: PromptAction = uiContext.getPromptAction();
6256try {
6257  promptAction.showDialog({
6258    title: 'showDialog Title Info',
6259    message: 'Message Info',
6260    buttons: [
6261      {
6262        text: 'button1',
6263        color: '#000000'
6264      },
6265      {
6266        text: 'button2',
6267        color: '#000000'
6268      }
6269    ]
6270  }, (err, data) => {
6271    if (err) {
6272      console.error('showDialog err: ' + err);
6273      return;
6274    }
6275    console.info('showDialog success callback, click button: ' + data.index);
6276  });
6277} catch (error) {
6278  let message = (error as BusinessError).message;
6279  let code = (error as BusinessError).code;
6280  console.error(`showDialog args error code is ${code}, message is ${message}`);
6281};
6282```
6283
6284### showDialog
6285
6286showDialog(options: promptAction.ShowDialogOptions): Promise&lt;promptAction.ShowDialogSuccessResponse&gt;
6287
6288Shows a dialog box. This API uses a promise to return the result.
6289
6290**Atomic service API**: This API can be used in atomic services since API version 11.
6291
6292**System capability**: SystemCapability.ArkUI.ArkUI.Full
6293
6294**Parameters**
6295
6296| Name    | Type                                      | Mandatory  | Description    |
6297| ------- | ---------------------------------------- | ---- | ------ |
6298| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes   | Dialog box options.|
6299
6300**Return value**
6301
6302| Type                                      | Description      |
6303| ---------------------------------------- | -------- |
6304| Promise&lt;[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)&gt; | Promise used to return the dialog box response result.|
6305
6306**Error codes**
6307
6308For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6309
6310| ID | Error Message                              |
6311| ------ | ---------------------------------- |
6312| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6313| 100001 | Internal error. |
6314
6315**Example**
6316
6317<!--code_no_check-->
6318```ts
6319import { PromptAction } from '@kit.ArkUI';
6320
6321let promptAction: PromptAction = uiContext.getPromptAction();
6322promptAction.showDialog({
6323  title: 'Title Info',
6324  message: 'Message Info',
6325  buttons: [
6326    {
6327      text: 'button1',
6328      color: '#000000'
6329    },
6330    {
6331      text: 'button2',
6332      color: '#000000'
6333    }
6334  ],
6335})
6336  .then(data => {
6337    console.info('showDialog success, click button: ' + data.index);
6338  })
6339  .catch((err: Error) => {
6340    console.error('showDialog error: ' + err);
6341  })
6342```
6343
6344### showActionMenu<sup>11+</sup>
6345
6346showActionMenu(options: promptAction.ActionMenuOptions, callback: AsyncCallback&lt;[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)&gt;):void
6347
6348Shows an action menu in the given settings. This API uses an asynchronous callback to return the result.
6349
6350**Atomic service API**: This API can be used in atomic services since API version 11.
6351
6352**System capability**: SystemCapability.ArkUI.ArkUI.Full
6353
6354**Parameters**
6355
6356| Name  | Type                                                        | Mandatory| Description              |
6357| -------- | ------------------------------------------------------------ | ---- | ------------------ |
6358| options  | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes  | Action menu options.    |
6359| callback | AsyncCallback&lt;[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)&gt; | Yes  | Callback used to return the action menu response result.|
6360
6361**Error codes**
6362
6363For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6364
6365| ID| Error Message                          |
6366| -------- | ---------------------------------- |
6367| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6368| 100001   | Internal error. |
6369
6370**Example**
6371
6372<!--code_no_check-->
6373```ts
6374import { PromptAction, promptAction  } from '@kit.ArkUI';
6375import { BusinessError } from '@kit.BasicServicesKit';
6376
6377let promptActionF: PromptAction = uiContext.getPromptAction();
6378try {
6379  promptActionF.showActionMenu({
6380    title: 'Title Info',
6381    buttons: [
6382      {
6383        text: 'item1',
6384        color: '#666666'
6385      },
6386      {
6387        text: 'item2',
6388        color: '#000000'
6389      }
6390    ]
6391  }, (err:BusinessError, data:promptAction.ActionMenuSuccessResponse) => {
6392    if (err) {
6393      console.error('showDialog err: ' + err);
6394      return;
6395    }
6396    console.info('showDialog success callback, click button: ' + data.index);
6397  });
6398} catch (error) {
6399  let message = (error as BusinessError).message;
6400  let code = (error as BusinessError).code;
6401  console.error(`showActionMenu args error code is ${code}, message is ${message}`);
6402};
6403```
6404
6405### showActionMenu<sup>(deprecated)</sup>
6406
6407showActionMenu(options: promptAction.ActionMenuOptions, callback: [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)):void
6408
6409Shows an action menu in the given settings. This API uses an asynchronous callback to return the result.
6410
6411This API is deprecated since API version 11. You are advised to use [showActionMenu](#showactionmenu11) instead.
6412
6413**System capability**: SystemCapability.ArkUI.ArkUI.Full
6414
6415**Parameters**
6416
6417| Name  | Type                                                        | Mandatory| Description              |
6418| -------- | ------------------------------------------------------------ | ---- | ------------------ |
6419| options  | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes  | Action menu options.    |
6420| callback | [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse) | Yes  | Callback used to return the action menu response result.|
6421
6422**Error codes**
6423
6424For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6425
6426| ID | Error Message                              |
6427| ------ | ---------------------------------- |
6428| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6429| 100001 | Internal error. |
6430
6431**Example**
6432
6433<!--code_no_check-->
6434```ts
6435import { PromptAction,promptAction  } from '@kit.ArkUI';
6436import { BusinessError } from '@kit.BasicServicesKit';
6437
6438let promptActionF: PromptAction = uiContext.getPromptAction();
6439try {
6440  promptActionF.showActionMenu({
6441    title: 'Title Info',
6442    buttons: [
6443      {
6444        text: 'item1',
6445        color: '#666666'
6446      },
6447      {
6448        text: 'item2',
6449        color: '#000000'
6450      }
6451    ]
6452  }, { index:0 });
6453} catch (error) {
6454  let message = (error as BusinessError).message;
6455  let code = (error as BusinessError).code;
6456  console.error(`showActionMenu args error code is ${code}, message is ${message}`);
6457};
6458```
6459
6460### showActionMenu
6461
6462showActionMenu(options: promptAction.ActionMenuOptions): Promise&lt;promptAction.ActionMenuSuccessResponse&gt;
6463
6464Shows an action menu. This API uses a promise to return the result.
6465
6466**Atomic service API**: This API can be used in atomic services since API version 11.
6467
6468**System capability**: SystemCapability.ArkUI.ArkUI.Full
6469
6470**Parameters**
6471
6472| Name    | Type                                      | Mandatory  | Description     |
6473| ------- | ---------------------------------------- | ---- | ------- |
6474| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes   | Action menu options.|
6475
6476**Return value**
6477
6478| Type                                      | Description     |
6479| ---------------------------------------- | ------- |
6480| Promise&lt;[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)&gt; | Promise used to return the action menu response result.|
6481
6482**Error codes**
6483
6484For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6485
6486| ID | Error Message                              |
6487| ------ | ---------------------------------- |
6488| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6489| 100001 | Internal error. |
6490
6491**Example**
6492
6493<!--code_no_check-->
6494```ts
6495import { PromptAction } from '@kit.ArkUI';
6496
6497let promptAction: PromptAction = uiContext.getPromptAction();
6498promptAction.showActionMenu({
6499  title: 'showActionMenu Title Info',
6500  buttons: [
6501    {
6502      text: 'item1',
6503      color: '#666666'
6504    },
6505    {
6506      text: 'item2',
6507      color: '#000000'
6508    },
6509  ]
6510})
6511  .then(data => {
6512    console.info('showActionMenu success, click button: ' + data.index);
6513  })
6514  .catch((err: Error) => {
6515    console.error('showActionMenu error: ' + err);
6516  })
6517```
6518
6519### openCustomDialog<sup>12+</sup>
6520
6521openCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>, options?: promptAction.BaseDialogOptions): Promise&lt;void&gt;
6522
6523Opens a custom dialog box corresponding to **dialogContent**. This API uses a promise to return the result. The dialog box displayed through this API has its content fully following style settings of **dialogContent**. It is displayed in the same way where **customStyle** is set to **true**. Note that using **[isModal](js-apis-promptAction.md#basedialogoptions11) = true** and **[showInSubWindow](js-apis-promptAction.md#basedialogoptions11) = true** together is not supported.
6524
6525**Atomic service API**: This API can be used in atomic services since API version 12.
6526
6527**System capability**: SystemCapability.ArkUI.ArkUI.Full
6528
6529**Parameters**
6530
6531| Name    | Type                                      | Mandatory  | Description     |
6532| ------- | ---------------------------------------- | ---- | ------- |
6533| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content of the custom dialog box.|
6534| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | No   |   Dialog box style.|
6535
6536**Return value**
6537
6538| Type                                      | Description     |
6539| ---------------------------------------- | ------- |
6540|   Promise&lt;void&gt;           |    Promise used to return the result.|
6541
6542**Error codes**
6543
6544For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6545
6546| ID | Error Message                              |
6547| ------ | ---------------------------------- |
6548| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6549| 103301 | The ComponentContent is incorrect. |
6550| 103302 | Dialog content already exists.|
6551
6552**Example**
6553
6554```ts
6555import { BusinessError } from '@kit.BasicServicesKit';
6556import { ComponentContent } from '@kit.ArkUI';
6557
6558class Params {
6559  text: string = ""
6560
6561  constructor(text: string) {
6562    this.text = text;
6563  }
6564}
6565
6566@Builder
6567function buildText(params: Params) {
6568  Column() {
6569    Text(params.text)
6570      .fontSize(50)
6571      .fontWeight(FontWeight.Bold)
6572      .margin({ bottom: 36 })
6573  }.backgroundColor('#FFF0F0F0')
6574}
6575
6576@Entry
6577@Component
6578struct Index {
6579  @State message: string = "hello"
6580
6581  build() {
6582    Row() {
6583      Column() {
6584        Button("click me")
6585          .onClick(() => {
6586            let uiContext = this.getUIContext();
6587            let promptAction = uiContext.getPromptAction();
6588            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
6589            promptAction.openCustomDialog(contentNode)
6590              .then(() => {
6591                console.info('succeeded')
6592              })
6593              .catch((error: BusinessError) => {
6594                console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`);
6595              })
6596          })
6597      }
6598      .width('100%')
6599      .height('100%')
6600    }
6601    .height('100%')
6602  }
6603}
6604```
6605
6606### openCustomDialogWithController<sup>18+</sup>
6607
6608openCustomDialogWithController\<T extends Object>(dialogContent: ComponentContent\<T>, controller: promptAction.DialogController, options?: promptAction.BaseDialogOptions): Promise&lt;void&gt;
6609
6610Opens a custom dialog box corresponding to **dialogContent**. This API uses a promise to return the result. A dialog box controller can be bound to the custom dialog box, allowing for subsequent control of the dialog box through the controller.
6611
6612The dialog box displayed through this API has its content fully following style settings of **dialogContent**. It is displayed in the same way where **customStyle** is set to **true**.
6613
6614Note that using **[isModal](js-apis-promptAction.md#basedialogoptions11) = true** and **[showInSubWindow](js-apis-promptAction.md#basedialogoptions11) = true** together is not supported.
6615
6616**Atomic service API**: This API can be used in atomic services since API version 18.
6617
6618**System capability**: SystemCapability.ArkUI.ArkUI.Full
6619
6620**Parameters**
6621
6622| Name    | Type                                      | Mandatory  | Description     |
6623| ------- | ---------------------------------------- | ---- | ------- |
6624| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content of the custom dialog box.|
6625| controller | [promptAction.DialogController](js-apis-promptAction.md#dialogcontroller18) | Yes| Controller of the custom dialog box.|
6626| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | No   | Style of the custom dialog box.|
6627
6628**Return value**
6629
6630| Type                                      | Description     |
6631| ---------------------------------------- | ------- |
6632|   Promise&lt;void&gt;           |    Promise used to return the result.|
6633
6634**Error codes**
6635
6636For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6637
6638| ID | Error Message                              |
6639| ------ | ---------------------------------- |
6640| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6641| 103301 | The ComponentContent is incorrect. |
6642| 103302 | Dialog content already exists.|
6643
6644**Example**
6645
6646```ts
6647import { BusinessError } from '@kit.BasicServicesKit';
6648import { ComponentContent, promptAction } from '@kit.ArkUI';
6649
6650class Params {
6651  text: string = ""
6652  dialogController: promptAction.DialogController = new promptAction.DialogController();
6653
6654  constructor(text: string, dialogController: promptAction.DialogController) {
6655    this.text = text;
6656    this.dialogController = dialogController;
6657  }
6658}
6659
6660@Builder
6661function buildText(params: Params) {
6662  Column() {
6663    Text(params.text)
6664      .fontSize(50)
6665      .fontWeight(FontWeight.Bold)
6666      .margin({ bottom: 36 })
6667    Button('Close by DialogController')
6668      .onClick(() => {
6669        if (params.dialogController != undefined) {
6670          params.dialogController.close()
6671        }
6672      })
6673  }.backgroundColor('#FFF0F0F0')
6674}
6675
6676@Entry
6677@ComponentV2
6678struct Index {
6679  @Local message: string = "hello"
6680  private dialogController: promptAction.DialogController = new promptAction.DialogController()
6681
6682  build() {
6683    Row() {
6684      Column() {
6685        Button("click me")
6686          .onClick(() => {
6687            let uiContext = this.getUIContext();
6688            let promptAction = uiContext.getPromptAction();
6689            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText),
6690              new Params(this.message, this.dialogController));
6691            promptAction.openCustomDialogWithController(contentNode, this.dialogController)
6692              .then(() => {
6693                console.info('succeeded')
6694              })
6695              .catch((error: BusinessError) => {
6696                console.error(`OpenCustomDialogWithController args error code is ${error.code}, message is ${error.message}`);
6697              })
6698          })
6699      }
6700      .width('100%')
6701      .height('100%')
6702    }
6703    .height('100%')
6704  }
6705}
6706```
6707
6708### closeCustomDialog<sup>12+</sup>
6709
6710closeCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>): Promise&lt;void&gt;
6711
6712Closes a custom dialog box corresponding to **dialogContent**. This API uses a promise to return the result.
6713
6714**Atomic service API**: This API can be used in atomic services since API version 12.
6715
6716**System capability**: SystemCapability.ArkUI.ArkUI.Full
6717
6718**Parameters**
6719
6720| Name    | Type                                      | Mandatory  | Description     |
6721| ------- | ---------------------------------------- | ---- | ------- |
6722| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content of the custom dialog box.|
6723
6724**Return value**
6725
6726| Type                                      | Description     |
6727| ---------------------------------------- | ------- |
6728|   Promise&lt;void&gt;           |    Promise used to return the result.|
6729
6730**Error codes**
6731
6732For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6733
6734| ID | Error Message                              |
6735| ------ | ---------------------------------- |
6736| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6737| 103301 | The ComponentContent is incorrect. |
6738| 103303 | The ComponentContent cannot be found. |
6739
6740**Example**
6741
6742```ts
6743import { BusinessError } from '@kit.BasicServicesKit';
6744import { ComponentContent } from '@kit.ArkUI';
6745
6746class Params {
6747  text: string = ""
6748
6749  constructor(text: string) {
6750    this.text = text;
6751  }
6752}
6753
6754@Builder
6755function buildText(params: Params) {
6756  Column() {
6757    Text(params.text)
6758      .fontSize(50)
6759      .fontWeight(FontWeight.Bold)
6760      .margin({ bottom: 36 })
6761  }.backgroundColor('#FFF0F0F0')
6762}
6763
6764@Entry
6765@Component
6766struct Index {
6767  @State message: string = "hello"
6768
6769  build() {
6770    Row() {
6771      Column() {
6772        Button("click me")
6773          .onClick(() => {
6774            let uiContext = this.getUIContext();
6775            let promptAction = uiContext.getPromptAction();
6776            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
6777            promptAction.openCustomDialog(contentNode)
6778              .then(() => {
6779                console.info('succeeded')
6780              })
6781              .catch((error: BusinessError) => {
6782                console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`);
6783              })
6784            setTimeout(() => {
6785              promptAction.closeCustomDialog(contentNode)
6786                .then(() => {
6787                  console.info('succeeded')
6788                })
6789                .catch((error: BusinessError) => {
6790                  console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`);
6791                })
6792            }, 2000); // Automatically close the dialog box after 2 seconds.
6793          })
6794      }
6795      .width('100%')
6796      .height('100%')
6797    }
6798    .height('100%')
6799  }
6800}
6801```
6802
6803### updateCustomDialog<sup>12+</sup>
6804
6805updateCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>, options: promptAction.BaseDialogOptions): Promise&lt;void&gt;
6806
6807Updates a custom dialog box corresponding to **dialogContent**. This API uses a promise to return the result.
6808
6809**Atomic service API**: This API can be used in atomic services since API version 12.
6810
6811**System capability**: SystemCapability.ArkUI.ArkUI.Full
6812
6813**Parameters**
6814
6815| Name    | Type                                      | Mandatory  | Description     |
6816| ------- | ---------------------------------------- | ---- | ------- |
6817| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content of the custom dialog box.|
6818| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | Yes   |   Dialog box style. Currently, only **alignment**, **offset**, **autoCancel**, and **maskColor** can be updated.|
6819
6820**Return value**
6821
6822| Type                                      | Description     |
6823| ---------------------------------------- | ------- |
6824|   Promise&lt;void&gt;           |    Promise used to return the result.|
6825
6826**Error codes**
6827
6828For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6829
6830| ID | Error Message                              |
6831| ------ | ---------------------------------- |
6832| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6833| 103301 | The ComponentContent is incorrect. |
6834| 103303 | The ComponentContent cannot be found. |
6835
6836**Example**
6837
6838```ts
6839import { BusinessError } from '@kit.BasicServicesKit';
6840import { ComponentContent } from '@kit.ArkUI';
6841
6842class Params {
6843  text: string = ""
6844
6845  constructor(text: string) {
6846    this.text = text;
6847  }
6848}
6849
6850@Builder
6851function buildText(params: Params) {
6852  Column() {
6853    Text(params.text)
6854      .fontSize(50)
6855      .fontWeight(FontWeight.Bold)
6856      .margin({ bottom: 36 })
6857  }.backgroundColor('#FFF0F0F0')
6858}
6859
6860@Entry
6861@Component
6862struct Index {
6863  @State message: string = "hello"
6864
6865  build() {
6866    Row() {
6867      Column() {
6868        Button("click me")
6869          .onClick(() => {
6870            let uiContext = this.getUIContext();
6871            let promptAction = uiContext.getPromptAction();
6872            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message))
6873            promptAction.openCustomDialog(contentNode)
6874              .then(() => {
6875                console.info('succeeded')
6876              })
6877              .catch((error: BusinessError) => {
6878                console.error(`updateCustomDialog args error code is ${error.code}, message is ${error.message}`)
6879              })
6880
6881            setTimeout(() => {
6882              promptAction.updateCustomDialog(contentNode, { alignment: DialogAlignment.CenterEnd })
6883                .then(() => {
6884                  console.info('succeeded')
6885                })
6886                .catch((error: BusinessError) => {
6887                  console.error(`updateCustomDialog args error code is ${error.code}, message is ${error.message}`)
6888                })
6889            }, 2000); // Automatically update the dialog box position after 2 seconds.
6890          })
6891      }
6892      .width('100%')
6893      .height('100%')
6894    }
6895    .height('100%')
6896  }
6897}
6898```
6899
6900### openCustomDialog<sup>12+</sup>
6901
6902openCustomDialog(options: promptAction.CustomDialogOptions): Promise\<number>
6903
6904Creates and displays a custom dialog box. This API uses a promise to return the dialog box ID, which can be used with **closeCustomDialog**. **isModal = true** and **showInSubWindow = true** cannot be used at the same time.
6905
6906**Atomic service API**: This API can be used in atomic services since API version 12.
6907
6908**System capability**: SystemCapability.ArkUI.ArkUI.Full
6909
6910**Parameters**
6911
6912| Name | Type                                                        | Mandatory| Description              |
6913| ------- | ------------------------------------------------------------ | ---- | ------------------ |
6914| options | [promptAction.CustomDialogOptions](js-apis-promptAction.md#customdialogoptions11) | Yes  | Content of the custom dialog box.|
6915
6916**Return value**
6917
6918| Type               | Description                                   |
6919| ------------------- | --------------------------------------- |
6920| Promise&lt;void&gt; | ID of the custom dialog box, which can be used with **closeCustomDialog**.|
6921
6922**Error codes**
6923
6924For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6925
6926| ID| Error Message                                                    |
6927| -------- | ------------------------------------------------------------ |
6928| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
6929| 100001   | Internal error.                                              |
6930
6931### presentCustomDialog<sup>18+</sup>
6932
6933presentCustomDialog(builder: CustomBuilder \| CustomBuilderWithId, controller?: promptAction.DialogController, options?: promptAction.DialogOptions): Promise\<number>
6934
6935Creates and displays a custom dialog box. This API uses a promise to return the dialog box ID, which can be used with **closeCustomDialog**.
6936
6937The dialog box ID can be included in the dialog box content for related operations. A dialog box controller can be bound to the custom dialog box, allowing for subsequent control of the dialog box through the controller.
6938
6939**isModal = true** and **showInSubWindow = true** cannot be used at the same time.
6940
6941**Atomic service API**: This API can be used in atomic services since API version 18.
6942
6943**System capability**: SystemCapability.ArkUI.ArkUI.Full
6944
6945**Parameters**
6946
6947| Name | Type                                                        | Mandatory| Description              |
6948| ------- | ------------------------------------------------------------ | ---- | ------------------ |
6949| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [CustomBuilderWithId](#custombuilderwithid18) | Yes  | Content of the custom dialog box.|
6950| controller | [promptAction.DialogController](js-apis-promptAction.md#dialogcontroller18) | No| Controller of the custom dialog box.|
6951| options | [promptAction.DialogOptions](js-apis-promptAction.md#dialogoptions18) | No| Style of the custom dialog box.|
6952
6953**Return value**
6954
6955| Type               | Description                                   |
6956| ------------------- | --------------------------------------- |
6957| Promise&lt;number&gt; | Promise used to return the custom dialog box ID.|
6958
6959**Error codes**
6960
6961For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6962
6963| ID| Error Message                                                    |
6964| -------- | ------------------------------------------------------------ |
6965| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
6966| 100001   | Internal error.                                              |
6967
6968**Example**
6969
6970```ts
6971import { BusinessError } from '@kit.BasicServicesKit';
6972import { PromptAction, promptAction } from '@kit.ArkUI';
6973
6974@Entry
6975@ComponentV2
6976struct Index {
6977  @Local message: string = "hello"
6978  private ctx: UIContext = this.getUIContext()
6979  private promptAction: PromptAction = this.ctx.getPromptAction()
6980  private dialogController: promptAction.DialogController = new promptAction.DialogController()
6981
6982  private customDialogComponentId: number = 0
6983  @Builder customDialogComponent() {
6984    Column() {
6985      Text(this.message).fontSize(30)
6986      Row({ space: 10 }) {
6987        Button("Close by DialogId").onClick(() => {
6988          this.promptAction.closeCustomDialog(this.customDialogComponentId)
6989        })
6990        Button("Close by DialogController").onClick(() => {
6991          this.dialogController.close()
6992        })
6993      }
6994    }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
6995  }
6996
6997  @Builder customDialogComponentWithId(dialogId: number) {
6998    Column() {
6999      Text(this.message).fontSize(30)
7000      Row({ space: 10 }) {
7001        Button("Close by DialogId").onClick(() => {
7002          this.promptAction.closeCustomDialog(dialogId)
7003        })
7004        Button("Close by DialogController").onClick(() => {
7005          this.dialogController.close()
7006        })
7007      }
7008    }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
7009  }
7010
7011  build() {
7012    Row() {
7013      Column({ space: 10 }) {
7014        Button('presentCustomDialog')
7015          .fontSize(20)
7016          .onClick(() => {
7017            this.promptAction.presentCustomDialog(() => {
7018              this.customDialogComponent()
7019            }, this.dialogController)
7020              .then((dialogId: number) => {
7021                this.customDialogComponentId = dialogId
7022              })
7023              .catch((err: BusinessError) => {
7024                console.error("presentCustomDialog error: " + err.code + " " + err.message)
7025              })
7026          })
7027        Button('presentCustomDialog with id')
7028          .fontSize(20)
7029          .onClick(() => {
7030            this.promptAction.presentCustomDialog((dialogId: number) => {
7031              this.customDialogComponentWithId(dialogId)
7032            }, this.dialogController)
7033              .catch((err: BusinessError) => {
7034                console.error("presentCustomDialog with id error: " + err.code + " " + err.message)
7035              })
7036          })
7037      }
7038      .width('100%')
7039      .height('100%')
7040    }
7041    .height('100%')
7042  }
7043}
7044```
7045
7046### closeCustomDialog<sup>12+</sup>
7047
7048closeCustomDialog(dialogId: number): void
7049
7050Closes the specified custom dialog box.
7051
7052**Atomic service API**: This API can be used in atomic services since API version 12.
7053
7054**System capability**: SystemCapability.ArkUI.ArkUI.Full
7055
7056**Parameters**
7057
7058| Name  | Type  | Mandatory| Description                            |
7059| -------- | ------ | ---- | -------------------------------- |
7060| dialogId | number | Yes  | ID of the custom dialog box to close. It is returned from **openCustomDialog**.|
7061
7062**Error codes**
7063
7064For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
7065
7066| ID| Error Message                                                    |
7067| -------- | ------------------------------------------------------------ |
7068| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
7069| 100001   | Internal error.                                              |
7070
7071**Example**
7072
7073```ts
7074import { PromptAction } from '@kit.ArkUI';
7075
7076@Entry
7077@Component
7078struct Index {
7079  promptAction: PromptAction = this.getUIContext().getPromptAction()
7080  private customDialogComponentId: number = 0
7081
7082  @Builder
7083  customDialogComponent() {
7084    Column() {
7085      Text('Dialog box').fontSize(30)
7086      Row({ space: 50 }) {
7087        Button("OK").onClick(() => {
7088          this.promptAction.closeCustomDialog(this.customDialogComponentId)
7089        })
7090        Button("Cancel").onClick(() => {
7091          this.promptAction.closeCustomDialog(this.customDialogComponentId)
7092        })
7093      }
7094    }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
7095  }
7096
7097  build() {
7098    Row() {
7099      Column() {
7100        Button("click me")
7101          .onClick(() => {
7102            this.promptAction.openCustomDialog({
7103              builder: () => {
7104                this.customDialogComponent()
7105              },
7106              onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
7107                console.info("reason" + JSON.stringify(dismissDialogAction.reason))
7108                console.log("dialog onWillDismiss")
7109                if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
7110                  dismissDialogAction.dismiss()
7111                }
7112                if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
7113                  dismissDialogAction.dismiss()
7114                }
7115              }
7116            }).then((dialogId: number) => {
7117              this.customDialogComponentId = dialogId
7118            })
7119          })
7120      }
7121      .width('100%')
7122      .height('100%')
7123    }
7124    .height('100%')
7125  }
7126}
7127```
7128
7129### getTopOrder<sup>18+</sup>
7130
7131getTopOrder(): LevelOrder
7132
7133Obtains the order of the topmost dialog box.
7134
7135This API returns the order of the dialog box currently at the top layer. This information can be used to specify the desired order for subsequent dialog boxes.
7136
7137**Atomic service API**: This API can be used in atomic services since API version 18.
7138
7139**System capability**: SystemCapability.ArkUI.ArkUI.Full
7140
7141**Return value**
7142
7143| Type               | Description                                   |
7144| ------------------- | --------------------------------------- |
7145| [LevelOrder](js-apis-promptAction.md#levelorder18) | Order of the topmost dialog box.|
7146
7147**Example**
7148
7149This example shows how to use **getTopOrder** to obtain the order of the dialog box currently at the top layer.
7150
7151```ts
7152import { ComponentContent, PromptAction, LevelOrder, promptAction, UIContext } from '@kit.ArkUI';
7153import { BusinessError } from '@kit.BasicServicesKit';
7154
7155class Params {
7156  text: string = ""
7157  constructor(text: string) {
7158    this.text = text;
7159  }
7160}
7161
7162@Builder
7163function buildText(params: Params) {
7164  Column({ space: 20 }) {
7165    Text(params.text)
7166      .fontSize(50)
7167      .fontWeight(FontWeight.Bold)
7168      .margin({ bottom: 36 })
7169  }.backgroundColor('#FFF0F0F0')
7170}
7171
7172@Entry
7173@Component
7174struct Index {
7175  @State message: string = 'Dialog box'
7176  private ctx: UIContext = this.getUIContext()
7177  private promptAction: PromptAction = this.ctx.getPromptAction()
7178  private contentNode: ComponentContent<Object> =
7179    new ComponentContent(this.ctx, wrapBuilder(buildText), new Params(this.message))
7180
7181  private baseDialogOptions: promptAction.BaseDialogOptions = {
7182    showInSubWindow: false,
7183    levelOrder: LevelOrder.clamp(30.1),
7184  }
7185
7186  build() {
7187    Row() {
7188      Column({ space: 10 }) {
7189        Button('Open Dialog Box')
7190          .fontSize(20)
7191          .onClick(() => {
7192            this.promptAction.openCustomDialog(this.contentNode, this.baseDialogOptions)
7193              .catch((err: BusinessError) => {
7194                console.error("openCustomDialog error: " + err.code + " " + err.message)
7195              })
7196              .then(() => {
7197                let topOrder: LevelOrder = this.promptAction.getTopOrder();
7198                if (topOrder !== undefined) {
7199                  console.error('topOrder: ' + topOrder.getOrder());
7200                }
7201              })
7202          })
7203      }.width('100%')
7204    }.height('100%')
7205  }
7206}
7207```
7208
7209### getBottomOrder<sup>18+</sup>
7210
7211getBottomOrder(): LevelOrder
7212
7213Obtains the order of the bottommost dialog box.
7214
7215This API returns the order of the dialog box currently at the bottom layer. This information can be used to specify the desired order for subsequent dialog boxes.
7216
7217**Atomic service API**: This API can be used in atomic services since API version 18.
7218
7219**System capability**: SystemCapability.ArkUI.ArkUI.Full
7220
7221**Return value**
7222
7223| Type               | Description                                   |
7224| ------------------- | --------------------------------------- |
7225| [LevelOrder](js-apis-promptAction.md#levelorder18) | Order of the topmost dialog box.|
7226
7227**Example**
7228
7229This example shows how to use **getBottomOrder** to obtain the order of the dialog box currently at the bottom layer.
7230
7231```ts
7232import { ComponentContent, PromptAction, LevelOrder, promptAction, UIContext } from '@kit.ArkUI';
7233import { BusinessError } from '@kit.BasicServicesKit';
7234
7235class Params {
7236  text: string = ""
7237  constructor(text: string) {
7238    this.text = text;
7239  }
7240}
7241
7242@Builder
7243function buildText(params: Params) {
7244  Column({ space: 20 }) {
7245    Text(params.text)
7246      .fontSize(50)
7247      .fontWeight(FontWeight.Bold)
7248      .margin({ bottom: 36 })
7249  }.backgroundColor('#FFF0F0F0')
7250}
7251
7252@Entry
7253@Component
7254struct Index {
7255  @State message: string = 'Dialog box'
7256  private ctx: UIContext = this.getUIContext()
7257  private promptAction: PromptAction = this.ctx.getPromptAction()
7258  private contentNode: ComponentContent<Object> =
7259    new ComponentContent(this.ctx, wrapBuilder(buildText), new Params(this.message))
7260
7261  private baseDialogOptions: promptAction.BaseDialogOptions = {
7262    showInSubWindow: false,
7263    levelOrder: LevelOrder.clamp(30.1),
7264  }
7265
7266  build() {
7267    Row() {
7268      Column({ space: 10 }) {
7269        Button('Open Dialog Box')
7270          .fontSize(20)
7271          .onClick(() => {
7272            this.promptAction.openCustomDialog(this.contentNode, this.baseDialogOptions)
7273              .catch((err: BusinessError) => {
7274                console.error("openCustomDialog error: " + err.code + " " + err.message)
7275              })
7276              .then(() => {
7277                let bottomOrder: LevelOrder = this.promptAction.getBottomOrder();
7278                if (bottomOrder !== undefined) {
7279                  console.error('bottomOrder: ' + bottomOrder.getOrder());
7280                }
7281              })
7282          })
7283      }.width('100%')
7284    }.height('100%')
7285  }
7286}
7287```
7288
7289### openPopup<sup>18+</sup>
7290
7291openPopup\<T extends Object>(content: ComponentContent\<T>, target: TargetInfo, options?: PopupCommonOptions): Promise&lt;void&gt;
7292
7293Opens a popup with the specified content. This API uses a promise to return the result.
7294
7295> **NOTE**
7296>
7297> 1. If an invalid **target** is provided, the popup will not be displayed.
7298>
7299> 2. You must maintain the provided **content**, on which [updatePopup](#updatepopup18) and [closePopup](#closepopup18) rely to identify the target popup.
7300>
7301> 3. If your **wrapBuilder** includes other components (such as [Popup](arkui-ts/ohos-arkui-advanced-Popup.md#popup) or [Chip](arkui-ts/ohos-arkui-advanced-Chip.md#chip)), the [ComponentContent](./js-apis-arkui-ComponentContent.md#componentcontent-1) constructor must include four parameters, and the **options** parameter must be **{ nestingBuilderSupported: true }**.
7302
7303**Atomic service API**: This API can be used in atomic services since API version 18.
7304
7305**System capability**: SystemCapability.ArkUI.ArkUI.Full
7306
7307**Parameters**
7308
7309| Name    | Type                                      | Mandatory  | Description     |
7310| ------- | ---------------------------------------- | ---- | ------- |
7311| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed in the popup.|
7312| target | [TargetInfo](#targetinfo18) | Yes| Information about the target component to be bound to the popup.|
7313| options | [PopupCommonOptions](arkui-ts/ts-universal-attributes-popup.md#popupcommonoptions18) | No| Style of the popup.|
7314
7315**Return value**
7316
7317| Type                                      | Description     |
7318| ---------------------------------------- | ------- |
7319|   Promise&lt;void&gt;           |    Promise used to return the result.|
7320
7321**Error codes**
7322
7323For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
7324
7325| ID | Error Message                              |
7326| ------ | ---------------------------------- |
7327| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
7328| 103301 | The ComponentContent is incorrect. |
7329| 103302 | The ComponentContent already exists. |
7330| 103304 | The targetId does not exist. |
7331| 103305 | The node of targetId is not in the component tree. |
7332
7333**Example**
7334
7335```ts
7336import { ComponentContent, FrameNode } from '@kit.ArkUI';
7337import { BusinessError } from '@kit.BasicServicesKit';
7338
7339interface PopupParam {
7340  updateFunc?: () => void
7341  closeFunc?: () => void
7342}
7343
7344export function showPopup(context: UIContext, uniqueId: number, contentNode: ComponentContent<PopupParam>,
7345  popupParam: PopupParam) {
7346  const promptAction = context.getPromptAction();
7347  let frameNode: FrameNode | null = context.getFrameNodeByUniqueId(uniqueId);
7348  let targetId = frameNode?.getFirstChild()?.getUniqueId();
7349  promptAction.openPopup(contentNode, { id: targetId }, {
7350    radius: 16,
7351    enableArrow: true
7352  })
7353    .then(() => {
7354      console.info('openPopup success');
7355    })
7356    .catch((err: BusinessError) => {
7357      console.info('openPopup error: ' + err.code + ' ' + err.message);
7358    })
7359  popupParam.updateFunc = () => {
7360    promptAction.updatePopup(contentNode, {
7361      enableArrow: false
7362    }, true)
7363      .then(() => {
7364        console.info('updatePopup success');
7365      })
7366      .catch((err: BusinessError) => {
7367        console.info('updatePopup error: ' + err.code + ' ' + err.message);
7368      })
7369  }
7370  popupParam.closeFunc = () => {
7371    promptAction.closePopup(contentNode)
7372      .then(() => {
7373        console.info('closePopup success');
7374      })
7375      .catch((err: BusinessError) => {
7376        console.info('closePopup error: ' + err.code + ' ' + err.message);
7377      })
7378  }
7379}
7380
7381@Builder
7382function buildText(param?: PopupParam) {
7383  Column() {
7384    Text('popup')
7385    Button('Update Popup')
7386      .fontSize(20)
7387      .onClick(() => {
7388        param?.updateFunc?.();
7389      })
7390    Button('Close Popup')
7391      .fontSize(20)
7392      .onClick(() => {
7393        param?.closeFunc?.();
7394      })
7395  }
7396}
7397
7398@Entry
7399@Component
7400struct Index {
7401  build() {
7402    Column() {
7403      Button('Open Popup')
7404        .fontSize(20)
7405        .onClick(() => {
7406          let context = this.getUIContext()
7407          const popupParam: PopupParam = {};
7408          const contentNode = new ComponentContent(context, wrapBuilder(buildText), popupParam);
7409          showPopup(context, this.getUniqueId(), contentNode, popupParam)
7410        })
7411    }
7412  }
7413}
7414```
7415
7416### updatePopup<sup>18+</sup>
7417
7418updatePopup\<T extends Object>(content: ComponentContent\<T>, options: PopupCommonOptions, partialUpdate?: boolean ): Promise&lt;void&gt;
7419
7420Updates the style of the popup corresponding to the provided **content**. This API uses a promise to return the result.
7421
7422> **NOTE**
7423>
7424> Updating the following properties is not supported: **showInSubWindow**, **focusable**, **onStateChange**, **onWillDismiss**, and **transition**.
7425>
7426
7427**Atomic service API**: This API can be used in atomic services since API version 18.
7428
7429**System capability**: SystemCapability.ArkUI.ArkUI.Full
7430
7431**Parameters**
7432
7433| Name    | Type                                      | Mandatory  | Description     |
7434| ------- | ---------------------------------------- | ---- | ------- |
7435| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed in the popup.|
7436| options | [PopupCommonOptions](arkui-ts/ts-universal-attributes-popup.md#popupcommonoptions18) | Yes| Style of the popup.<br>**NOTE**<br>Updating the following properties is not supported: **showInSubWindow**, **focusable**, **onStateChange**, **onWillDismiss**, and **transition**.|
7437| partialUpdate | boolean | No| Whether to update the popup in incremental mode.<br>Default value: **false**<br>**NOTE**<br>1. **true**: incremental update, where the specified properties in **options** are updated, and other properties stay at their current value.<br>2. **false**: full update, where all properties except those specified in **options** are restored to default values.|
7438
7439**Return value**
7440
7441| Type                                      | Description     |
7442| ---------------------------------------- | ------- |
7443|   Promise&lt;void&gt;           |    Promise used to return the result.|
7444
7445**Error codes**
7446
7447For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
7448
7449| ID | Error Message                              |
7450| ------ | ---------------------------------- |
7451| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
7452| 103301 | The ComponentContent is incorrect. |
7453| 103303 | The ComponentContent cannot be found. |
7454
7455**Example**
7456
7457See the example for [openPopup](#openpopup18).
7458
7459### closePopup<sup>18+</sup>
7460
7461closePopup\<T extends Object>(content: ComponentContent\<T>): Promise&lt;void&gt;
7462
7463Closes the popup corresponding to the provided **content**. This API uses a promise to return the result.
7464
7465**Atomic service API**: This API can be used in atomic services since API version 18.
7466
7467**System capability**: SystemCapability.ArkUI.ArkUI.Full
7468
7469**Parameters**
7470
7471| Name    | Type                                      | Mandatory  | Description     |
7472| ------- | ---------------------------------------- | ---- | ------- |
7473| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed in the popup.|
7474
7475**Return value**
7476
7477| Type                                      | Description     |
7478| ---------------------------------------- | ------- |
7479|   Promise&lt;void&gt;           |    Promise used to return the result.|
7480
7481**Error codes**
7482
7483For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
7484
7485| ID | Error Message                              |
7486| ------ | ---------------------------------- |
7487| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
7488| 103301 | The ComponentContent is incorrect. |
7489| 103303 | The ComponentContent cannot be found. |
7490
7491**Example**
7492
7493See the example for [openPopup](#openpopup18).
7494
7495### openMenu<sup>18+</sup>
7496
7497openMenu\<T extends Object>(content: ComponentContent\<T>, target: TargetInfo, options?: MenuOptions): Promise&lt;void&gt;
7498
7499Opens a menu with the specified content. This API uses a promise to return the result.
7500
7501> **NOTE**
7502>
7503> 1. If an invalid **target** is provided, the menu will not be displayed.
7504>
7505> 2. You must maintain the provided **content**, on which [updateMenu](#updatemenu18) and [closeMenu](#closemenu18) rely to identify the target menu.
7506>
7507> 3. If your **wrapBuilder** includes other components (such as [Popup](arkui-ts/ohos-arkui-advanced-Popup.md#popup) or [Chip](arkui-ts/ohos-arkui-advanced-Chip.md#chip)), the [ComponentContent](./js-apis-arkui-ComponentContent.md#componentcontent-1) constructor must include four parameters, and the **options** parameter must be **{ nestingBuilderSupported: true }**.
7508
7509**Atomic service API**: This API can be used in atomic services since API version 18.
7510
7511**System capability**: SystemCapability.ArkUI.ArkUI.Full
7512
7513**Parameters**
7514
7515| Name    | Type                                      | Mandatory  | Description     |
7516| ------- | ---------------------------------------- | ---- | ------- |
7517| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed in the menu.|
7518| target | [TargetInfo](#targetinfo18) | Yes| Information about the target component to be bound to the popup.|
7519| options | [MenuOptions](./arkui-ts/ts-universal-attributes-menu.md#menuoptions10) | No| Style of the menu.<br>**NOTE**<br>The **title** property is not effective.<br>The **preview** parameter supports only the **MenuPreviewMode** type.|
7520
7521**Return value**
7522
7523| Type                                      | Description     |
7524| ---------------------------------------- | ------- |
7525|   Promise&lt;void&gt;           |    Promise used to return the result.|
7526
7527**Error codes**
7528
7529For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
7530
7531| ID | Error Message                              |
7532| ------ | ---------------------------------- |
7533| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
7534| 103301 | The ComponentContent is incorrect. |
7535| 103302 | The ComponentContent already exists. |
7536| 103304 | The targetId does not exist. |
7537| 103305 | The node of targetId is not in the component tree. |
7538
7539**Example**
7540
7541```ts
7542import { ComponentContent, FrameNode } from '@kit.ArkUI';
7543
7544export function doSomething(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) {
7545  showMenu(context, uniqueId, contentNode);
7546}
7547
7548@Builder
7549
7550function MyMenu() {
7551  Column() {
7552    Menu(){
7553      MenuItem({ startIcon: $r("app.media.startIcon"), content: "Menu item 1" })
7554      MenuItem({ startIcon: $r("app.media.startIcon"), content: "Menu item 2" })
7555    }
7556  }
7557  .width('80%')
7558  .padding('20lpx')
7559}
7560
7561export function showMenu(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) {
7562
7563  const promptAction = context.getPromptAction();
7564  let frameNode: FrameNode | null = context.getFrameNodeByUniqueId(uniqueId);
7565  let frameNodeTarget = frameNode?.getFirstChild();
7566  frameNodeTarget = frameNodeTarget?.getChild(0);
7567  let targetId = frameNodeTarget?.getUniqueId();
7568
7569  promptAction.openMenu(contentNode, {id: targetId},{
7570    enableArrow: true,
7571  });
7572}
7573
7574@Entry
7575@Component
7576struct Index {
7577  build() {
7578    Column(){
7579      Button('OpenMenu', { type: ButtonType.Normal, stateEffect: true })
7580        .borderRadius('16lpx')
7581        .width('80%')
7582        .margin(10)
7583        .onClick(() => {
7584          let context = this.getUIContext()
7585          const contentNode = new ComponentContent(context, wrapBuilder(MyMenu));
7586          doSomething(context, this.getUniqueId(), contentNode)
7587        })
7588    }
7589  }
7590}
7591```
7592
7593### updateMenu<sup>18+</sup>
7594
7595updateMenu\<T extends Object>(content: ComponentContent\<T>, options: MenuOptions, partialUpdate?: boolean ): Promise&lt;void&gt;
7596
7597Updates the style of the menu corresponding to the provided **content**. This API uses a promise to return the result.
7598
7599> **NOTE**
7600>
7601> Updating the following properties is not supported: **showInSubWindow**, **preview**, **previewAnimationOptions**, **transition**, **onAppear**, **aboutToAppear**, **onDisappear **and **aboutToDisappear**.
7602>
7603
7604**Atomic service API**: This API can be used in atomic services since API version 18.
7605
7606**System capability**: SystemCapability.ArkUI.ArkUI.Full
7607
7608**Parameters**
7609
7610| Name    | Type                                      | Mandatory  | Description     |
7611| ------- | ---------------------------------------- | ---- | ------- |
7612| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed in the menu.|
7613| options | [MenuOptions](./arkui-ts/ts-universal-attributes-menu.md#menuoptions10) | Yes| Style of the menu.<br>**NOTE**<br>Updating the following properties is not supported: **showInSubWindow**, **preview**, **previewAnimationOptions**, **transition**, **onAppear**, **aboutToAppear**, **onDisappear **and **aboutToDisappear**.|
7614| partialUpdate | boolean | No| Whether to update the menu in incremental mode.<br>Default value: **false**<br>**NOTE**<br>1. **true**: incremental update, where the specified properties in **options** are updated, and other properties stay at their current value.<br>2. **false**: full update, where all properties except those specified in **options** are restored to default values.|
7615
7616**Return value**
7617
7618| Type                                      | Description     |
7619| ---------------------------------------- | ------- |
7620|   Promise&lt;void&gt;           |    Promise used to return the result.|
7621
7622**Error codes**
7623
7624For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
7625
7626| ID | Error Message                              |
7627| ------ | ---------------------------------- |
7628| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
7629| 103301 | The ComponentContent is incorrect. |
7630| 103303 | The ComponentContent cannot be found. |
7631
7632**Example**
7633
7634```ts
7635import { ComponentContent, FrameNode } from '@kit.ArkUI';
7636
7637export function doSomething(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) {
7638  showMenu(context, uniqueId, contentNode);
7639}
7640
7641@Builder
7642
7643function MyMenu() {
7644  Column() {
7645    Menu(){
7646      MenuItem({ startIcon: $r("app.media.startIcon"), content: "Menu item 1" })
7647      MenuItem({ startIcon: $r("app.media.startIcon"), content: "Menu item 2" })
7648    }
7649  }
7650  .width('80%')
7651  .padding('20lpx')
7652}
7653
7654export function showMenu(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) {
7655
7656  const promptAction = context.getPromptAction();
7657  let frameNode: FrameNode | null = context.getFrameNodeByUniqueId(uniqueId);
7658  let frameNodeTarget = frameNode?.getFirstChild();
7659  frameNodeTarget = frameNodeTarget?.getChild(0);
7660  let targetId = frameNodeTarget?.getUniqueId();
7661
7662  promptAction.openMenu(contentNode, {id: targetId},{
7663    enableArrow: true,
7664  });
7665
7666  setTimeout(() => {
7667    promptAction.updateMenu(contentNode, {
7668      enableArrow: false,
7669    });
7670  }, 2000)
7671}
7672
7673@Entry
7674@Component
7675struct Index {
7676  build() {
7677    Column(){
7678      Button('OpenMenu', { type: ButtonType.Normal, stateEffect: true })
7679        .borderRadius('16lpx')
7680        .width('80%')
7681        .margin(10)
7682        .onClick(() => {
7683          let context = this.getUIContext()
7684          const contentNode = new ComponentContent(context, wrapBuilder(MyMenu));
7685          doSomething(context, this.getUniqueId(), contentNode)
7686        })
7687    }
7688  }
7689}
7690```
7691
7692### closeMenu<sup>18+</sup>
7693
7694closeMenu\<T extends Object>(content: ComponentContent\<T>): Promise&lt;void&gt;
7695
7696Closes the menu corresponding to the provided content. This API uses a promise to return the result.
7697
7698**Atomic service API**: This API can be used in atomic services since API version 18.
7699
7700**System capability**: SystemCapability.ArkUI.ArkUI.Full
7701
7702**Parameters**
7703
7704| Name    | Type                                      | Mandatory  | Description     |
7705| ------- | ---------------------------------------- | ---- | ------- |
7706| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed in the menu.|
7707
7708**Return value**
7709
7710| Type                                      | Description     |
7711| ---------------------------------------- | ------- |
7712|   Promise&lt;void&gt;           |    Promise used to return the result.|
7713
7714**Error codes**
7715
7716For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
7717
7718| ID | Error Message                              |
7719| ------ | ---------------------------------- |
7720| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
7721| 103301 | The ComponentContent is incorrect. |
7722| 103303 | The ComponentContent cannot be found. |
7723
7724**Example**
7725
7726```ts
7727import { ComponentContent, FrameNode } from '@kit.ArkUI';
7728
7729export function doSomething(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) {
7730  showMenu(context, uniqueId, contentNode);
7731}
7732
7733@Builder
7734
7735function MyMenu() {
7736  Column() {
7737    Menu(){
7738      MenuItem({ startIcon: $r("app.media.startIcon"), content: "Menu item 1" })
7739      MenuItem({ startIcon: $r("app.media.startIcon"), content: "Menu item 2" })
7740    }
7741  }
7742  .width('80%')
7743  .padding('20lpx')
7744}
7745
7746export function showMenu(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) {
7747
7748  const promptAction = context.getPromptAction();
7749  let frameNode: FrameNode | null = context.getFrameNodeByUniqueId(uniqueId);
7750  let frameNodeTarget = frameNode?.getFirstChild();
7751  frameNodeTarget = frameNodeTarget?.getChild(0);
7752  let targetId = frameNodeTarget?.getUniqueId();
7753
7754  promptAction.openMenu(contentNode, {id: targetId},{
7755    enableArrow: true,
7756  });
7757
7758  setTimeout(() => {
7759    promptAction.closeMenu(contentNode);
7760  }, 2000)
7761}
7762
7763@Entry
7764@Component
7765struct Index {
7766  build() {
7767    Column(){
7768      Button('OpenMenu', { type: ButtonType.Normal, stateEffect: true })
7769        .borderRadius('16lpx')
7770        .width('80%')
7771        .margin(10)
7772        .onClick(() => {
7773          let context = this.getUIContext()
7774          const contentNode = new ComponentContent(context, wrapBuilder(MyMenu));
7775          doSomething(context, this.getUniqueId(), contentNode)
7776        })
7777    }
7778  }
7779}
7780```
7781
7782## DragController<sup>11+</sup>
7783In the following API examples, you must first use [getDragController()](js-apis-arkui-UIContext.md#getdragcontroller11) in **UIContext** to obtain a **UIContext** instance, and then call the APIs using the obtained instance.
7784
7785### executeDrag<sup>11+</sup>
7786
7787executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo, callback: AsyncCallback&lt;dragController.DragEventParam&gt;): void
7788
7789Executes dragging, by passing in the object to be dragged and the dragging information. This API uses a callback to return the drag event result.
7790
7791**Atomic service API**: This API can be used in atomic services since API version 12.
7792
7793**System capability**: SystemCapability.ArkUI.ArkUI.Full
7794
7795**Parameters**
7796
7797| Name  | Type                                                        | Mandatory| Description                                                        |
7798| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
7799| custom   | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo) | Yes  | Object to be dragged.<br> **NOTE**<br>The global builder is not supported. If the [Image](arkui-ts/ts-basic-components-image.md) component is used in the builder, enable synchronous loading, that is, set the [syncLoad](arkui-ts/ts-basic-components-image.md#syncload8) attribute of the component to **true**. The builder is used only to generate the image displayed during the current dragging. Changes to the builder, if any, apply to the next dragging, but not to the current dragging.|
7800| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | Yes  | Dragging information.                                                  |
7801| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;[dragController.DragEventParam](js-apis-arkui-dragController.md#drageventparam12)&gt; | Yes  | Callback used to return the result.<br>- **event**: drag event information that includes only the drag result.<br>- **extraParams**: extra information about the drag event.|
7802
7803**Error codes**
7804For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
7805
7806| ID| Error Message     |
7807| -------- | ------------- |
7808| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
7809| 100001   | Internal handling failed. |
7810
7811**Example**
7812
7813```ts
7814import { dragController } from "@kit.ArkUI"
7815import { unifiedDataChannel } from '@kit.ArkData';
7816
7817@Entry
7818@Component
7819struct DragControllerPage {
7820  @Builder DraggingBuilder() {
7821    Column() {
7822      Text("DraggingBuilder")
7823    }
7824    .width(100)
7825    .height(100)
7826    .backgroundColor(Color.Blue)
7827  }
7828
7829  build() {
7830    Column() {
7831      Button('touch to execute drag')
7832        .onTouch((event?:TouchEvent) => {
7833          if(event){
7834            if (event.type == TouchType.Down) {
7835              let text = new unifiedDataChannel.Text()
7836              let unifiedData = new unifiedDataChannel.UnifiedData(text)
7837
7838              let dragInfo: dragController.DragInfo = {
7839                pointerId: 0,
7840                data: unifiedData,
7841                extraParams: ''
7842              }
7843              class tmp{
7844                event:DragEvent|undefined = undefined
7845                extraParams:string = ''
7846              }
7847              let eve:tmp = new tmp()
7848              dragController.executeDrag(()=>{this.DraggingBuilder()}, dragInfo, (err, eve) => {
7849                if(eve.event){
7850                  if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) {
7851                  // ...
7852                  } else if (eve.event.getResult() == DragResult.DRAG_FAILED) {
7853                  // ...
7854                  }
7855                }
7856              })
7857            }
7858          }
7859        })
7860    }
7861  }
7862}
7863```
7864
7865### executeDrag<sup>11+</sup>
7866
7867executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo): Promise&lt;dragController.DragEventParam&gt;
7868
7869Executes dragging, by passing in the object to be dragged and the dragging information. This API uses a promise to return the drag event result.
7870
7871**Atomic service API**: This API can be used in atomic services since API version 12.
7872
7873**System capability**: SystemCapability.ArkUI.ArkUI.Full
7874
7875**Parameters**
7876
7877| Name  | Type                                                        | Mandatory| Description                            |
7878| -------- | ------------------------------------------------------------ | ---- | -------------------------------- |
7879| custom   | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo) | Yes  | Object to be dragged.|
7880| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo)                                        | Yes  | Dragging information.                      |
7881
7882**Return value**
7883
7884| Type                                                        | Description                                                        |
7885| ------------------------------------------------------------ | ------------------------------------------------------------ |
7886| Promise&lt;[dragController.DragEventParam](js-apis-arkui-dragController.md#drageventparam12)&gt; | Callback used to return the result.<br>- **event**: drag event information that includes only the drag result.<br>- **extraParams**: extra information about the drag event.|
7887
7888**Error codes**
7889For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
7890
7891| ID| Error Message     |
7892| -------- | ------------- |
7893| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
7894| 100001   | Internal handling failed. |
7895
7896**Example**
7897
7898```ts
7899import { dragController, componentSnapshot } from "@kit.ArkUI"
7900import { image } from '@kit.ImageKit';
7901import { unifiedDataChannel } from '@kit.ArkData';
7902
7903@Entry
7904@Component
7905struct DragControllerPage {
7906  @State pixmap: image.PixelMap|null = null
7907
7908  @Builder DraggingBuilder() {
7909    Column() {
7910      Text("DraggingBuilder")
7911    }
7912    .width(100)
7913    .height(100)
7914    .backgroundColor(Color.Blue)
7915  }
7916
7917  @Builder PixmapBuilder() {
7918    Column() {
7919      Text("PixmapBuilder")
7920    }
7921    .width(100)
7922    .height(100)
7923    .backgroundColor(Color.Blue)
7924  }
7925
7926  build() {
7927    Column() {
7928      Button('touch to execute drag')
7929        .onTouch((event?:TouchEvent) => {
7930          if(event){
7931            if (event.type == TouchType.Down) {
7932              let text = new unifiedDataChannel.Text()
7933              let unifiedData = new unifiedDataChannel.UnifiedData(text)
7934
7935              let dragInfo: dragController.DragInfo = {
7936                pointerId: 0,
7937                data: unifiedData,
7938                extraParams: ''
7939              }
7940              let pb:CustomBuilder = ():void=>{this.PixmapBuilder()}
7941              componentSnapshot.createFromBuilder(pb).then((pix: image.PixelMap) => {
7942                this.pixmap = pix;
7943                let dragItemInfo: DragItemInfo = {
7944                  pixelMap: this.pixmap,
7945                  builder: ()=>{this.DraggingBuilder()},
7946                  extraInfo: "DragItemInfoTest"
7947                }
7948
7949                class tmp{
7950                  event:DragResult|undefined = undefined
7951                  extraParams:string = ''
7952                }
7953                let eve:tmp = new tmp()
7954                dragController.executeDrag(dragItemInfo, dragInfo)
7955                  .then((eve) => {
7956                    if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) {
7957                      // ...
7958                    } else if (eve.event.getResult() == DragResult.DRAG_FAILED) {
7959                      // ...
7960                    }
7961                  })
7962                  .catch((err:Error) => {
7963                  })
7964              })
7965            }
7966          }
7967        })
7968    }
7969    .width('100%')
7970    .height('100%')
7971  }
7972}
7973```
7974
7975### createDragAction<sup>11+</sup>
7976
7977createDragAction(customArray: Array&lt;CustomBuilder \| DragItemInfo&gt;, dragInfo: dragController.DragInfo): dragController.DragAction
7978
7979Creates a drag action object for initiating drag and drop operations. You need to explicitly specify one or more drag previews, the drag data, and the drag handle point. If a drag operation initiated by an existing drag action object is not completed, no new object can be created, and calling the API will throw an exception. After the lifecycle of the drag action object ends, the callback functions registered on this object become invalid. Therefore, it is necessary to hold this object within a longer scope and replace the old value with a new object returned by **createDragAction** before each drag initiation.
7980
7981**NOTE**<br>You are advised to control the number of drag previews. If too many previews are passed in, the drag efficiency may be affected.
7982
7983**Atomic service API**: This API can be used in atomic services since API version 12.
7984
7985**System capability**: SystemCapability.ArkUI.ArkUI.Full
7986
7987**Parameters**
7988
7989| Name  | Type                                                        | Mandatory| Description                            |
7990| --------      | ------------------------------------------------------------ | ---- | -------------------------------- |
7991| customArray  | Array&lt;[CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo)&gt; | Yes  | Object to be dragged.|
7992| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo)                                | Yes  | Dragging information.                      |
7993
7994**Return value**
7995
7996| Type                                                  | Description              |
7997| ------------------------------------------------------ | ------------------ |
7998| [dragController.DragAction](js-apis-arkui-dragController.md#dragaction11)| **DragAction** object, which is used to subscribe to drag state change events and start the dragging service.|
7999
8000**Error codes**
8001For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
8002
8003| ID| Error Message     |
8004| -------- | ------------- |
8005| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
8006| 100001   | Internal handling failed. |
8007
8008**Example**
80091. In the **EntryAbility.ets** file, obtain the UI context and save it to LocalStorage.
8010```ts
8011import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
8012import { hilog } from '@kit.PerformanceAnalysisKit';
8013import { window, UIContext } from '@kit.ArkUI';
8014
8015let uiContext: UIContext;
8016let localStorage: LocalStorage = new LocalStorage('uiContext');
8017
8018export default class EntryAbility extends UIAbility {
8019  storage: LocalStorage = localStorage;
8020  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
8021    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
8022  }
8023
8024  onDestroy(): void {
8025    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
8026  }
8027
8028  onWindowStageCreate(windowStage: window.WindowStage): void {
8029    // Main window is created, set main page for this ability
8030    let storage: LocalStorage = new LocalStorage();
8031    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
8032
8033    windowStage.loadContent('pages/Index', storage, (err, data) => {
8034      if (err.code) {
8035        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
8036        return;
8037      }
8038      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
8039      windowStage.getMainWindow((err, data) =>
8040      {
8041        if (err.code) {
8042          console.error('Failed to abtain the main window. Cause:' + err.message);
8043          return;
8044        }
8045        let windowClass: window.Window = data;
8046        uiContext = windowClass.getUIContext();
8047        this.storage.setOrCreate<UIContext>('uiContext', uiContext);
8048        // Obtain a UIContext instance.
8049      })
8050    });
8051  }
8052
8053  onWindowStageDestroy(): void {
8054    // Main window is destroyed, release UI related resources
8055    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
8056  }
8057
8058  onForeground(): void {
8059    // Ability has brought to foreground
8060    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
8061  }
8062
8063  onBackground(): void {
8064    // Ability has back to background
8065    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
8066  }
8067}
8068```
80692. Call **LocalStorage.getShared()** to obtain the UI context and then use the **DragController** object obtained to perform subsequent operations.
8070```ts
8071import { dragController, componentSnapshot, UIContext, DragController } from "@kit.ArkUI"
8072import { image } from '@kit.ImageKit';
8073import { unifiedDataChannel } from '@kit.ArkData';
8074
8075let storages = LocalStorage.getShared();
8076
8077@Entry(storages)
8078@Component
8079struct DragControllerPage {
8080  @State pixmap: image.PixelMap|null = null
8081  private dragAction: dragController.DragAction|null = null;
8082  customBuilders:Array<CustomBuilder | DragItemInfo> = new Array<CustomBuilder | DragItemInfo>();
8083  @Builder DraggingBuilder() {
8084    Column() {
8085      Text("DraggingBuilder")
8086    }
8087    .width(100)
8088    .height(100)
8089    .backgroundColor(Color.Blue)
8090  }
8091
8092  build() {
8093    Column() {
8094
8095      Column() {
8096        Text("Test")
8097      }
8098      .width(100)
8099      .height(100)
8100      .backgroundColor(Color.Red)
8101
8102      Button('Drag Multiple Objects').onTouch((event?:TouchEvent) => {
8103        if(event){
8104          if (event.type == TouchType.Down) {
8105            console.info("muti drag Down by listener");
8106            this.customBuilders.push(()=>{this.DraggingBuilder()});
8107            this.customBuilders.push(()=>{this.DraggingBuilder()});
8108            this.customBuilders.push(()=>{this.DraggingBuilder()});
8109            let text = new unifiedDataChannel.Text()
8110            let unifiedData = new unifiedDataChannel.UnifiedData(text)
8111            let dragInfo: dragController.DragInfo = {
8112              pointerId: 0,
8113              data: unifiedData,
8114              extraParams: ''
8115            }
8116            try{
8117              let uiContext: UIContext = storages.get<UIContext>('uiContext') as UIContext;
8118              this.dragAction = uiContext.getDragController().createDragAction(this.customBuilders, dragInfo)
8119              if(!this.dragAction){
8120                console.info("listener dragAction is null");
8121                return
8122              }
8123              this.dragAction.on('statusChange', (dragAndDropInfo)=>{
8124                if (dragAndDropInfo.status == dragController.DragStatus.STARTED) {
8125                  console.info("drag has start");
8126                } else if (dragAndDropInfo.status == dragController.DragStatus.ENDED){
8127                  console.info("drag has end");
8128                  if (!this.dragAction) {
8129                    return
8130                  }
8131                  this.customBuilders.splice(0, this.customBuilders.length)
8132                  this.dragAction.off('statusChange')
8133                }
8134              })
8135              this.dragAction.startDrag().then(()=>{}).catch((err:Error)=>{
8136                console.error("start drag Error:" + err.message);
8137              })
8138            } catch(err) {
8139              console.error("create dragAction Error:" + err.message);
8140            }
8141          }
8142        }
8143      }).margin({top:20})
8144    }
8145  }
8146}
8147```
8148
8149### getDragPreview<sup>11+</sup>
8150
8151getDragPreview(): dragController.DragPreview
8152
8153Obtains the **DragPreview** object, which represents the preview displayed during a drag.
8154
8155**Atomic service API**: This API can be used in atomic services since API version 12.
8156
8157**System capability**: SystemCapability.ArkUI.ArkUI.Full
8158
8159**Return value**
8160
8161| Type                                                        | Description                                                        |
8162| ------------------------------------------------------------ | ------------------------------------------------------------ |
8163| [dragController.DragPreview](js-apis-arkui-dragController.md#dragpreview11) | **DragPreview** object. It provides the API for setting the preview style. It does not work in the **OnDrop** and **OnDragEnd** callbacks.|
8164
8165**Error codes**: For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md).
8166
8167**Example**
8168
8169For details, see [animate](js-apis-arkui-dragController.md#animate11).
8170
8171### setDragEventStrictReportingEnabled<sup>12+</sup>
8172
8173setDragEventStrictReportingEnabled(enable: boolean): void
8174
8175Sets whether the **onDragLeave** callback of the parent component is triggered when an item is dragged from the parent to the child component.
8176
8177**Atomic service API**: This API can be used in atomic services since API version 12.
8178
8179**System capability**: SystemCapability.ArkUI.ArkUI.Full
8180
8181**Parameters**
8182
8183| Name| Type   | Mandatory| Description                                                        |
8184| ------ | ------- | ---- | ------------------------------------------------------------ |
8185| enable | boolean | Yes  | Whether the **onDragLeave** callback of the parent component is triggered when an item is dragged from the parent to the child component. The value **true** means the **onDragLeave** callback of the parent component is triggered, and **false** means the opposite.|
8186
8187**Example**
8188
8189```ts
8190import { UIAbility } from '@kit.AbilityKit';
8191import { window, UIContext } from '@kit.ArkUI';
8192
8193 export default class EntryAbility extends UIAbility {
8194   onWindowStageCreate(windowStage: window.WindowStage): void {
8195       windowStage.loadContent('pages/Index', (err, data) => {
8196         if (err.code) {
8197         return;
8198       }
8199       windowStage.getMainWindow((err, data) => {
8200         if (err.code) {
8201           return;
8202         }
8203         let windowClass: window.Window = data;
8204         let uiContext: UIContext = windowClass.getUIContext();
8205         uiContext.getDragController().setDragEventStrictReportingEnabled(true);
8206     });
8207   });
8208 }
8209}
8210```
8211
8212### cancelDataLoading<sup>15+</sup>
8213
8214cancelDataLoading(key: string): void
8215
8216Cancels the data loading initiated by the [startDataLoading](arkui-ts/ts-universal-events-drag-drop.md#dragevent7) API.
8217
8218**Atomic service API**: This API can be used in atomic services since API version 15.
8219
8220**System capability**: SystemCapability.ArkUI.ArkUI.Full
8221
8222**Parameters**
8223
8224| Name| Type   | Mandatory| Description                                                        |
8225| ------ | ------- | ---- | ------------------------------------------------------------ |
8226| key | string | Yes  | Identifier for the drag data. It is used to distinguish between different drag operations. The key can be obtained through the **startDataLoading** API.|
8227
8228**Error codes**
8229
8230For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Drag Event Error Codes](./errorcode-drag-event.md).
8231
8232| ID| Error Message                                                    |
8233| -------- | ------------------------------------------------------------ |
8234| 401      | Parameter error. |
8235| 190004      | Operation failed. |
8236
8237### notifyDragStartRequest<sup>18+</sup>
8238
8239notifyDragStartRequest(requestStatus: dragController.DragStartRequestStatus): void
8240
8241Controls whether the application can initiate a drag operation.
8242
8243**Atomic service API**: This API can be used in atomic services since API version 18.
8244
8245**System capability**: SystemCapability.ArkUI.ArkUI.Full
8246
8247**Parameters**
8248
8249| Name| Type  | Mandatory| Description                                                       |
8250| ------ | ------- | ---- | ------------------------------------------------------------ |
8251| requestStatus  | [dragController.DragStartRequestStatus](js-apis-arkui-dragController.md#dragstartrequeststatus18)    | Yes |Whether the application can initiate a drag operation.|
8252
8253**Example**
8254
8255```ts
8256import { unifiedDataChannel } from '@kit.ArkData';
8257import { image } from '@kit.ImageKit';
8258import { dragController } from "@kit.ArkUI";
8259
8260// xxx.ets
8261@Entry
8262@Component
8263struct NormalEts {
8264  @State finished: boolean = false
8265  @State timeout1: number = 1
8266  @State pixmap: image.PixelMap | undefined = undefined
8267  @State unifiedData1: unifiedDataChannel.UnifiedData | undefined = undefined
8268  @State previewData: DragItemInfo | undefined = undefined
8269
8270  loadData() {
8271    let timeout = setTimeout(() => {
8272      this.getUIContext().getComponentSnapshot().get("image1", (error: Error, pixmap: image.PixelMap) => {
8273        this.pixmap = pixmap
8274        this.previewData = {
8275          pixelMap: this.pixmap
8276        }
8277      })
8278
8279      let data: unifiedDataChannel.Image = new unifiedDataChannel.Image();
8280      data.imageUri = "app.media.startIcon";
8281      let unifiedData = new unifiedDataChannel.UnifiedData(data);
8282      this.unifiedData1 = unifiedData
8283
8284      this.getUIContext().getDragController().notifyDragStartRequest(dragController.DragStartRequestStatus.READY)
8285    }, 4000);
8286    this.timeout1 = timeout
8287  }
8288
8289
8290    build() {
8291      Column({space: 20}) {
8292        Image($r("app.media.startIcon"))
8293          .width(300)
8294          .height(200)
8295          .id("image1")
8296          .draggable(true)
8297          .dragPreview(this.previewData)
8298          .onPreDrag((status: PreDragStatus) => {
8299            if (status == PreDragStatus.PREPARING_FOR_DRAG_DETECTION) {
8300              this.loadData()
8301            } else {
8302              clearTimeout(this.timeout1);
8303            }
8304          })
8305          .onDragStart((event: DragEvent) => {
8306            if (this.finished == false) {
8307              this.getUIContext().getDragController().notifyDragStartRequest(dragController.DragStartRequestStatus.WAITING)
8308            } else {
8309              event.setData(this.unifiedData1);
8310            }
8311          })
8312          .onDragEnd(()=>{
8313            this.finished = false
8314          })
8315      }
8316      .height(400)
8317      .backgroundColor(Color.Pink)
8318    }
8319}
8320```
8321
8322## OverlayManager<sup>12+</sup>
8323
8324In the following API examples, you must first use [getOverlayManager()](#getoverlaymanager12) in **UIContext** to obtain an **OverlayManager** instance, and then call the APIs using the obtained instance.
8325> **NOTE**
8326>
8327> The nodes on **OverlayManager** are above the page level, but below such components as created through **Dialog**, **Popup**, **Menu**, **BindSheet**, **BindContentCover**, and **Toast**.
8328>
8329> The drawing method inside and outside the safe area of nodes on **OverlayManager** is consistent with that of the page, and the keyboard avoidance method is also the same as that of the page.
8330>
8331> For properties related to **OverlayManager**, you are advised to use AppStorage for global storage across the application to prevent changes in property values when switching pages, which could lead to service errors.
8332
8333### addComponentContent<sup>12+</sup>
8334
8335addComponentContent(content: ComponentContent, index?: number): void
8336
8337Adds a specified **ComponentContent** node to the **OverlayManager**.
8338
8339**Atomic service API**: This API can be used in atomic services since API version 12.
8340
8341**System capability**: SystemCapability.ArkUI.ArkUI.Full
8342
8343**Parameters**
8344
8345| Name    | Type                                      | Mandatory  | Description         |
8346| ------- | ---------------------------------------- | ---- | ----------- |
8347| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | Yes   | Content to add to the new node on the **OverlayManager**.<br>**NOTE**<br> By default, the new node is centered on the page and stacked according to its stacking level.|
8348| index | number | No   | Stacking level of the new node on the **OverlayManager**.<br>**NOTE**<br> If the value is greater than or equal to 0, a larger value indicates a higher stacking level; for those that have the same index, the one that is added at a later time has a higher stacking level.<br> If the value is less than 0 or is **null** or **undefined**, the **ComponentContent** node is added at the highest level by default.<br>If the same **ComponentContent** node is added multiple times, only the last added one is retained.<br>
8349
8350**Example**
8351
8352```ts
8353import { ComponentContent, OverlayManager, router } from '@kit.ArkUI';
8354
8355class Params {
8356  text: string = ""
8357  offset: Position
8358  constructor(text: string, offset: Position) {
8359    this.text = text
8360    this.offset = offset
8361  }
8362}
8363@Builder
8364function builderText(params: Params) {
8365  Column() {
8366    Text(params.text)
8367      .fontSize(30)
8368      .fontWeight(FontWeight.Bold)
8369  }.offset(params.offset)
8370}
8371
8372@Entry
8373@Component
8374struct OverlayExample {
8375  @State message: string = 'ComponentContent';
8376  private uiContext: UIContext = this.getUIContext()
8377  private overlayNode: OverlayManager = this.uiContext.getOverlayManager()
8378  @StorageLink('contentArray') contentArray: ComponentContent<Params>[] = []
8379  @StorageLink('componentContentIndex') componentContentIndex: number = 0
8380  @StorageLink('arrayIndex') arrayIndex: number = 0
8381  @StorageLink("componentOffset") componentOffset: Position = {x: 0, y: 80}
8382
8383  build() {
8384    Column() {
8385      Button("++componentContentIndex: " + this.componentContentIndex).onClick(()=>{
8386        ++this.componentContentIndex
8387      })
8388      Button("--componentContentIndex: " + this.componentContentIndex).onClick(()=>{
8389        --this.componentContentIndex
8390      })
8391      Button("Add ComponentContent" + this.contentArray.length).onClick(()=>{
8392        let componentContent = new ComponentContent(
8393          this.uiContext, wrapBuilder<[Params]>(builderText),
8394          new Params(this.message + (this.contentArray.length), this.componentOffset)
8395        )
8396        this.contentArray.push(componentContent)
8397        this.overlayNode.addComponentContent(componentContent, this.componentContentIndex)
8398      })
8399      Button("++arrayIndex: " + this.arrayIndex).onClick(()=>{
8400        ++this.arrayIndex
8401      })
8402      Button("--arrayIndex: " + this.arrayIndex).onClick(()=>{
8403        --this.arrayIndex
8404      })
8405      Button("Delete ComponentContent" + this.arrayIndex).onClick(()=>{
8406        if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) {
8407          let componentContent = this.contentArray.splice(this.arrayIndex, 1)
8408          this.overlayNode.removeComponentContent(componentContent.pop())
8409        } else {
8410          console.info("Invalid arrayIndex.")
8411        }
8412      })
8413      Button("Show ComponentContent" + this.arrayIndex).onClick(()=>{
8414        if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) {
8415          let componentContent = this.contentArray[this.arrayIndex]
8416          this.overlayNode.showComponentContent(componentContent)
8417        } else {
8418          console.info("Invalid arrayIndex.")
8419        }
8420      })
8421      Button("Hide ComponentContent" + this.arrayIndex).onClick(()=>{
8422        if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) {
8423          let componentContent = this.contentArray[this.arrayIndex]
8424          this.overlayNode.hideComponentContent(componentContent)
8425        } else {
8426          console.info("Invalid arrayIndex.")
8427        }
8428      })
8429      Button("Show All ComponentContent").onClick(()=>{
8430          this.overlayNode.showAllComponentContents()
8431      })
8432      Button("Hide All ComponentContent").onClick(()=>{
8433        this.overlayNode.hideAllComponentContents()
8434      })
8435
8436      Button("Go").onClick(()=>{
8437        router.pushUrl({
8438          url: 'pages/Second'
8439        })
8440      })
8441    }
8442    .width('100%')
8443    .height('100%')
8444  }
8445}
8446```
8447
8448### addComponentContentWithOrder<sup>18+</sup>
8449
8450addComponentContentWithOrder(content: ComponentContent, levelOrder?: LevelOrder): void
8451
8452Creates a floating layer node with the specified display order.
8453
8454This API allows you to define the stacking order of the nodes when they are created.
8455
8456**Atomic service API**: This API can be used in atomic services since API version 18.
8457
8458**System capability**: SystemCapability.ArkUI.ArkUI.Full
8459
8460**Parameters**
8461
8462| Name    | Type                                      | Mandatory  | Description         |
8463| ------- | ---------------------------------------- | ---- | ----------- |
8464| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | Yes   | Content to add to the new node on the **OverlayManager**.<br>**NOTE**<br> By default, the new node is centered on the page and stacked according to its stacking level.|
8465| levelOrder | [LevelOrder](js-apis-promptAction.md#levelorder18) | No   | Display order of the new floating layer node.<br>**NOTE**<br>- Default value: **LevelOrder.clamp(0)**|
8466
8467**Example**
8468
8469This example demonstrates how to use **addComponentContentWithOrder** to create a floating layer node with the specified display order.
8470
8471```ts
8472import { ComponentContent, PromptAction, LevelOrder, UIContext, OverlayManager } from '@kit.ArkUI';
8473
8474class Params {
8475  text: string = ""
8476  offset: Position
8477  constructor(text: string, offset: Position) {
8478    this.text = text
8479    this.offset = offset
8480  }
8481}
8482@Builder
8483function builderText(params: Params) {
8484  Column() {
8485    Text(params.text)
8486      .fontSize(30)
8487      .fontWeight(FontWeight.Bold)
8488  }.offset(params.offset)
8489}
8490
8491@Entry
8492@Component
8493struct Index {
8494  @State message: string = 'Dialog box'
8495  private ctx: UIContext = this.getUIContext()
8496  private promptAction: PromptAction = this.ctx.getPromptAction()
8497  private overlayNode: OverlayManager = this.ctx.getOverlayManager()
8498  @StorageLink('contentArray') contentArray: ComponentContent<Params>[] = []
8499  @StorageLink('componentContentIndex') componentContentIndex: number = 0
8500  @StorageLink('arrayIndex') arrayIndex: number = 0
8501  @StorageLink("componentOffset") componentOffset: Position = {x: 0, y: 80}
8502
8503  build() {
8504    Row() {
8505      Column({ space: 10 }) {
8506        Button('OverlayManager Bottom Overlay')
8507          .fontSize(20)
8508          .onClick(() => {
8509            let componentContent = new ComponentContent(
8510              this.ctx, wrapBuilder<[Params]>(builderText),
8511              new Params(this.message + (this.contentArray.length), this.componentOffset)
8512            )
8513            this.contentArray.push(componentContent)
8514            this.overlayNode.addComponentContentWithOrder(componentContent, LevelOrder.clamp(100.1))
8515            let topOrder: LevelOrder = this.promptAction.getTopOrder();
8516            if (topOrder !== undefined) {
8517              console.error('topOrder: ' + topOrder.getOrder());
8518            }
8519            let bottomOrder: LevelOrder = this.promptAction.getBottomOrder();
8520            if (bottomOrder !== undefined) {
8521              console.error('bottomOrder: ' + bottomOrder.getOrder());
8522            }
8523          })
8524        Button('OverlayManager Top Overlay')
8525          .fontSize(20)
8526          .onClick(() => {
8527            let componentContent = new ComponentContent(
8528              this.ctx, wrapBuilder<[Params]>(builderText),
8529              new Params(this.message + (this.contentArray.length), this.componentOffset)
8530            )
8531            this.contentArray.push(componentContent)
8532            this.overlayNode.addComponentContentWithOrder(componentContent, LevelOrder.clamp(100.2))
8533            let topOrder: LevelOrder = this.promptAction.getTopOrder();
8534            if (topOrder !== undefined) {
8535              console.error('topOrder: ' + topOrder.getOrder());
8536            }
8537            let bottomOrder: LevelOrder = this.promptAction.getBottomOrder();
8538            if (bottomOrder !== undefined) {
8539              console.error('bottomOrder: ' + bottomOrder.getOrder());
8540            }
8541          })
8542      }.width('100%')
8543    }.height('100%')
8544  }
8545}
8546```
8547
8548### removeComponentContent<sup>12+</sup>
8549
8550removeComponentContent(content: ComponentContent): void
8551
8552Removes a specified **ComponentContent** node from the **OverlayManager**
8553
8554**Atomic service API**: This API can be used in atomic services since API version 12.
8555
8556**System capability**: SystemCapability.ArkUI.ArkUI.Full
8557
8558**Parameters**
8559
8560| Name    | Type                                      | Mandatory  | Description         |
8561| ------- | ---------------------------------------- | ---- | ----------- |
8562| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | Yes   | Content to remove from the **OverlayManager**.|
8563
8564**Example**
8565
8566See [addComponentContent Example](#addcomponentcontent12).
8567
8568### showComponentContent<sup>12+</sup>
8569
8570showComponentContent(content: ComponentContent): void
8571
8572Shows a specified **ComponentContent** node on the **OverlayManager**.
8573
8574**Atomic service API**: This API can be used in atomic services since API version 12.
8575
8576**System capability**: SystemCapability.ArkUI.ArkUI.Full
8577
8578**Parameters**
8579
8580| Name    | Type                                      | Mandatory  | Description         |
8581| ------- | ---------------------------------------- | ---- | ----------- |
8582| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | Yes   | Content to show on the **OverlayManager**.|
8583
8584**Example**
8585
8586See [addComponentContent Example](#addcomponentcontent12).
8587
8588### hideComponentContent<sup>12+</sup>
8589
8590hideComponentContent(content: ComponentContent): void
8591
8592Hides a specified **ComponentContent** node on the **OverlayManager**.
8593
8594**Atomic service API**: This API can be used in atomic services since API version 12.
8595
8596**System capability**: SystemCapability.ArkUI.ArkUI.Full
8597
8598**Parameters**
8599
8600| Name    | Type                                      | Mandatory  | Description         |
8601| ------- | ---------------------------------------- | ---- | ----------- |
8602| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | Yes   | Content to hide on the **OverlayManager**.|
8603
8604**Example**
8605
8606See [addComponentContent Example](#addcomponentcontent12).
8607
8608### showAllComponentContents<sup>12+</sup>
8609
8610showAllComponentContents(): void
8611
8612Shows all **ComponentContent** nodes on the **OverlayManager**.
8613
8614**Atomic service API**: This API can be used in atomic services since API version 12.
8615
8616**System capability**: SystemCapability.ArkUI.ArkUI.Full
8617
8618**Example**
8619
8620See [addComponentContent Example](#addcomponentcontent12).
8621
8622### hideAllComponentContents<sup>12+</sup>
8623
8624hideAllComponentContents(): void
8625
8626Hides all **ComponentContent** nodes on the **OverlayManager**.
8627
8628**Atomic service API**: This API can be used in atomic services since API version 12.
8629
8630**System capability**: SystemCapability.ArkUI.ArkUI.Full
8631
8632**Example**
8633
8634See [addComponentContent Example](#addcomponentcontent12).
8635
8636## OverlayManagerOptions<sup>15+</sup>
8637
8638Defines the options used to initialize the [OverlayManager](#overlaymanager12).
8639
8640**Atomic service API**: This API can be used in atomic services since API version 15.
8641
8642**System capability**: SystemCapability.ArkUI.ArkUI.Full
8643
8644| Name            | Type               | Mandatory    | Description                    |
8645| --------------- | ---------------------- | ------------ | --------------------- |
8646| renderRootOverlay   | boolean | No| Whether to render the overlay root node. The value **true** means to render the overlay root node, and **false** means the opposite. The default value is **true**.|
8647| enableBackPressedEvent<sup>18+</sup>   | boolean | No| Whether to enable the ComponentContent under **OverlayManager** to be closed through a swipe gesture. The default value is **false**.|
8648
8649## AtomicServiceBar<sup>11+</sup>
8650
8651In the following API examples, you must first use [getAtomicServiceBar](#getatomicservicebar11) in **UIContext** to obtain an **AtomicServiceBar** instance, and then call the APIs using the obtained instance.
8652> **NOTE**
8653>
8654> Since API version 12, the atomic service menu bar style is changed, and the following APIs are obsolete:
8655
8656### setVisible<sup>11+</sup>
8657
8658setVisible(visible: boolean): void
8659
8660Sets whether the atomic service menu bar is visible.
8661> **NOTE**
8662>
8663> The atomic service menu bar is hidden by default and replaced with a floating button since API version 12; it cannot be changed to visible using this API.
8664
8665**Atomic service API**: This API can be used in atomic services since API version 11.
8666
8667**System capability**: SystemCapability.ArkUI.ArkUI.Full
8668
8669**Parameters**
8670
8671| Name| Type| Mandatory| Description|
8672| ------- | ------- | ------- | ------- |
8673| visible | boolean | Yes| Whether the atomic service menu bar is visible. The value **true** means the atomic service menu bar is visible, and **false** means the opposite.|
8674
8675
8676**Example**
8677
8678```ts
8679import {UIContext, AtomicServiceBar, window } from '@kit.ArkUI';
8680import { hilog } from '@kit.PerformanceAnalysisKit';
8681
8682onWindowStageCreate(windowStage: window.WindowStage) {
8683  // Main window is created, set main page for this ability
8684  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
8685  windowStage.loadContent('pages/Index', (err, data) => {
8686    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
8687    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
8688    if (atomicServiceBar != undefined) {
8689      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
8690      atomicServiceBar.setVisible(false);
8691    } else {
8692      hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
8693    }
8694  });
8695}
8696```
8697
8698### setBackgroundColor<sup>11+</sup>
8699
8700setBackgroundColor(color:Nullable<Color | number | string>): void
8701
8702Sets the background color of the atomic service menu bar.
8703> **NOTE**
8704>
8705> The background of the atomic service menu bar is hidden by default since API version 12; its color cannot be set using this API.
8706
8707**Atomic service API**: This API can be used in atomic services since API version 12.
8708
8709**System capability**: SystemCapability.ArkUI.ArkUI.Full
8710
8711**Parameters**
8712
8713| Name| Type| Mandatory| Description|
8714| ------ | ------ | ------ | ------ |
8715| color | Nullable\<[Color](arkui-ts/ts-appendix-enums.md#color) \| number \| string> | Yes| Background color of the atomic service menu bar. The value **undefined** means to use the default color. A number value indicates a HEX color in RGB or ARGB format, for example, **0xffffff**. A string value indicates a color in RGB or ARGB format, for example, **'#ffffff'**.|
8716
8717**Example**
8718
8719```ts
8720import {UIContext, AtomicServiceBar,window } from '@kit.ArkUI';
8721import { hilog } from '@kit.PerformanceAnalysisKit';
8722onWindowStageCreate(windowStage: window.WindowStage) {
8723  // Main window is created, set main page for this ability
8724  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
8725  windowStage.loadContent('pages/Index', (err, data) => {
8726    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
8727    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
8728    if (atomicServiceBar != undefined) {
8729      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
8730      atomicServiceBar.setBackgroundColor(0x88888888);
8731    } else {
8732      hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
8733    }
8734  });
8735}
8736```
8737
8738### setTitleContent<sup>11+</sup>
8739
8740setTitleContent(content:string): void
8741
8742Sets the title content of the atomic service menu bar.
8743> **NOTE**
8744>
8745> The title of the atomic service menu bar is hidden by default since API version 12; its content cannot be set using this API.
8746
8747**Atomic service API**: This API can be used in atomic services since API version 12.
8748
8749**System capability**: SystemCapability.ArkUI.ArkUI.Full
8750
8751**Parameters**
8752
8753|Name|Type|Mandatory|Description|
8754| ------- | ------- | ------- | ------- |
8755| content | string | Yes| Title content of the atomic service menu bar.|
8756
8757**Example**
8758
8759```ts
8760import {UIContext, AtomicServiceBar,window } from '@kit.ArkUI';
8761import { hilog } from '@kit.PerformanceAnalysisKit';
8762
8763onWindowStageCreate(windowStage: window.WindowStage) {
8764  // Main window is created, set main page for this ability
8765  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
8766  windowStage.loadContent('pages/Index', (err, data) => {
8767    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
8768    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
8769    if (atomicServiceBar != undefined) {
8770      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
8771      atomicServiceBar.setTitleContent('text2');
8772    } else {
8773      hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
8774    }
8775  });
8776}
8777```
8778
8779### setTitleFontStyle<sup>11+</sup>
8780
8781setTitleFontStyle(font:FontStyle):void
8782
8783Sets the font style of the atomic service menu bar.
8784> **NOTE**
8785>
8786> The title of the atomic service menu bar is hidden by default since API version 12; its font style cannot be set using this API.
8787
8788**Atomic service API**: This API can be used in atomic services since API version 12.
8789
8790**System capability**: SystemCapability.ArkUI.ArkUI.Full
8791
8792**Parameters**
8793
8794| Name| Type| Mandatory| Description|
8795| ------ | ------ | ------ | ------ |
8796| font | [FontStyle](arkui-ts/ts-appendix-enums.md#fontstyle) | Yes| Font style of the atomic service menu bar.|
8797
8798**Example**
8799
8800```ts
8801import {UIContext, Font, AtomicServiceBar } from '@kit.ArkUI';
8802import { hilog } from '@kit.PerformanceAnalysisKit';
8803
8804onWindowStageCreate(windowStage: window.WindowStage) {
8805  // Main window is created, set main page for this ability
8806  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
8807  windowStage.loadContent('pages/Index', (err, data) => {
8808    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
8809    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
8810    if (atomicServiceBar != undefined) {
8811      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
8812      atomicServiceBar.setTitleFontStyle(FontStyle.Normal);
8813    } else {
8814      hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
8815    }
8816  });
8817}
8818```
8819
8820### setIconColor<sup>11+</sup>
8821
8822setIconColor(color:Nullable<Color | number | string>): void
8823
8824Sets the color of the atomic service icon.
8825> **NOTE**
8826>
8827> The atomic service menu bar is hidden by default and replaced with a floating button since API version 12; the icon color cannot be changed using this API.
8828
8829**Atomic service API**: This API can be used in atomic services since API version 12.
8830
8831**System capability**: SystemCapability.ArkUI.ArkUI.Full
8832
8833**Parameters**
8834
8835| Name| Type| Mandatory| Description|
8836| ------- | ------- | ------- | ------- |
8837| color | Nullable\<[Color](arkui-ts/ts-appendix-enums.md#color) \| number \| string> | Yes| Color of the atomic service icon. The value **undefined** means to use the default color. A number value indicates a HEX color in RGB or ARGB format, for example, **0xffffff**. A string value indicates a color in RGB or ARGB format, for example, **'#ffffff'**.|
8838
8839
8840**Example**
8841
8842```ts
8843import {UIContext, Font, window } from '@kit.ArkUI';
8844import { hilog } from '@kit.PerformanceAnalysisKit';
8845
8846onWindowStageCreate(windowStage: window.WindowStage) {
8847  // Main window is created, set main page for this ability
8848  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
8849  windowStage.loadContent('pages/Index', (err, data) => {
8850    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
8851    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
8852    if (atomicServiceBar != undefined) {
8853      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
8854      atomicServiceBar.setIconColor(0x12345678);
8855    } else {
8856      hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
8857    }
8858  });
8859}
8860```
8861
8862### getBarRect<sup>15+</sup>
8863
8864getBarRect(): Frame
8865
8866Obtains the layout information of the atomic service menu bar relative to the window.
8867> **NOTE**
8868>
8869> The layout information includes the left and right margins of the atomic service menu bar.
8870
8871**Atomic service API**: This API can be used in atomic services since API version 15.
8872
8873**System capability**: SystemCapability.ArkUI.ArkUI.Full
8874
8875**Return value**
8876
8877| Type               | Description           |
8878| ----------------- | ------------- |
8879| [Frame](./js-apis-arkui-graphics.md#frame) | Size and position of the atomic service menu bar.|
8880
8881**Example**
8882
8883```ts
8884import { AtomicServiceBar } from '@kit.ArkUI';
8885import { hilog } from '@kit.PerformanceAnalysisKit';
8886@Entry
8887@Component
8888struct Index {
8889  build() {
8890    Button("getBarRect")
8891      .onClick(() => {
8892        let uiContext: UIContext = this.getUIContext();
8893        let currentBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
8894        if (currentBar != undefined) {
8895          let rect = currentBar.getBarRect();
8896          hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully. x:' +
8897            rect.x + ' y:' + rect.y + ' width:' + rect.width + ' height:' + rect.height);
8898        } else {
8899          hilog.info(0x0000, 'testTag', 'Get AtomServiceBar failed.');
8900        }
8901      })
8902  }
8903}
8904```
8905
8906## KeyboardAvoidMode<sup>11+</sup>
8907
8908Enumerates the modes in which the layout responds when the keyboard is displayed.
8909
8910**System capability**: SystemCapability.ArkUI.ArkUI.Full
8911
8912| Name  | Value  | Description      |
8913| ------ | ---- | ---------- |
8914| OFFSET | 0    | The layout moves up.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
8915| RESIZE | 1    | The layout is resized.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
8916| OFFSET_WITH_CARET<sup>14+</sup>  | 2 | The layout moves up, and this adjustment also occurs if the caret position in the text box changes.<br>**Atomic service API**: This API can be used in atomic services since API version 14.|
8917| RESIZE_WITH_CARET<sup>14+</sup>  | 3 | The layout is resized, and this adjustment also occurs if the caret position in the text box changes.<br>**Atomic service API**: This API can be used in atomic services since API version 14.|
8918| NONE<sup>14+</sup>  | 4 | The layout is not adjusted to avoid the keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 14.|
8919
8920
8921## FocusController<sup>12+</sup>
8922In the following API examples, you must first use [getFocusController()](js-apis-arkui-UIContext.md#getFocusController12) in **UIContext** to obtain a **UIContext** instance, and then call the APIs using the obtained instance.
8923
8924### clearFocus<sup>12+</sup>
8925
8926clearFocus(): void
8927
8928Clears the focus and forcibly moves the focus to the root container node of the page, causing other nodes in the focus chain to lose focus.
8929
8930**Atomic service API**: This API can be used in atomic services since API version 12.
8931
8932**System capability**: SystemCapability.ArkUI.ArkUI.Full
8933
8934**Example**
8935
8936```ts
8937@Entry
8938@Component
8939struct ClearFocusExample {
8940  @State inputValue: string = ''
8941  @State btColor: Color = Color.Blue
8942
8943  build() {
8944    Column({ space: 20 }) {
8945      Column({ space: 5 }) {
8946        Button('button1')
8947          .width(200)
8948          .height(70)
8949          .fontColor(Color.White)
8950          .focusOnTouch(true)
8951          .backgroundColor(Color.Blue)
8952        Button('button2')
8953          .width(200)
8954          .height(70)
8955          .fontColor(Color.White)
8956          .focusOnTouch(true)
8957          .backgroundColor(this.btColor)
8958          .defaultFocus(true)
8959          .onFocus(() => {
8960            this.btColor = Color.Red
8961          })
8962          .onBlur(() => {
8963            this.btColor = Color.Blue
8964          })
8965        Button('clearFocus')
8966          .width(200)
8967          .height(70)
8968          .fontColor(Color.White)
8969          .backgroundColor(Color.Blue)
8970          .onClick(() => {
8971            this.getUIContext().getFocusController().clearFocus()
8972          })
8973      }
8974    }
8975    .width('100%')
8976    .height('100%')
8977  }
8978}
8979```
8980
8981### requestFocus<sup>12+</sup>
8982
8983requestFocus(key: string): void
8984
8985Sets focus on the specified entity node in the component tree based on the component ID. This API takes effect in the current frame.
8986
8987**Atomic service API**: This API can be used in atomic services since API version 12.
8988
8989**System capability**: SystemCapability.ArkUI.ArkUI.Full
8990
8991**Parameters**
8992
8993| Name| Type| Mandatory| Description|
8994| ------- | ------- | ------- | ------- |
8995| key | string | Yes| [Component ID](arkui-ts/ts-universal-attributes-component-id.md) of the target node.|
8996
8997**Error codes**
8998
8999For details about the error codes, see [Focus Error Codes](errorcode-focus.md).
9000
9001| ID| Error Message                                       |
9002| -------- | ----------------------------------------------- |
9003| 150001   | the component cannot be focused.                |
9004| 150002   | This component has an unfocusable ancestor.     |
9005| 150003   | the component is not on tree or does not exist. |
9006
9007**Example**
9008
9009```ts
9010@Entry
9011@Component
9012struct RequestExample {
9013  @State btColor: Color = Color.Blue
9014
9015  build() {
9016    Column({ space: 20 }) {
9017      Column({ space: 5 }) {
9018        Button('Button')
9019          .width(200)
9020          .height(70)
9021          .fontColor(Color.White)
9022          .focusOnTouch(true)
9023          .backgroundColor(this.btColor)
9024          .onFocus(() => {
9025            this.btColor = Color.Red
9026          })
9027          .onBlur(() => {
9028            this.btColor = Color.Blue
9029          })
9030          .id("testButton")
9031
9032        Divider()
9033          .vertical(false)
9034          .width("80%")
9035          .backgroundColor(Color.Black)
9036          .height(10)
9037
9038        Button('requestFocus')
9039          .width(200)
9040          .height(70)
9041          .onClick(() => {
9042            this.getUIContext().getFocusController().requestFocus("testButton")
9043          })
9044
9045        Button('requestFocus fail')
9046          .width(200)
9047          .height(70)
9048          .onClick(() => {
9049            try {
9050              this.getUIContext().getFocusController().requestFocus("eee")
9051            } catch (error) {
9052              console.error('requestFocus failed code is ' + error.code + ' message is ' + error.message)
9053            }
9054          })
9055      }
9056    }
9057    .width('100%')
9058    .height('100%')
9059  }
9060}
9061```
9062
9063### activate<sup>14+</sup>
9064
9065activate(isActive: boolean, autoInactive?: boolean): void
9066
9067Sets the [focus activation state](../../ui/arkts-common-events-focus-event.md) of this page.
9068
9069**Atomic service API**: This API can be used in atomic services since API version 14.
9070
9071**System capability**: SystemCapability.ArkUI.ArkUI.Full
9072
9073**Parameters**
9074
9075| Name| Type| Mandatory| Description|
9076| ------- | ------- | ------- | ------- |
9077| isActive| boolean| Yes| Whether to enter or exit the focus activation state.<br>The value **true** means to enter the focus activation state, and **false** means to exit the focus activation state.|
9078| autoInactive | boolean | No| Logic for exiting the focus activation state.<br>The value **true** means the focus activation state will be exited automatically when touch or mouse events are triggered, and **false** means the state is controlled solely by API calls.<br>Default value: **true**|
9079
9080```ts
9081// This example demonstrates how to enter the focus activation state when the page loading is completed. In this state, arrow keys can be used for focus navigation.
9082@Entry
9083@Component
9084struct ActivateExample {
9085  aboutToAppear() {
9086    this.getUIContext().getFocusController().activate(true, false)
9087  }
9088
9089  aboutToDisappear() {
9090    this.getUIContext().getFocusController().activate(false)
9091  }
9092
9093  build() {
9094    Row() {
9095      Button('Button1')
9096        .width(200)
9097        .height(70)
9098        .defaultFocus(true)
9099
9100      Button('Button2')
9101        .width(200)
9102        .height(70)
9103
9104      Button('Button3')
9105        .width(200)
9106        .height(70)
9107    }
9108    .padding(10)
9109    .justifyContent(FlexAlign.SpaceBetween)
9110    .width(800)
9111  }
9112}
9113```
9114
9115### setAutoFocusTransfer<sup>14+</sup>
9116
9117setAutoFocusTransfer(isAutoFocusTransfer: boolean): void;
9118
9119Sets whether the new page automatically obtains focus during page switching.
9120
9121**Atomic service API**: This API can be used in atomic services since API version 14.
9122
9123**System capability**: SystemCapability.ArkUI.ArkUI.Full
9124
9125**Parameters**
9126
9127| Name| Type| Mandatory| Description|
9128| ------- | ------- | ------- | ------- |
9129| isAutoFocusTransfer | boolean| Yes| Whether the new page automatically obtains focus during page switching using navigation components or APIs, such as [Router](js-apis-router.md#routerpushurl9), [Navigation](arkui-ts/ts-basic-components-navigation.md#navigation), [Menu](arkui-ts/ts-basic-components-menu.md#menu), [Dialog](arkui-ts/ohos-arkui-advanced-Dialog.md), and [Popup](arkui-ts/ohos-arkui-advanced-Popup.md#popup).<br> The value **true** means the new page automatically obtains focus, and **false** means the opposite. Default value: **true**|
9130
9131```ts
9132@CustomDialog
9133struct CustomDialogExample {
9134  controller?: CustomDialogController
9135  build() {
9136    Column() {
9137      Text('This is a custom dialog box')
9138        .fontSize(30)
9139        .height(100)
9140      Text('The dialog box should not automatically acquire focus')
9141        .fontSize(20)
9142        .height(100)
9143      Button('Close Dialog Box')
9144        .onClick(() => {
9145          if (this.controller != undefined) {
9146            this.getUIContext().getFocusController().setAutoFocusTransfer(true)
9147            this.controller.close()
9148          }
9149        })
9150        .margin(20)
9151    }
9152  }
9153}
9154@Entry
9155@Component
9156struct CustomDialogUser {
9157  dialogController: CustomDialogController | null = new CustomDialogController({
9158    builder: CustomDialogExample({
9159    }),
9160  })
9161  aboutToDisappear() {
9162    this.dialogController = null
9163  }
9164
9165  build() {
9166    Column() {
9167      Button('click me')
9168        .onClick(() => {
9169          if (this.dialogController != null) {
9170            this.getUIContext().getFocusController().setAutoFocusTransfer(false)
9171            this.dialogController.open()
9172          }
9173        }).backgroundColor(0x317aff)
9174    }.width('100%').margin({ top: 5 })
9175  }
9176}
9177```
9178
9179### setKeyProcessingMode<sup>15+</sup>
9180
9181setKeyProcessingMode(mode: KeyProcessingMode): void
9182
9183Sets the mode for processing key events.
9184
9185**Atomic service API**: This API can be used in atomic services since API version 15.
9186
9187**System capability**: SystemCapability.ArkUI.ArkUI.Full
9188
9189**Parameters**
9190
9191| Name| Type| Mandatory| Description|
9192| ------- | ------- | ------- | ------- |
9193| mode | [KeyProcessingMode](./arkui-ts/ts-universal-attributes-focus.md#keyprocessingmode15)| Yes| Mode for processing key events.|
9194
9195```ts
9196
9197// This example demonstrates how to set the focus behavior after the page is loaded.
9198@Entry
9199@Component
9200struct Index {
9201
9202  aboutToAppear() {
9203    this.getUIContext().getFocusController().setKeyProcessingMode(KeyProcessingMode.ANCESTOR_EVENT)
9204  }
9205
9206  build() {
9207    Row() {
9208      Row() {
9209        Button('Button1').id('Button1').onKeyEvent((event) => {
9210          console.log("Button1");
9211          return true
9212        })
9213        Button('Button2').id('Button2').onKeyEvent((event) => {
9214          console.log("Button2");
9215          return true
9216        })
9217      }
9218      .width('100%')
9219      .height('100%')
9220      .id('Row1')
9221      .onKeyEventDispatch((event) => {
9222        let context = this.getUIContext();
9223        context.getFocusController().requestFocus('Button1');
9224        return context.dispatchKeyEvent('Button1', event);
9225      })
9226    }
9227    .height('100%')
9228    .width('100%')
9229    .onKeyEventDispatch((event) => {
9230      if (event.type == KeyType.Down) {
9231        let context = this.getUIContext();
9232        context.getFocusController().requestFocus('Row1');
9233        return context.dispatchKeyEvent('Row1', event);
9234      }
9235      return true;
9236    })
9237  }
9238}
9239```
9240
9241## PointerStyle<sup>12+</sup>
9242
9243type PointerStyle = pointer.PointerStyle
9244
9245Defines the pointer style.
9246
9247**Atomic service API**: This API can be used in atomic services since API version 12.
9248
9249**System capability**: SystemCapability.MultimodalInput.Input.Pointer
9250
9251|Type|Description|
9252| -- | -- |
9253|[pointer.PointerStyle](../apis-input-kit/js-apis-pointer.md#pointerstyle) |Pointer style.|
9254
9255## CursorController<sup>12+</sup>
9256In the following API examples, you must first use [getCursorController()](js-apis-arkui-UIContext.md#getcursorcontroller12) in **UIContext** to obtain a **CursorController** instance, and then call the APIs using the obtained instance.
9257
9258### restoreDefault<sup>12+</sup>
9259
9260restoreDefault(): void
9261
9262Restores the default cursor style.
9263
9264**Atomic service API**: This API can be used in atomic services since API version 12.
9265
9266**System capability**: SystemCapability.ArkUI.ArkUI.Full
9267
9268**Example**
9269In this example, the **restoreDefault** API of **CursorController** is used to restore the cursor style when the cursor moves out of the green frame.
9270
9271```ts
9272import { pointer } from '@kit.InputKit';
9273import { UIContext, CursorController } from '@kit.ArkUI';
9274
9275@Entry
9276@Component
9277struct CursorControlExample {
9278  @State text: string = ''
9279  cursorCustom: CursorController = this.getUIContext().getCursorController();
9280
9281  build() {
9282    Column() {
9283      Row().height(200).width(200).backgroundColor(Color.Green).position({x: 150 ,y:70})
9284        .onHover((flag) => {
9285          if (flag) {
9286            this.cursorCustom.setCursor(pointer.PointerStyle.EAST)
9287          } else {
9288            console.info("restoreDefault");
9289            this.cursorCustom.restoreDefault();
9290          }
9291        })
9292    }.width('100%')
9293  }
9294}
9295```
9296![cursor-restoreDefault](figures/cursor-restoreDefault.gif)
9297
9298### setCursor<sup>12+</sup>
9299
9300setCursor(value: PointerStyle): void
9301
9302Sets the cursor style.
9303
9304**Atomic service API**: This API can be used in atomic services since API version 12.
9305
9306**System capability**: SystemCapability.ArkUI.ArkUI.Full
9307
9308**Parameters**
9309
9310| Name    | Type                                      | Mandatory  | Description     |
9311| ------- | ---------------------------------------- | ---- | ------- |
9312| value | [PointerStyle](#pointerstyle12) | Yes   | Cursor style.|
9313
9314**Example**
9315In this example, the **setCursor** API of **CursorController** is used to set the cursor style to **PointerStyle.WEST** when the cursor moves into the blue frame.
9316
9317```ts
9318import { pointer } from '@kit.InputKit';
9319import { UIContext, CursorController } from '@kit.ArkUI';
9320
9321@Entry
9322@Component
9323struct CursorControlExample {
9324  @State text: string = ''
9325  cursorCustom: CursorController = this.getUIContext().getCursorController();
9326
9327  build() {
9328    Column() {
9329      Row().height(200).width(200).backgroundColor(Color.Blue).position({x: 100 ,y:70})
9330        .onHover((flag) => {
9331          if (flag) {
9332            this.cursorCustom.setCursor(pointer.PointerStyle.WEST)
9333          } else {
9334            this.cursorCustom.restoreDefault();
9335          }
9336        })
9337    }.width('100%')
9338  }
9339}
9340```
9341![cursor-setCursor](figures/cursor-setCursor.gif)
9342
9343## ContextMenuController<sup>12+</sup>
9344In the following API examples, you must first use [getContextMenuController()](js-apis-arkui-UIContext.md#getcontextmenucontroller12) in **UIContext** to obtain a **ContextMenuController** instance, and then call the APIs using the obtained instance.
9345
9346### close<sup>12+</sup>
9347
9348close(): void
9349
9350Closes this menu.
9351
9352**Atomic service API**: This API can be used in atomic services since API version 12.
9353
9354**System capability**: SystemCapability.ArkUI.ArkUI.Full
9355
9356**Example**
9357This example triggers the **close** API of **ContextMenuController** by a time to close the menu.
9358
9359```ts
9360import { ContextMenuController } from '@kit.ArkUI';
9361
9362@Entry
9363@Component
9364struct Index {
9365  menu: ContextMenuController = this.getUIContext().getContextMenuController();
9366
9367  @Builder MenuBuilder() {
9368    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
9369      Button('Test ContextMenu1 Close')
9370      Divider().strokeWidth(2).margin(5).color(Color.Black)
9371      Button('Test ContextMenu2')
9372      Divider().strokeWidth(2).margin(5).color(Color.Black)
9373      Button('Test ContextMenu3')
9374    }
9375    .width(200)
9376    .height(160)
9377  }
9378
9379  build() {
9380    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
9381      Button("Start Timer").onClick(()=>
9382      {
9383        setTimeout(() => {
9384          this.menu.close();
9385        }, 10000);
9386      })
9387
9388      Column() {
9389        Text("Test ContextMenu close")
9390          .fontSize(20)
9391          .width('100%')
9392          .height(500)
9393          .backgroundColor(0xAFEEEE)
9394          .textAlign(TextAlign.Center)
9395      }
9396      .bindContextMenu(this.MenuBuilder, ResponseType.LongPress)
9397    }
9398    .width('100%')
9399    .height('100%')
9400  }
9401}
9402```
9403
9404![contextMenuController_close](figures/contextMenuController_close.gif)
9405
9406## MeasureUtils<sup>12+</sup>
9407
9408In the following API examples, you must first use [getMeasureUtils()](js-apis-arkui-UIContext.md#getmeasureutils12) in **UIContext** to obtain a **MeasureUtils** instance, and then call the APIs using the obtained instance.
9409
9410### measureText<sup>12+</sup>
9411
9412measureText(options: MeasureOptions): number
9413
9414Measures the width of the given single-line text.
9415
9416**Atomic service API**: This API can be used in atomic services since API version 12.
9417
9418**System capability**: SystemCapability.ArkUI.ArkUI.Full
9419
9420**Parameters**
9421
9422| Name    | Type                             | Mandatory  | Description       |
9423| ------- | ------------------------------- | ---- | --------- |
9424| options | [MeasureOptions](js-apis-measure.md#measureoptions) | Yes   | Options of the target text.|
9425
9426**Return value**
9427
9428| Type         | Description      |
9429| ------------  | --------- |
9430| number        | Text width.<br>**NOTE**<br>Unit: px|
9431
9432
9433**Example**
9434This example uses the **measureText** API of **MeasureUtils** to obtain the width of the **"Hello World"** text.
9435
9436```ts
9437import { MeasureUtils } from '@kit.ArkUI';
9438
9439@Entry
9440@Component
9441struct Index {
9442  @State uiContext: UIContext = this.getUIContext();
9443  @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils();
9444  @State textWidth: number = this.uiContextMeasure.measureText({
9445    textContent: "Hello World",
9446    fontSize: '50px'
9447  })
9448
9449  build() {
9450    Row() {
9451      Column() {
9452        Text(`The width of 'Hello World': ${this.textWidth}`)
9453      }
9454      .width('100%')
9455    }
9456    .height('100%')
9457  }
9458}
9459```
9460
9461### measureTextSize<sup>12+</sup>
9462
9463measureTextSize(options: MeasureOptions): SizeOptions
9464
9465Measures the width and height of the given single-line text.
9466
9467**Atomic service API**: This API can be used in atomic services since API version 12.
9468
9469**System capability**: SystemCapability.ArkUI.ArkUI.Full
9470
9471**Parameters**
9472
9473| Name    | Type                             | Mandatory  | Description       |
9474| ------- | ------------------------------- | ---- | --------- |
9475| options | [MeasureOptions](js-apis-measure.md#measureoptions) | Yes   | Options of the target text.|
9476
9477**Return value**
9478
9479| Type         | Description      |
9480| ------------  | --------- |
9481| [SizeOption](arkui-ts/ts-types.md#sizeoptions)   | Width and height of the text.<br>**NOTE**<br> The return values for text width and height are both in px.|
9482
9483
9484**Example**
9485This example uses the **measureTextSize** API of **MeasureUtils** to obtain the width and height of the **"Hello World"** text.
9486
9487```ts
9488import { MeasureUtils } from '@kit.ArkUI';
9489
9490@Entry
9491@Component
9492struct Index {
9493  @State uiContext: UIContext = this.getUIContext();
9494  @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils();
9495  textSize : SizeOptions = this.uiContextMeasure.measureTextSize({
9496    textContent: "Hello World",
9497    fontSize: '50px'
9498  })
9499  build() {
9500    Row() {
9501      Column() {
9502        Text(`The width of 'Hello World': ${this.textSize.width}`)
9503        Text(`The height of 'Hello World': ${this.textSize.height}`)
9504      }
9505      .width('100%')
9506    }
9507    .height('100%')
9508  }
9509}
9510```
9511
9512## ComponentSnapshot<sup>12+</sup>
9513
9514In the following API examples, you must first use [getComponentSnapshot()](js-apis-arkui-UIContext.md#getcomponentsnapshot12) in **UIContext** to obtain a **ComponentSnapshot** instance, and then call the APIs using the obtained instance.
9515
9516### get<sup>12+</sup>
9517
9518get(id: string, callback: AsyncCallback<image.PixelMap>, options?: componentSnapshot.SnapshotOptions): void
9519
9520Obtains the snapshot of a component that has been loaded. This API uses an asynchronous callback to return the result.
9521
9522> **NOTE**
9523>
9524> The snapshot captures content rendered in the last frame. If a snapshot is taken at the same time as the component triggers an update, the updated rendering content will not be captured in the snapshot; instead, the snapshot will return the rendering content from the previous frame.
9525
9526**Atomic service API**: This API can be used in atomic services since API version 12.
9527
9528**System capability**: SystemCapability.ArkUI.ArkUI.Full
9529
9530**Parameters**
9531
9532| Name  | Type                                                        | Mandatory| Description                                                        |
9533| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
9534| id       | string                                                       | Yes  | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.|
9535| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | Yes  | Callback used to return the result.                                        |
9536| options<sup>12+</sup>       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | No   | Custom settings of the snapshot.|
9537
9538**Error codes**
9539
9540For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
9541
9542| ID| Error Message                                                    |
9543| -------- | ------------------------------------------------------------ |
9544| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
9545| 100001   | Invalid ID.                                                  |
9546
9547**Example**
9548
9549```ts
9550import { image } from '@kit.ImageKit';
9551import { UIContext } from '@kit.ArkUI';
9552
9553@Entry
9554@Component
9555struct SnapshotExample {
9556  @State pixmap: image.PixelMap | undefined = undefined
9557  uiContext: UIContext = this.getUIContext();
9558  build() {
9559    Column() {
9560      Row() {
9561        Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5)
9562        Image($r('app.media.img')).autoResize(true).width(150).height(150).margin(5).id("root")
9563      }
9564      Button("click to generate UI snapshot")
9565        .onClick(() => {
9566          this.uiContext.getComponentSnapshot().get("root", (error: Error, pixmap: image.PixelMap) => {
9567            if (error) {
9568              console.error("error: " + JSON.stringify(error))
9569              return;
9570            }
9571            this.pixmap = pixmap
9572          }, {scale : 2, waitUntilRenderFinished : true})
9573        }).margin(10)
9574    }
9575    .width('100%')
9576    .height('100%')
9577    .alignItems(HorizontalAlign.Center)
9578  }
9579}
9580```
9581
9582### get<sup>12+</sup>
9583
9584get(id: string, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
9585
9586Obtains the snapshot of a component that has been loaded. This API uses a promise to return the result.
9587
9588> **NOTE**
9589>
9590> The snapshot captures content rendered in the last frame. If a snapshot is taken at the same time as the component triggers an update, the updated rendering content will not be captured in the snapshot; instead, the snapshot will return the rendering content from the previous frame.
9591
9592**Atomic service API**: This API can be used in atomic services since API version 12.
9593
9594**System capability**: SystemCapability.ArkUI.ArkUI.Full
9595
9596**Parameters**
9597
9598| Name| Type  | Mandatory| Description                                                        |
9599| ------ | ------ | ---- | ------------------------------------------------------------ |
9600| id     | string | Yes  | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.|
9601| options<sup>12+</sup>       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | No   | Custom settings of the snapshot.|
9602
9603**Return value**
9604
9605| Type                                                        | Description            |
9606| ------------------------------------------------------------ | ---------------- |
9607| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | Promise used to return the result.|
9608
9609**Error codes**
9610
9611For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
9612
9613| ID| Error Message                                                    |
9614| -------- | ------------------------------------------------------------ |
9615| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
9616| 100001   | Invalid ID.                                                  |
9617
9618**Example**
9619
9620```ts
9621import { image } from '@kit.ImageKit';
9622import { UIContext } from '@kit.ArkUI';
9623
9624@Entry
9625@Component
9626struct SnapshotExample {
9627  @State pixmap: image.PixelMap | undefined = undefined
9628  uiContext: UIContext = this.getUIContext();
9629
9630  build() {
9631    Column() {
9632      Row() {
9633        Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5)
9634        Image($r('app.media.icon')).autoResize(true).width(150).height(150).margin(5).id("root")
9635      }
9636      Button("click to generate UI snapshot")
9637        .onClick(() => {
9638          this.uiContext.getComponentSnapshot()
9639            .get("root", {scale : 2, waitUntilRenderFinished : true})
9640            .then((pixmap: image.PixelMap) => {
9641              this.pixmap = pixmap
9642            })
9643            .catch((err: Error) => {
9644              console.error("error: " + err)
9645            })
9646        }).margin(10)
9647    }
9648    .width('100%')
9649    .height('100%')
9650    .alignItems(HorizontalAlign.Center)
9651  }
9652}
9653```
9654
9655### createFromBuilder<sup>12+</sup>
9656
9657createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): void
9658
9659Renders a custom component from [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) in the background of the application and outputs its snapshot. This API uses an asynchronous callback to return the result.
9660> **NOTE**
9661>
9662> Due to the need to wait for the component to be built and rendered, there is a delay of up to 500 ms in the callback for offscreen snapshot capturing.
9663>
9664> If a component is on a time-consuming task, for example, an [Image](arkui-ts/ts-basic-components-image.md) or [Web](../apis-arkweb/ts-basic-components-web.md) component that is loading online images, its loading may be still in progress when this API is called. In this case, the output snapshot does not represent the component in the way it looks when the loading is successfully completed.
9665
9666**Atomic service API**: This API can be used in atomic services since API version 12.
9667
9668**System capability**: SystemCapability.ArkUI.ArkUI.Full
9669
9670**Parameters**
9671
9672| Name  | Type                                                        | Mandatory| Description                                                        |
9673| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
9674| builder  | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8)         | Yes  | Builder for the custom component.<br>**NOTE**<br>The global builder is not supported.     |
9675| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | Yes  | Callback used to return the result. The coordinates and size of the offscreen component's drawing area can be obtained through the callback.|
9676| delay<sup>12+</sup>   | number | No   | Delay time for triggering the screenshot command. When the layout includes an **Image** component, it is necessary to set a delay time to allow the system to decode the image resources. The decoding time is subject to the resource size. In light of this, whenever possible, use pixel map resources that do not require decoding.<br> When pixel map resources are used or when **syncload** to **true** for the **Image** component, you can set **delay** to **0** to forcibly capture snapshots without waiting. This delay time does not refer to the time from the API call to the return: As the system needs to temporarily construct the passed-in **builder** offscreen, the return time is usually longer than this delay.<br>**NOTE**<br>In the **builder** passed in, state variables should not be used to control the construction of child components. If they are used, they should not change when the API is called, so as to avoid unexpected snapshot results.<br> Default value: **300**<br> Unit: ms<br> Value range: [0, +∞). If the value is less than 0, the default value is used.|
9677| checkImageStatus<sup>12+</sup>  | boolean | No   | Whether to check the image decoding status before taking a snapshot. If the value is **true**, the system checks whether all **Image** components have been decoded before taking the snapshot. If the check is not completed, the system aborts the snapshot and returns an exception.<br>Default value: **false**|
9678| options<sup>12+</sup>       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | No   | Custom settings of the snapshot.|
9679
9680**Error codes**
9681
9682For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
9683
9684| ID| Error Message                                                    |
9685| -------- | ------------------------------------------------------------ |
9686| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
9687| 100001   | The builder is not a valid build function.                   |
9688| 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. |
9689
9690**Example**
9691
9692```ts
9693import { image } from '@kit.ImageKit';
9694import { UIContext } from '@kit.ArkUI';
9695
9696@Entry
9697@Component
9698struct ComponentSnapshotExample {
9699  @State pixmap: image.PixelMap | undefined = undefined
9700  uiContext: UIContext = this.getUIContext();
9701  @Builder
9702  RandomBuilder() {
9703    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
9704      Text('Test menu item 1')
9705        .fontSize(20)
9706        .width(100)
9707        .height(50)
9708        .textAlign(TextAlign.Center)
9709      Divider().height(10)
9710      Text('Test menu item 2')
9711        .fontSize(20)
9712        .width(100)
9713        .height(50)
9714        .textAlign(TextAlign.Center)
9715    }
9716    .width(100)
9717    .id("builder")
9718  }
9719
9720  build() {
9721    Column() {
9722      Button("click to generate UI snapshot")
9723        .onClick(() => {
9724          this.uiContext.getComponentSnapshot().createFromBuilder(() => {
9725            this.RandomBuilder()
9726          },
9727            (error: Error, pixmap: image.PixelMap) => {
9728              if (error) {
9729                console.error("error: " + JSON.stringify(error))
9730                return;
9731              }
9732              this.pixmap = pixmap
9733            }, 320, true, {scale : 2, waitUntilRenderFinished : true})
9734        })
9735      Image(this.pixmap)
9736        .margin(10)
9737        .height(200)
9738        .width(200)
9739        .border({ color: Color.Black, width: 2 })
9740    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
9741  }
9742}
9743```
9744
9745### createFromBuilder<sup>12+</sup>
9746
9747createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
9748
9749Renders a custom component from [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) in the background of the application and outputs its snapshot. This API uses a promise to return the result.
9750
9751> **NOTE**
9752>
9753> Due to the need to wait for the component to be built and rendered, there is a delay of up to 500 ms in the callback for offscreen snapshot capturing.
9754>
9755> If a component is on a time-consuming task, for example, an [Image](arkui-ts/ts-basic-components-image.md) or [Web](../apis-arkweb/ts-basic-components-web.md) component that is loading online images, its loading may be still in progress when this API is called. In this case, the output snapshot does not represent the component in the way it looks when the loading is successfully completed.
9756
9757**Atomic service API**: This API can be used in atomic services since API version 12.
9758
9759**System capability**: SystemCapability.ArkUI.ArkUI.Full
9760
9761**Parameters**
9762
9763| Name | Type                                                | Mandatory| Description                                                   |
9764| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- |
9765| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | Yes  | Builder for the custom component.<br>**NOTE**<br>The global builder is not supported.|
9766| delay<sup>12+</sup>   | number | No   | Delay time for triggering the screenshot command. When the layout includes an **Image** component, it is necessary to set a delay time to allow the system to decode the image resources. The decoding time is subject to the resource size. In light of this, whenever possible, use pixel map resources that do not require decoding.<br> When pixel map resources are used or when **syncload** to **true** for the **Image** component, you can set **delay** to **0** to forcibly capture snapshots without waiting. This delay time does not refer to the time from the API call to the return: As the system needs to temporarily construct the passed-in **builder** offscreen, the return time is usually longer than this delay.<br>**NOTE**<br>In the **builder** passed in, state variables should not be used to control the construction of child components. If they are used, they should not change when the API is called, so as to avoid unexpected snapshot results.<br> Default value: **300**<br> Unit: ms|
9767| checkImageStatus<sup>12+</sup>  | boolean | No   | Whether to check the image decoding status before taking a snapshot. If the value is **true**, the system checks whether all **Image** components have been decoded before taking the snapshot. If the check is not completed, the system aborts the snapshot and returns an exception.<br>Default value: **false**|
9768| options<sup>12+</sup>       | [SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)           | No   | Custom settings of the snapshot.|
9769
9770**Return value**
9771
9772| Type                                                        | Description            |
9773| ------------------------------------------------------------ | ---------------- |
9774| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | Promise used to return the result.|
9775
9776**Error codes**
9777
9778For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
9779
9780| ID| Error Message                                                    |
9781| -------- | ------------------------------------------------------------ |
9782| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
9783| 100001   | The builder is not a valid build function.                   |
9784| 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. |
9785
9786**Example**
9787
9788```ts
9789import { image } from '@kit.ImageKit';
9790import { UIContext } from '@kit.ArkUI';
9791
9792@Entry
9793@Component
9794struct ComponentSnapshotExample {
9795  @State pixmap: image.PixelMap | undefined = undefined
9796  uiContext: UIContext = this.getUIContext();
9797  @Builder
9798  RandomBuilder() {
9799    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
9800      Text('Test menu item 1')
9801        .fontSize(20)
9802        .width(100)
9803        .height(50)
9804        .textAlign(TextAlign.Center)
9805      Divider().height(10)
9806      Text('Test menu item 2')
9807        .fontSize(20)
9808        .width(100)
9809        .height(50)
9810        .textAlign(TextAlign.Center)
9811    }
9812    .width(100)
9813    .id("builder")
9814  }
9815  build() {
9816    Column() {
9817      Button("click to generate UI snapshot")
9818        .onClick(() => {
9819          this.uiContext.getComponentSnapshot()
9820            .createFromBuilder(() => {
9821              this.RandomBuilder()
9822            }, 320, true, {scale : 2, waitUntilRenderFinished : true})
9823            .then((pixmap: image.PixelMap) => {
9824              this.pixmap = pixmap
9825            })
9826            .catch((err: Error) => {
9827              console.error("error: " + err)
9828            })
9829        })
9830      Image(this.pixmap)
9831        .margin(10)
9832        .height(200)
9833        .width(200)
9834        .border({ color: Color.Black, width: 2 })
9835    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
9836  }
9837}
9838```
9839
9840### getSync<sup>12+</sup>
9841
9842getSync(id: string, options?: componentSnapshot.SnapshotOptions): image.PixelMap
9843
9844Obtains the snapshot of a component that has been loaded. This API synchronously waits for the snapshot to complete and returns a [PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) object.
9845
9846> **NOTE**
9847>
9848> The snapshot captures content rendered in the last frame. If a snapshot is taken at the same time as the component triggers an update, the updated rendering content will not be captured in the snapshot; instead, the snapshot will return the rendering content from the previous frame.
9849
9850**Atomic service API**: This API can be used in atomic services since API version 12.
9851
9852**System capability**: SystemCapability.ArkUI.ArkUI.Full
9853
9854**Parameters**
9855
9856| Name | Type    | Mandatory  | Description                                      |
9857| ---- | ------ | ---- | ---------------------------------------- |
9858| id   | string | Yes   | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.|
9859| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | No   | Custom settings of the snapshot.|
9860
9861**Return value**
9862
9863| Type                           | Description      |
9864| ----------------------------- | -------- |
9865| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Promise used to return the result.|
9866
9867**Error codes**
9868
9869For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
9870
9871| ID | Error Message               |
9872| ------ | ------------------- |
9873| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
9874| 100001 | Invalid ID. |
9875| 160002 | Timeout. |
9876
9877**Example**
9878
9879```ts
9880import { image } from '@kit.ImageKit';
9881import { UIContext } from '@kit.ArkUI';
9882
9883@Entry
9884@Component
9885struct SnapshotExample {
9886  @State pixmap: image.PixelMap | undefined = undefined
9887
9888  build() {
9889    Column() {
9890      Row() {
9891        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
9892        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")
9893      }
9894      Button("click to generate UI snapshot")
9895        .onClick(() => {
9896          try {
9897            let pixelmap = this.getUIContext().getComponentSnapshot().getSync("root", {scale : 2, waitUntilRenderFinished : true})
9898            this.pixmap = pixelmap
9899          } catch (error) {
9900            console.error("getSync errorCode: " + error.code + " message: " + error.message)
9901          }
9902        }).margin(10)
9903    }
9904    .width('100%')
9905    .height('100%')
9906    .alignItems(HorizontalAlign.Center)
9907  }
9908}
9909```
9910
9911### getWithUniqueId<sup>15+</sup>
9912
9913getWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
9914
9915Obtains the snapshot of a component that has been loaded based on the provided [uniqueId](js-apis-arkui-frameNode.md#getuniqueid12). This API uses a promise to return the result.
9916
9917> **NOTE**
9918>
9919> The snapshot captures content rendered in the last frame. If a snapshot is taken at the same time as the component triggers an update, the updated rendering content will not be captured in the snapshot; instead, the snapshot will return the rendering content from the previous frame.
9920
9921**Atomic service API**: This API can be used in atomic services since API version 15.
9922
9923**System capability**: SystemCapability.ArkUI.ArkUI.Full
9924
9925**Parameters**
9926
9927| Name | Type    | Mandatory  | Description                                      |
9928| ---- | ------ | ---- | ---------------------------------------- |
9929| uniqueId   | number | Yes   | [Unique ID](js-apis-arkui-frameNode.md#getuniqueid12) of the target component.|
9930| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | No   | Custom settings of the snapshot.|
9931
9932**Return value**
9933
9934| Type                                                        | Description            |
9935| ------------------------------------------------------------ | ---------------- |
9936| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | Promise used to return the result.|
9937
9938**Error codes**
9939
9940For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
9941
9942| ID| Error Message                                                    |
9943| -------- | ------------------------------------------------------------ |
9944| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
9945| 100001   | Invalid ID.                                                  |
9946
9947**Example**
9948
9949```ts
9950import { NodeController, FrameNode, typeNode } from '@kit.ArkUI';
9951import { image } from '@kit.ImageKit';
9952import { UIContext } from '@kit.ArkUI';
9953
9954class MyNodeController extends NodeController {
9955  public node: FrameNode | null = null;
9956
9957  public imageNode: FrameNode | null = null;
9958
9959  makeNode(uiContext: UIContext): FrameNode | null {
9960    this.node = new FrameNode(uiContext);
9961    this.node.commonAttribute.width('100%').height('100%')
9962
9963    let image = typeNode.createNode(uiContext, 'Image');
9964    image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true)
9965    this.imageNode = image;
9966
9967    this.node.appendChild(image);
9968    return this.node;
9969  }
9970}
9971
9972@Entry
9973@Component
9974struct SnapshotExample {
9975  private myNodeController: MyNodeController = new MyNodeController();
9976
9977  @State pixmap: image.PixelMap | undefined = undefined
9978
9979  build() {
9980    Column() {
9981      Row() {
9982        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
9983        NodeContainer(this.myNodeController).width(200).height(200).margin(5)
9984      }
9985      Button("UniqueId get snapshot")
9986        .onClick(() => {
9987          try {
9988            this.getUIContext()
9989              .getComponentSnapshot()
9990              .getWithUniqueId(this.myNodeController.imageNode?.getUniqueId(), {scale: 2, waitUntilRenderFinished: true})
9991              .then((pixmap: image.PixelMap) => {
9992                this.pixmap = pixmap
9993              })
9994              .catch((err: Error) => {
9995                console.log("error: " + err)
9996              })
9997          } catch (error) {
9998            console.error("UniqueId get snapshot Error: " + JSON.stringify(error))
9999          }
10000        }).margin(10)
10001    }
10002    .width('100%')
10003    .height('100%')
10004    .alignItems(HorizontalAlign.Center)
10005  }
10006}
10007```
10008
10009### getSyncWithUniqueId<sup>15+</sup>
10010
10011getSyncWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): image.PixelMap
10012
10013Obtains the snapshot of a component that has been loaded based on the provided [uniqueId](js-apis-arkui-frameNode.md#getuniqueid12). This API synchronously waits for the snapshot to complete and returns a [PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) object.
10014
10015> **NOTE**
10016>
10017> The snapshot captures content rendered in the last frame. If a snapshot is taken at the same time as the component triggers an update, the updated rendering content will not be captured in the snapshot; instead, the snapshot will return the rendering content from the previous frame.
10018
10019**Atomic service API**: This API can be used in atomic services since API version 15.
10020
10021**System capability**: SystemCapability.ArkUI.ArkUI.Full
10022
10023**Parameters**
10024
10025| Name | Type    | Mandatory  | Description                                      |
10026| ---- | ------ | ---- | ---------------------------------------- |
10027| uniqueId   | number | Yes   | [Unique ID](js-apis-arkui-frameNode.md#getuniqueid12) of the target component.|
10028| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | No   | Custom settings of the snapshot.|
10029
10030**Return value**
10031
10032| Type                           | Description      |
10033| ----------------------------- | -------- |
10034| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Promise used to return the result.|
10035
10036**Error codes**
10037
10038For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
10039
10040| ID | Error Message               |
10041| ------ | ------------------- |
10042| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
10043| 100001 | Invalid ID. |
10044| 160002 | Timeout. |
10045
10046**Example**
10047
10048```ts
10049import { NodeController, FrameNode, typeNode } from '@kit.ArkUI';
10050import { image } from '@kit.ImageKit';
10051import { UIContext } from '@kit.ArkUI';
10052
10053class MyNodeController extends NodeController {
10054  public node: FrameNode | null = null;
10055
10056  public imageNode: FrameNode | null = null;
10057
10058  makeNode(uiContext: UIContext): FrameNode | null {
10059    this.node = new FrameNode(uiContext);
10060    this.node.commonAttribute.width('100%').height('100%')
10061
10062    let image = typeNode.createNode(uiContext, 'Image');
10063    image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true)
10064    this.imageNode = image;
10065
10066    this.node.appendChild(image);
10067    return this.node;
10068  }
10069}
10070
10071@Entry
10072@Component
10073struct SnapshotExample {
10074  private myNodeController: MyNodeController = new MyNodeController();
10075
10076  @State pixmap: image.PixelMap | undefined = undefined
10077
10078  build() {
10079    Column() {
10080      Row() {
10081        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
10082        NodeContainer(this.myNodeController).width(200).height(200).margin(5)
10083      }
10084      Button("UniqueId getSync snapshot")
10085        .onClick(() => {
10086          try {
10087            this.pixmap = this.getUIContext()
10088              .getComponentSnapshot()
10089              .getSyncWithUniqueId(this.myNodeController.imageNode?.getUniqueId(), {scale: 2, waitUntilRenderFinished: true})
10090          } catch (error) {
10091            console.error("UniqueId getSync snapshot Error: " + JSON.stringify(error))
10092          }
10093        }).margin(10)
10094    }
10095    .width('100%')
10096    .height('100%')
10097    .alignItems(HorizontalAlign.Center)
10098  }
10099}
10100```
10101
10102### createFromComponent<sup>18+</sup>
10103
10104createFromComponent\<T extends Object>(content: ComponentContent\<T>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
10105
10106Takes a snapshot of the provided **content** object. This API uses a promise to return the result.
10107
10108**Atomic service API**: This API can be used in atomic services since API version 18.
10109
10110**System capability**: SystemCapability.ArkUI.ArkUI.Full
10111
10112**Parameters**
10113
10114| Name  | Type                                                        | Mandatory| Description                                                        |
10115| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
10116| content  | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md)         | Yes  | Component content to be captured. This is the content currently displayed in the **UIContext**.     |
10117| delay   | number | No   | Delay time for triggering the screenshot command. When the layout includes an **Image** component, it is necessary to set a delay time to allow the system to decode the image resources. The decoding time is subject to the resource size. In light of this, whenever possible, use pixel map resources that do not require decoding.<br> When pixel map resources are used or when **syncload** to **true** for the **Image** component, you can set **delay** to **0** to forcibly capture snapshots without waiting. This delay time does not refer to the time from the API call to the return: As the system needs to temporarily construct the passed-in **builder** offscreen, the return time is usually longer than this delay.<br>**NOTE**<br>In the **builder** passed in, state variables should not be used to control the construction of child components. If they are used, they should not change when the API is called, so as to avoid unexpected snapshot results.<br> Value range: [0, +∞). If the value is less than 0, the default value is used.<br>Default value: **300**<br> Unit: ms|
10118| checkImageStatus  | boolean | No   | Whether to check the image decoding status before taking a snapshot. If the value is **true**, the system checks whether all **Image** components have been decoded before taking the snapshot. If the check is not completed, the system aborts the snapshot and returns an exception.<br>Default value: **false**|
10119| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | No   | Custom settings of the snapshot. You can specify the scale ratio for the pixelmap during rendering and whether to force the system to complete all rendering commands before taking the snapshot.|
10120
10121**Error codes**
10122
10123For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Snapshot Error Codes](errorcode-snapshot.md).
10124
10125| ID| Error Message                                                    |
10126| -------- | ------------------------------------------------------------ |
10127| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
10128| 100001   | The builder is not a valid build function.                   |
10129| 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. |
10130
10131**Example**
10132
10133```ts
10134import { image } from '@kit.ImageKit';
10135import { ComponentContent } from '@kit.ArkUI';
10136
10137class Params {
10138  text: string | undefined | null  = "";
10139
10140  constructor(text: string | undefined | null ) {
10141    this.text = text;
10142  }
10143}
10144
10145@Builder
10146function buildText(params: Params) {
10147  ReusableChildComponent({ text: params.text });
10148}
10149
10150@Component
10151struct ReusableChildComponent {
10152  @Prop text: string | undefined | null  = "";
10153
10154  aboutToReuse(params: Record<string, object>) {
10155    console.log("ReusableChildComponent Reusable " + JSON.stringify(params));
10156  }
10157
10158  aboutToRecycle(): void {
10159    console.log("ReusableChildComponent aboutToRecycle " + this.text);
10160  }
10161
10162  build() {
10163    Column() {
10164      Text(this.text)
10165        .fontSize(90)
10166        .fontWeight(FontWeight.Bold)
10167        .margin({ bottom: 36 })
10168        .width('100%')
10169        .height('100%')
10170    }.backgroundColor('#FFF0F0F0')
10171  }
10172}
10173
10174@Entry
10175@Component
10176struct Index {
10177  @State pixmap: image.PixelMap | undefined = undefined
10178  @State message: string | undefined | null = "hello"
10179  uiContext: UIContext = this.getUIContext();
10180
10181  build() {
10182    Row() {
10183      Column() {
10184        Button("Create Component Snapshot")
10185          .onClick(() => {
10186            let uiContext = this.getUIContext();
10187            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
10188            this.uiContext.getComponentSnapshot()
10189              .createFromComponent(contentNode
10190                , 320, true, {scale : 2, waitUntilRenderFinished : true})
10191              .then((pixmap: image.PixelMap) => {
10192                this.pixmap = pixmap
10193              })
10194              .catch((err: Error) => {
10195                console.error("error: " + err)
10196              })
10197          })
10198        Image(this.pixmap)
10199          .margin(10)
10200          .height(200)
10201          .width(200)
10202          .border({ color: Color.Black, width: 2 })
10203      }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
10204    }
10205    .width('100%')
10206    .height('100%')
10207  }
10208}
10209```
10210
10211## FrameCallback<sup>12+</sup>
10212
10213Implements the API for setting the task that needs to be executed during the next frame rendering. It must be used together with [postFrameCallback](#postframecallback12) and [postDelayedFrameCallback](#postdelayedframecallback12) in [UIContext](#uicontext). Extend this class and override either the [onFrame](#onframe12) or [onIdle](#onidle12) method to implement specific service logic.
10214
10215### onFrame<sup>12+</sup>
10216
10217onFrame(frameTimeInNano: number): void
10218
10219Called when the next frame is rendered.
10220
10221**Atomic service API**: This API can be used in atomic services since API version 12.
10222
10223**System capability**: SystemCapability.ArkUI.ArkUI.Full
10224
10225**Parameters**
10226
10227| Name | Type                                                | Mandatory| Description                                                   |
10228| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- |
10229| frameTimeInNano | number | Yes  | Time when the rendering of the next frame starts, in nanoseconds.<br>Value range: [0, +∞)|
10230
10231**Example**
10232
10233```ts
10234import {FrameCallback } from '@kit.ArkUI';
10235
10236class MyFrameCallback extends FrameCallback {
10237  private tag: string;
10238
10239  constructor(tag: string) {
10240    super()
10241    this.tag = tag;
10242  }
10243
10244  onFrame(frameTimeNanos: number) {
10245    console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString());
10246  }
10247}
10248
10249@Entry
10250@Component
10251struct Index {
10252  build() {
10253    Row() {
10254      Column() {
10255        Button('Invoke postFrameCallback')
10256          .onClick(() => {
10257            this.getUIContext().postFrameCallback(new MyFrameCallback("normTask"));
10258          })
10259        Button('Invoke postDelayedFrameCallback')
10260          .onClick(() => {
10261            this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5);
10262          })
10263      }
10264      .width('100%')
10265    }
10266    .height('100%')
10267  }
10268}
10269```
10270
10271### onIdle<sup>12+</sup>
10272
10273onIdle(timeLeftInNano: number): void
10274
10275Called after the rendering of the subsequent frame has finished and there is more than 1 millisecond left before the next VSync signal. If the time left is not more than 1 millisecond, the execution of this API will be deferred to a later frame.
10276
10277**Atomic service API**: This API can be used in atomic services since API version 12.
10278
10279**System capability**: SystemCapability.ArkUI.ArkUI.Full
10280
10281**Parameters**
10282
10283| Name | Type                                                | Mandatory| Description                                                   |
10284| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- |
10285| timeLeftInNano | number | Yes  | Remaining idle time for the current frame, in nanoseconds.<br>Value range: [0, +∞)|
10286
10287**Example**
10288
10289```ts
10290import { FrameCallback } from '@ohos.arkui.UIContext';
10291
10292class MyIdleCallback extends FrameCallback {
10293  private tag: string;
10294
10295  constructor(tag: string) {
10296    super()
10297    this.tag = tag;
10298  }
10299
10300  onIdle(timeLeftInNano: number) {
10301    console.info('MyIdleCallback ' + this.tag + ' ' + timeLeftInNano.toString());
10302  }
10303}
10304
10305@Entry
10306@Component
10307struct Index {
10308  build() {
10309    Row() {
10310      Column() {
10311        Button('Invoke postFrameCallback')
10312          .onClick(() => {
10313            this.getUIContext().postFrameCallback(new MyIdleCallback("normTask"));
10314          })
10315        Button('Invoke postDelayedFrameCallback')
10316          .onClick(() => {
10317            this.getUIContext().postDelayedFrameCallback(new MyIdleCallback("delayTask"), 5);
10318          })
10319      }
10320      .width('100%')
10321    }
10322    .height('100%')
10323  }
10324}
10325```
10326
10327## DynamicSyncScene<sup>12+</sup>
10328
10329In the following API examples, you must first use **requireDynamicSyncScene()** in **UIContext** to obtain a **DynamicSyncScene** instance, and then call the APIs using the obtained instance.
10330
10331### setFrameRateRange<sup>12+</sup>
10332
10333setFrameRateRange(range: ExpectedFrameRateRange): void
10334
10335Sets the expected frame rate range.
10336
10337While you can specify a target frame rate for your application, the actual frame rate may vary. The system will take into account its capabilities and make decisions to optimize performance. It will aim to deliver a frame rate as close as possible to your setting, but this might not always be achievable.
10338
10339**Atomic service API**: This API can be used in atomic services since API version 12.
10340
10341**System capability**: SystemCapability.ArkUI.ArkUI.Full
10342
10343**Parameters**
10344
10345| Name     | Type        | Mandatory  | Description  |
10346| -------- | ---------- | ---- | ---- |
10347| range | [ExpectedFrameRateRange](../apis-arkui/arkui-ts/ts-explicit-animation.md#expectedframeraterange11)| Yes   | Expected frame rate range.<br>Default value: **{min:0, max:120, expected: 120}**|
10348
10349**Example**
10350
10351```ts
10352import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI'
10353
10354@Entry
10355@Component
10356struct Frame {
10357  @State ANIMATION:ExpectedFrameRateRange = {min:0, max:120, expected: 90}
10358  @State GESTURE:ExpectedFrameRateRange = {min:0, max:120, expected: 30}
10359  private scenes: SwiperDynamicSyncScene[] = []
10360
10361  build() {
10362    Column() {
10363      Text("Animation"+ JSON.stringify(this.ANIMATION))
10364      Text("Responsive"+ JSON.stringify(this.GESTURE))
10365      Row(){
10366        Swiper() {
10367          Text("one")
10368          Text("two")
10369          Text("three")
10370        }
10371        .width('100%')
10372        .height('300vp')
10373        .id("dynamicSwiper")
10374        .backgroundColor(Color.Blue)
10375        .autoPlay(true)
10376        .onAppear(()=>{
10377          this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[]
10378        })
10379      }
10380
10381      Button("set frame")
10382        .onClick(()=>{
10383          this.scenes.forEach((scenes: SwiperDynamicSyncScene) => {
10384
10385            if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) {
10386              scenes.setFrameRateRange(this.ANIMATION)
10387            }
10388
10389            if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) {
10390              scenes.setFrameRateRange(this.GESTURE)
10391            }
10392          });
10393        })
10394    }
10395  }
10396}
10397```
10398
10399### getFrameRateRange<sup>12+</sup>
10400
10401getFrameRateRange(): ExpectedFrameRateRange
10402
10403Obtains the expected frame rate range.
10404
10405**Atomic service API**: This API can be used in atomic services since API version 12.
10406
10407**System capability**: SystemCapability.ArkUI.ArkUI.Full
10408
10409**Return value**
10410
10411| Type                 | Description     |
10412| ------------------- | ------- |
10413| [ExpectedFrameRateRange](../apis-arkui/arkui-ts/ts-explicit-animation.md#expectedframeraterange11) | Expected frame rate range.|
10414
10415**Example**
10416
10417```ts
10418import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI'
10419
10420@Entry
10421@Component
10422struct Frame {
10423  @State ANIMATION:ExpectedFrameRateRange = {min:0, max:120, expected: 90}
10424  @State GESTURE:ExpectedFrameRateRange = {min:0, max:120, expected: 30}
10425  private scenes: SwiperDynamicSyncScene[] = []
10426
10427  build() {
10428    Column() {
10429      Text("Animation"+ JSON.stringify(this.ANIMATION))
10430      Text("Responsive"+ JSON.stringify(this.GESTURE))
10431      Row(){
10432        Swiper() {
10433          Text("one")
10434          Text("two")
10435          Text("three")
10436        }
10437        .width('100%')
10438        .height('300vp')
10439        .id("dynamicSwiper")
10440        .backgroundColor(Color.Blue)
10441        .autoPlay(true)
10442        .onAppear(()=>{
10443          this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[]
10444        })
10445      }
10446
10447      Button("set frame")
10448        .onClick(()=>{
10449          this.scenes.forEach((scenes: SwiperDynamicSyncScene) => {
10450
10451            if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) {
10452              scenes.setFrameRateRange(this.ANIMATION)
10453              scenes.getFrameRateRange()
10454            }
10455
10456            if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) {
10457              scenes.setFrameRateRange(this.GESTURE)
10458              scenes.getFrameRateRange()
10459            }
10460          });
10461        })
10462      }
10463  }
10464}
10465```
10466## SwiperDynamicSyncScene<sup>12+</sup>
10467
10468Inherits from [DynamicSyncScene](#dynamicsyncscene12) and represents the dynamic sync scene of the **Swiper** component.
10469
10470**Atomic service API**: This API can be used in atomic services since API version 12.
10471
10472**System capability**: SystemCapability.ArkUI.ArkUI.Full
10473
10474| Name      | Type                                                     | Read Only| Optional| Description                               |
10475| --------- | --------------------------------------------------------- | ---- | ---- | ---------------------------------- |
10476| type      | [SwiperDynamicSyncSceneType](#swiperdynamicsyncscenetype12) | Yes  | No  | Dynamic sync scene of the **Swiper** component.            |
10477
10478## SwiperDynamicSyncSceneType<sup>12+</sup>
10479
10480Enumerates the dynamic sync scene types.
10481
10482**Atomic service API**: This API can be used in atomic services since API version 12.
10483
10484**System capability**: SystemCapability.ArkUI.ArkUI.Full
10485
10486| Name    | Value  | Description                  |
10487| -------- | ---- | ---------------------- |
10488| GESTURE | 0   | Gesture operation.|
10489| ANIMATION | 1   | Animation transition.|
10490
10491## MarqueeDynamicSyncScene<sup>14+</sup>
10492
10493Inherits from [DynamicSyncScene](#dynamicsyncscene12) and represents the dynamic sync scene of the [Marquee](arkui-ts/ts-basic-components-marquee.md) component.
10494
10495**Atomic service API**: This API can be used in atomic services since API version 14.
10496
10497**System capability**: SystemCapability.ArkUI.ArkUI.Full
10498
10499| Name      | Type                                                     | Read Only| Optional| Description                               |
10500| --------- | --------------------------------------------------------- | ---- | ---- | ---------------------------------- |
10501| type      | [MarqueeDynamicSyncSceneType](#marqueedynamicsyncscenetype14) | Yes  | No  | Dynamic sync scene of the **Marquee** component.            |
10502
10503## MarqueeDynamicSyncSceneType<sup>14+</sup>
10504
10505Enumerates the dynamic sync scene types for the **Marquee** component.
10506
10507**Atomic service API**: This API can be used in atomic services since API version 14.
10508
10509**System capability**: SystemCapability.ArkUI.ArkUI.Full
10510
10511| Name    | Value  | Description                  |
10512| -------- | ---- | ---------------------- |
10513| ANIMATION | 1   | Animation transition.|
10514
10515**Example**
10516
10517```ts
10518import { MarqueeDynamicSyncSceneType, MarqueeDynamicSyncScene } from '@kit.ArkUI';
10519
10520@Entry
10521@Component
10522struct MarqueeExample {
10523  @State start: boolean = false
10524  @State src: string = ''
10525  @State marqueeText: string = 'Running Marquee'
10526  private fromStart: boolean = true
10527  private step: number = 10
10528  private loop: number = Number.POSITIVE_INFINITY
10529  controller: TextClockController = new TextClockController()
10530  convert2time(value: number): string{
10531    let date = new Date(Number(value+'000'));
10532    let hours = date.getHours().toString().padStart(2, '0');
10533    let minutes = date.getMinutes().toString().padStart(2, '0');
10534    let seconds = date.getSeconds().toString().padStart(2, '0');
10535    return hours+ ":" + minutes + ":" + seconds;
10536  }
10537  @State ANIMATION: ExpectedFrameRateRange = {min:0, max:120, expected:30}
10538  private scenes: MarqueeDynamicSyncScene[] = []
10539
10540  build() {
10541    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
10542      Marquee({
10543        start: this.start,
10544        step: this.step,
10545        loop: this.loop,
10546        fromStart: this.fromStart,
10547        src: this.marqueeText + this.src
10548      })
10549        .marqueeUpdateStrategy(MarqueeUpdateStrategy.PRESERVE_POSITION)
10550        .width(300)
10551        .height(80)
10552        .fontColor('#FFFFFF')
10553        .fontSize(48)
10554        .fontWeight(700)
10555        .backgroundColor('#182431')
10556        .margin({ bottom: 40 })
10557        .id('dynamicMarquee')
10558        .onAppear(()=>{
10559          this.scenes = this.getUIContext().requireDynamicSyncScene('dynamicMarquee') as MarqueeDynamicSyncScene[]
10560        })
10561      Button('Start')
10562        .onClick(() => {
10563          this.start = true
10564          this.controller.start()
10565          this.scenes.forEach((scenes: MarqueeDynamicSyncScene) => {
10566            if (scenes.type == MarqueeDynamicSyncSceneType.ANIMATION) {
10567              scenes.setFrameRateRange(this.ANIMATION)
10568            }
10569          });
10570        })
10571        .width(120)
10572        .height(40)
10573        .fontSize(16)
10574        .fontWeight(500)
10575        .backgroundColor('#007DFF')
10576      TextClock({ timeZoneOffset: -8, controller: this.controller })
10577        .format('hms')
10578        .onDateChange((value: number) => {
10579          this.src = this.convert2time(value);
10580        })
10581        .margin(20)
10582        .fontSize(30)
10583    }
10584    .width('100%')
10585    .height('100%')
10586  }
10587}
10588```
10589## TextMenuController<sup>16+</sup>
10590In the following API examples, you must first use [getTextMenuController()](js-apis-arkui-UIContext.md#gettextmenucontroller16) in **UIContext** to obtain a **TextMenuController** instance, and then call the APIs using the obtained instance.
10591
10592### setMenuOptions<sup>16+</sup>
10593
10594setMenuOptions(options: TextMenuOptions): void
10595
10596Sets menu options.
10597
10598**Atomic service API**: This API can be used in atomic services since API version 16.
10599
10600**System capability**: SystemCapability.ArkUI.ArkUI.Full
10601
10602**Parameters**
10603
10604| Name     | Type        | Mandatory  | Description  |
10605| -------- | ---------- | ---- | ---- |
10606| options | [TextMenuOptions](../apis-arkui/arkui-ts/ts-text-common.md#textmenuoptions16)| Yes   | Menu options.<br>Default value: **{showMode: TextMenuShowMode.DEFAULT}**|
10607
10608**Example**
10609
10610```ts
10611// xxx.ets
10612@Entry
10613@Component
10614struct Index {
10615  aboutToAppear(): void {
10616    // Set the UIContext to preferentially display the context menu on selection in a separate window.
10617    this.getUIContext()
10618      .getTextMenuController()
10619      .setMenuOptions(
10620        {
10621          showMode: TextMenuShowMode.PREFER_WINDOW
10622        }
10623      )
10624  }
10625
10626  build() {
10627    Row() {
10628      Column() {
10629        TextInput({ text: "This is a TextInput. Long press to display the context menu on selection." })
10630          .height(60)
10631          .fontStyle(FontStyle.Italic)
10632          .fontWeight(FontWeight.Bold)
10633          .textAlign(TextAlign.Center)
10634          .caretStyle({ width: '4vp' })
10635
10636        Text("This is a Text. Long press to display the context menu on selection.")
10637          .height(60)
10638          .copyOption(CopyOptions.InApp)
10639          .fontStyle(FontStyle.Italic)
10640          .fontWeight(FontWeight.Bold)
10641          .textAlign(TextAlign.Center)
10642      }.width('100%')
10643    }
10644    .height('100%')
10645  }
10646}
10647```
10648