• 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 });
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** 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### dispatchKeyEvent<sup>15+</sup>
2550
2551dispatchKeyEvent(node: number | string, event: KeyEvent): boolean
2552
2553Dispatches a key event to the specified component. To ensure predictable behavior, the target component must be within the subtree of the dispatching component.
2554
2555**Atomic service API**: This API can be used in atomic services since API version 15.
2556
2557**System capability**: SystemCapability.ArkUI.ArkUI.Full
2558
2559| Name| Type                         | Mandatory| Description              |
2560| ------ | ----------------------------- | ---- | ------------------ |
2561| node  | number \| string | Yes  | ID or unique ID of the target component.|
2562| event  |[KeyEvent](./arkui-ts/ts-universal-events-key.md#keyevent) | Yes  | **KeyEvent** object.|
2563
2564**Example**
2565
2566```ts
2567@Entry
2568@Component
2569struct Index {
2570  build() {
2571    Row() {
2572      Row() {
2573        Button('Button1').id('Button1').onKeyEvent((event) => {
2574          console.log("Button1");
2575          return true
2576        })
2577        Button('Button2').id('Button2').onKeyEvent((event) => {
2578          console.log("Button2");
2579          return true
2580        })
2581      }
2582      .width('100%')
2583      .height('100%')
2584      .id('Row1')
2585      .onKeyEventDispatch((event) => {
2586        let context = this.getUIContext();
2587        context.getFocusController().requestFocus('Button1');
2588        return context.dispatchKeyEvent('Button1', event);
2589      })
2590
2591    }
2592    .height('100%')
2593    .width('100%')
2594    .onKeyEventDispatch((event) => {
2595      if (event.type == KeyType.Down) {
2596        let context = this.getUIContext();
2597        context.getFocusController().requestFocus('Row1');
2598        return context.dispatchKeyEvent('Row1', event);
2599      }
2600      return true;
2601    })
2602  }
2603}
2604```
2605## Font
2606
2607In 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.
2608
2609### registerFont
2610
2611registerFont(options: font.FontOptions): void
2612
2613Registers a custom font with the font manager.
2614
2615**Atomic service API**: This API can be used in atomic services since API version 11.
2616
2617**System capability**: SystemCapability.ArkUI.ArkUI.Full
2618
2619**Parameters**
2620
2621| Name    | Type                                      | Mandatory  | Description         |
2622| ------- | ---------------------------------------- | ---- | ----------- |
2623| options | [font.FontOptions](js-apis-font.md#fontoptions) | Yes   | Information about the custom font to register.|
2624
2625**Example**
2626
2627<!--code_no_check-->
2628```ts
2629import { Font } from '@kit.ArkUI';
2630
2631let font:Font = uiContext.getFont();
2632font.registerFont({
2633  familyName: 'medium',
2634  familySrc: '/font/medium.ttf'
2635});
2636```
2637### getSystemFontList
2638
2639getSystemFontList(): Array\<string>
2640
2641Obtains the list of supported fonts.
2642
2643**Atomic service API**: This API can be used in atomic services since API version 11.
2644
2645**System capability**: SystemCapability.ArkUI.ArkUI.Full
2646
2647**Return value**
2648
2649| Type            | Description       |
2650| -------------- | --------- |
2651| Array\<string> | List of supported fonts.|
2652
2653>  **NOTE**
2654>
2655>  This API takes effect only on 2-in-1 devices.
2656
2657**Example**
2658
2659<!--code_no_check-->
2660```ts
2661import { Font } from '@kit.ArkUI';
2662
2663let font:Font|undefined = uiContext.getFont();
2664if(font){
2665  font.getSystemFontList()
2666}
2667```
2668
2669### getFontByName
2670
2671getFontByName(fontName: string): font.FontInfo
2672
2673Obtains information about a system font based on the font name.
2674
2675**Atomic service API**: This API can be used in atomic services since API version 11.
2676
2677**System capability**: SystemCapability.ArkUI.ArkUI.Full
2678
2679**Parameters**
2680
2681| Name     | Type    | Mandatory  | Description     |
2682| -------- | ------ | ---- | ------- |
2683| fontName | string | Yes   | System font name.|
2684
2685**Return value**
2686
2687| Type                                     | Description          |
2688| ----------------------------------------- | -------------- |
2689| [font.FontInfo](js-apis-font.md#fontinfo10) | Information about the system font.|
2690
2691**Example**
2692
2693<!--code_no_check-->
2694```ts
2695import { Font } from '@kit.ArkUI';
2696
2697let font:Font|undefined = uiContext.getFont();
2698if(font){
2699  font.getFontByName('Sans Italic')
2700}
2701```
2702
2703## Context<sup>12+</sup>
2704
2705type Context = common.Context
2706
2707Defines the context of the current ability.
2708
2709**Atomic service API**: This API can be used in atomic services since API version 12.
2710
2711**System capability**: SystemCapability.Ability.AbilityRuntime.Core
2712
2713**Model restriction**: This API can be used only in the stage model.
2714
2715| Type|Description  |
2716| ------ | ------------------- |
2717| [common.Context](../apis-ability-kit/js-apis-app-ability-common.md#context) |Context object associated with the current ability.|
2718
2719## ComponentUtils
2720
2721In 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.
2722
2723### getRectangleById
2724
2725getRectangleById(id: string): componentUtils.ComponentInfo
2726
2727Obtains the size, position, translation, scaling, rotation, and affine matrix information of the specified component.
2728
2729**Atomic service API**: This API can be used in atomic services since API version 11.
2730
2731**System capability**: SystemCapability.ArkUI.ArkUI.Full
2732
2733**Parameters**
2734
2735| Name | Type    | Mandatory  | Description       |
2736| ---- | ------ | ---- | --------- |
2737| id   | string | Yes   | Unique component ID.|
2738
2739**Return value**
2740
2741| Type                                                        | Description                                            |
2742| ------------------------------------------------------------ | ------------------------------------------------ |
2743| [componentUtils.ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | Size, position, translation, scaling, rotation, and affine matrix information of the component.|
2744
2745**Error codes**
2746
2747For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
2748
2749| ID | Error Message               |
2750| ------ | ------------------- |
2751| 100001 | UI execution context not found. |
2752
2753**Example**
2754
2755<!--code_no_check-->
2756```ts
2757import { ComponentUtils } from '@kit.ArkUI';
2758
2759let componentUtils:ComponentUtils = uiContext.getComponentUtils();
2760let modePosition = componentUtils.getRectangleById("onClick");
2761let localOffsetWidth = modePosition.size.width;
2762let localOffsetHeight = modePosition.size.height;
2763```
2764
2765## UIInspector
2766
2767In 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.
2768
2769### createComponentObserver
2770
2771createComponentObserver(id: string): inspector.ComponentObserver
2772
2773Registers a callback for layout and rendering completion notifications for a specific component.
2774
2775**Atomic service API**: This API can be used in atomic services since API version 11.
2776
2777**System capability**: SystemCapability.ArkUI.ArkUI.Full
2778
2779**Parameters**
2780
2781| Name | Type    | Mandatory  | Description     |
2782| ---- | ------ | ---- | ------- |
2783| 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).|
2784
2785**Return value**
2786
2787| Type                                                        | Description                                              |
2788| ------------------------------------------------------------ | -------------------------------------------------- |
2789| [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.|
2790
2791**Example**
2792
2793<!--code_no_check-->
2794```ts
2795import { UIInspector } from '@kit.ArkUI';
2796
2797let inspector: UIInspector = uiContext.getUIInspector();
2798let listener = inspector.createComponentObserver('COMPONENT_ID');
2799```
2800
2801## PageInfo<sup>12+</sup>
2802Represents the page information of the router or navigation destination. If there is no related page information, **undefined** is returned.
2803
2804**Atomic service API**: This API can be used in atomic services since API version 12.
2805
2806**System capability**: SystemCapability.ArkUI.ArkUI.Full
2807
2808| Name| Type| Mandatory| Description|
2809| -------- | -------- | -------- | -------- |
2810| routerPageInfo | observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo) | No| Router information.|
2811| navDestinationInfo | observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo) | No| Navigation destination information.|
2812
2813## UIObserver<sup>11+</sup>
2814
2815In 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.
2816
2817### on('navDestinationUpdate')<sup>11+</sup>
2818
2819on(type: 'navDestinationUpdate', callback: Callback\<observer.NavDestinationInfo\>): void
2820
2821Subscribes to status changes of this **NavDestination** component.
2822
2823**Atomic service API**: This API can be used in atomic services since API version 12.
2824
2825**System capability**: SystemCapability.ArkUI.ArkUI.Full
2826
2827**Parameters**
2828
2829| Name  | Type                                                 | Mandatory| Description                                                        |
2830| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
2831| type     | string                                                | Yes  | Event type. The value is fixed at **'navDestinationUpdate'**, which indicates the state change event of the **NavDestination** component.|
2832| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | Yes  | Callback used to return the current state of the **NavDestination** component.                |
2833
2834**Example**
2835
2836<!--code_no_check-->
2837```ts
2838// Index.ets
2839// Example usage of uiObserver.on('navDestinationUpdate', callback)
2840// uiObserver.off('navDestinationUpdate', callback)
2841
2842@Component
2843struct PageOne {
2844  build() {
2845    NavDestination() {
2846      Text("pageOne")
2847    }.title("pageOne")
2848  }
2849}
2850
2851@Entry
2852@Component
2853struct Index {
2854  private stack: NavPathStack = new NavPathStack();
2855
2856  @Builder
2857  PageBuilder(name: string) {
2858    PageOne()
2859  }
2860
2861  aboutToAppear() {
2862    this.getUIContext().getUIObserver().on('navDestinationUpdate', (info) => {
2863      console.info('NavDestination state update', JSON.stringify(info));
2864    });
2865  }
2866
2867  aboutToDisappear() {
2868    this.getUIContext().getUIObserver().off('navDestinationUpdate');
2869  }
2870
2871  build() {
2872    Column() {
2873      Navigation(this.stack) {
2874        Button("push").onClick(() => {
2875          this.stack.pushPath({ name: "pageOne" });
2876        })
2877      }
2878      .title("Navigation")
2879      .navDestination(this.PageBuilder)
2880    }
2881    .width('100%')
2882    .height('100%')
2883  }
2884}
2885```
2886
2887### off('navDestinationUpdate')<sup>11+</sup>
2888
2889off(type: 'navDestinationUpdate', callback?: Callback\<observer.NavDestinationInfo\>): void
2890
2891Unsubscribes from state changes of this **NavDestination** component.
2892
2893**Atomic service API**: This API can be used in atomic services since API version 12.
2894
2895**System capability**: SystemCapability.ArkUI.ArkUI.Full
2896
2897**Parameters**
2898
2899| Name  | Type                                                 | Mandatory| Description                                                        |
2900| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
2901| type     | string                                                | Yes  | Event type. The value is fixed at **'navDestinationUpdate'**, which indicates the state change event of the **NavDestination** component.|
2902| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | No  | Callback used to return the current state of the **NavDestination** component.                |
2903
2904**Example**
2905
2906See the example for [uiObserver.on('navDestinationUpdate')](#onnavdestinationupdate11).
2907
2908### on('navDestinationUpdate')<sup>11+</sup>
2909
2910on(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback: Callback\<observer.NavDestinationInfo\>): void
2911
2912Subscribes to state changes of this **NavDestination** component.
2913
2914**Atomic service API**: This API can be used in atomic services since API version 12.
2915
2916**System capability**: SystemCapability.ArkUI.ArkUI.Full
2917
2918**Parameters**
2919
2920| Name  | Type                                                        | Mandatory| Description                                                        |
2921| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2922| type     | string                                                       | Yes  | Event type. The value is fixed at **'navDestinationUpdate'**, which indicates the state change event of the **NavDestination** component.|
2923| options  | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | Yes  | ID of the target **NavDestination** component.                                  |
2924| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\>        | Yes  | Callback used to return the current state of the **NavDestination** component.                |
2925
2926**Example**
2927
2928<!--code_no_check-->
2929```ts
2930// Index.ets
2931// Example usage of uiObserver.on('navDestinationUpdate', navigationId, callback)
2932// uiObserver.off('navDestinationUpdate', navigationId, callback)
2933@Component
2934struct PageOne {
2935  build() {
2936    NavDestination() {
2937      Text("pageOne")
2938    }.title("pageOne")
2939  }
2940}
2941
2942@Entry
2943@Component
2944struct Index {
2945  private stack: NavPathStack = new NavPathStack();
2946
2947  @Builder
2948  PageBuilder(name: string) {
2949    PageOne()
2950  }
2951
2952  aboutToAppear() {
2953    this.getUIContext().getUIObserver().on('navDestinationUpdate', { navigationId: "testId" }, (info) => {
2954      console.info('NavDestination state update', JSON.stringify(info));
2955    });
2956  }
2957
2958  aboutToDisappear() {
2959    this.getUIContext().getUIObserver().off('navDestinationUpdate', { navigationId: "testId" });
2960  }
2961
2962  build() {
2963    Column() {
2964      Navigation(this.stack) {
2965        Button("push").onClick(() => {
2966          this.stack.pushPath({ name: "pageOne" });
2967        })
2968      }
2969      .id("testId")
2970      .title("Navigation")
2971      .navDestination(this.PageBuilder)
2972    }
2973    .width('100%')
2974    .height('100%')
2975  }
2976}
2977```
2978
2979### off('navDestinationUpdate')<sup>11+</sup>
2980
2981off(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback?: Callback\<observer.NavDestinationInfo\>): void
2982
2983Unsubscribes from state changes of the **NavDestination** component.
2984
2985**Atomic service API**: This API can be used in atomic services since API version 12.
2986
2987**System capability**: SystemCapability.ArkUI.ArkUI.Full
2988
2989**Parameters**
2990
2991| Name  | Type                                                        | Mandatory| Description                                                        |
2992| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
2993| type     | string                                                       | Yes  | Event type. The value is fixed at **'navDestinationUpdate'**, which indicates the state change event of the **NavDestination** component.|
2994| options  | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | Yes  | ID of the target **NavDestination** component.                                  |
2995| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\>        | No  | Callback used to return the current state of the **NavDestination** component.                |
2996
2997**Example**
2998
2999See the example for [uiObserver.on('navDestinationUpdate')](#onnavdestinationupdate11-1).
3000
3001### on('scrollEvent')<sup>12+</sup>
3002
3003on(type: 'scrollEvent', callback: Callback\<observer.ScrollEventInfo\>): void
3004
3005Subscribes to the start and end of a scroll event.
3006
3007**Atomic service API**: This API can be used in atomic services since API version 12.
3008
3009**System capability**: SystemCapability.ArkUI.ArkUI.Full
3010
3011**Parameters**
3012
3013| Name  | Type                                                 | Mandatory| Description                                                        |
3014| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
3015| type     | string                                                | Yes  | Event type. The value **'scrollEvent'** indicates the start and end of a scroll event.     |
3016| 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.  |
3017
3018**Example**
3019
3020See [offscrollevent Example](#offscrollevent12-1).
3021
3022### off('scrollEvent')<sup>12+</sup>
3023
3024off(type: 'scrollEvent', callback?: Callback\<observer.ScrollEventInfo\>): void
3025
3026Unsubscribes from the start and end of a scroll event.
3027
3028**Atomic service API**: This API can be used in atomic services since API version 12.
3029
3030**System capability**: SystemCapability.ArkUI.ArkUI.Full
3031
3032**Parameters**
3033
3034| Name  | Type                                                 | Mandatory| Description                                                        |
3035| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
3036| type     | string                                                | Yes  | Event type. The value **'scrollEvent'** indicates the start and end of a scroll event.     |
3037| 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.  |
3038
3039**Example**
3040
3041See [offscrollevent Example](#offscrollevent12-1).
3042
3043### on('scrollEvent')<sup>12+</sup>
3044
3045on(type: 'scrollEvent', options: observer.ObserverOptions, callback: Callback\<observer.ScrollEventInfo\>): void
3046
3047Subscribes to the start and end of a scroll event.
3048
3049**Atomic service API**: This API can be used in atomic services since API version 12.
3050
3051**System capability**: SystemCapability.ArkUI.ArkUI.Full
3052
3053**Parameters**
3054
3055| Name  | Type                                                        | Mandatory| Description                                                        |
3056| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3057| type     | string                                                       | Yes  | Event type. The value **'scrollEvent'** indicates the start and end of a scroll event.|
3058| options  | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | Yes  | Observer options, including the ID of the target scrollable component.                   |
3059| 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.                |
3060
3061**Example**
3062
3063See [offscrollevent Example](#offscrollevent12-1).
3064
3065### off('scrollEvent')<sup>12+</sup>
3066
3067off(type: 'scrollEvent', options: observer.ObserverOptions, callback?: Callback\<observer.ScrollEventInfo\>): void
3068
3069Unsubscribes from the start and end of a scroll event.
3070
3071**Atomic service API**: This API can be used in atomic services since API version 12.
3072
3073**System capability**: SystemCapability.ArkUI.ArkUI.Full
3074
3075**Parameters**
3076
3077| Name  | Type                                                        | Mandatory| Description                                                        |
3078| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3079| type     | string                                                       | Yes  | Event type. The value **'scrollEvent'** indicates the start and end of a scroll event.|
3080| options  | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | Yes  | Observer options, including the ID of the target scrollable component.                   |
3081| 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.                |
3082
3083**Example**
3084
3085```ts
3086import { UIObserver } from '@kit.ArkUI'
3087
3088@Entry
3089@Component
3090struct Index {
3091  scroller: Scroller = new Scroller()
3092  observer: UIObserver = new UIObserver()
3093  private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7]
3094
3095  build() {
3096    Row() {
3097      Column() {
3098        Scroll(this.scroller) {
3099          Column() {
3100            ForEach(this.arr, (item: number) => {
3101              Text(item.toString())
3102                .width('90%')
3103                .height(150)
3104                .backgroundColor(0xFFFFFF)
3105                .borderRadius(15)
3106                .fontSize(16)
3107                .textAlign(TextAlign.Center)
3108                .margin({ top: 10 })
3109            }, (item: string) => item)
3110          }.width('100%')
3111        }
3112        .id("testId")
3113        .height('80%')
3114      }
3115      .width('100%')
3116
3117      Row() {
3118        Button('UIObserver on')
3119          .onClick(() => {
3120            this.observer.on('scrollEvent', (info) => {
3121              console.info('scrollEventInfo', JSON.stringify(info));
3122            });
3123          })
3124        Button('UIObserver off')
3125          .onClick(() => {
3126            this.observer.off('scrollEvent');
3127          })
3128      }
3129
3130      Row() {
3131        Button('UIObserverWithId on')
3132          .onClick(() => {
3133            this.observer.on('scrollEvent', { id:"testId" }, (info) => {
3134              console.info('scrollEventInfo', JSON.stringify(info));
3135            });
3136          })
3137        Button('UIObserverWithId off')
3138          .onClick(() => {
3139            this.observer.off('scrollEvent', { id:"testId" });
3140          })
3141      }
3142    }
3143    .height('100%')
3144  }
3145}
3146```
3147
3148### on('routerPageUpdate')<sup>11+</sup>
3149
3150on(type: 'routerPageUpdate', callback: Callback\<observer.RouterPageInfo\>): void
3151
3152Subscribes to state changes of the page in the router.
3153
3154**Atomic service API**: This API can be used in atomic services since API version 12.
3155
3156**System capability**: SystemCapability.ArkUI.ArkUI.Full
3157
3158**Parameters**
3159
3160| Name  | Type                                                        | Mandatory| Description                                                        |
3161| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3162| type     | string                                                       | Yes  | Event type. The value is fixed at **'routerPageUpdate'**, which indicates the state change event of the page in the router.|
3163| 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.                |
3164
3165**Example**
3166
3167```ts
3168import { UIContext, UIObserver } from '@kit.ArkUI';
3169
3170let observer:UIObserver = this.getUIContext().getUIObserver();
3171observer.on('routerPageUpdate', (info) => {
3172    console.info('RouterPage state updated, called by ' + `${info.name}`);
3173});
3174```
3175
3176### off('routerPageUpdate')<sup>11+</sup>
3177
3178off(type: 'routerPageUpdate', callback?: Callback\<observer.RouterPageInfo\>): void
3179
3180Unsubscribes to state changes of the page in the router.
3181
3182**Atomic service API**: This API can be used in atomic services since API version 12.
3183
3184**System capability**: SystemCapability.ArkUI.ArkUI.Full
3185
3186**Parameters**
3187
3188| Name  | Type                                                        | Mandatory| Description                                                        |
3189| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3190| type     | string                                                       | Yes  | Event type. The value is fixed at **'routerPageUpdate'**, which indicates the state change event of the page in the router.|
3191| callback | Callback\<observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo)\>        | No  | Callback to be unregistered.                |
3192
3193**Example**
3194
3195```ts
3196import { UIContext, UIObserver } from '@kit.ArkUI';
3197
3198let observer:UIObserver = this.getUIContext().getUIObserver();
3199function callBackFunc(info:observer.RouterPageInfo) {};
3200// callBackFunc is defined and used before
3201observer.off('routerPageUpdate', callBackFunc);
3202```
3203
3204### on('densityUpdate')<sup>12+</sup>
3205
3206on(type: 'densityUpdate', callback: Callback\<observer.DensityInfo\>): void
3207
3208Subscribes to the pixel density changes of the screen.
3209
3210**Atomic service API**: This API can be used in atomic services since API version 12.
3211
3212**System capability**: SystemCapability.ArkUI.ArkUI.Full
3213
3214**Parameters**
3215
3216| Name  | Type                                                        | Mandatory| Description                                                        |
3217| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3218| type     | string                                                       | Yes  | Event type. The value **'densityUpdate'** indicates the pixel density changes of the screen.|
3219| callback | Callback\<observer.[DensityInfo](./js-apis-arkui-observer.md#densityinfo12)\>        | Yes  | Callback used to return the screen pixel density after the change.                |
3220
3221```ts
3222import { uiObserver } from '@kit.ArkUI';
3223
3224@Entry
3225@Component
3226struct Index {
3227  @State density: number = 0;
3228  @State message: string = 'No listener registered'
3229
3230  densityUpdateCallback = (info: uiObserver.DensityInfo) => {
3231    this.density = info.density;
3232    this.message = 'DPI after change:' + this.density.toString();
3233  }
3234
3235  build() {
3236    Column() {
3237      Text(this.message)
3238        .fontSize(24)
3239        .fontWeight(FontWeight.Bold)
3240      Button('Subscribe to Screen Pixel Density Changes')
3241        .onClick(() => {
3242          this.message = 'Listener registered'
3243          this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback);
3244        })
3245    }
3246  }
3247}
3248```
3249
3250### off('densityUpdate')<sup>12+</sup>
3251
3252off(type: 'densityUpdate', callback?: Callback\<observer.DensityInfo\>): void
3253
3254Unsubscribes from the pixel density changes of the screen.
3255
3256**Atomic service API**: This API can be used in atomic services since API version 12.
3257
3258**System capability**: SystemCapability.ArkUI.ArkUI.Full
3259
3260**Parameters**
3261
3262| Name  | Type                                                                | Mandatory| Description                                                                                        |
3263| -------- | -------------------------------------------------------------------- | ---- | -------------------------------------------------------------------------------------------- |
3264| type     | string                                                               | Yes  | Event type. The value **'densityUpdate'** indicates the pixel density changes of the screen.                                       |
3265| 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.|
3266
3267```ts
3268import { uiObserver } from '@kit.ArkUI';
3269
3270@Entry
3271@Component
3272struct Index {
3273  @State density: number = 0;
3274  @State message: string = 'No listener registered'
3275
3276  densityUpdateCallback = (info: uiObserver.DensityInfo) => {
3277    this.density = info.density;
3278    this.message = 'DPI after change:' + this.density.toString();
3279  }
3280
3281  build() {
3282    Column() {
3283      Text(this.message)
3284        .fontSize(24)
3285        .fontWeight(FontWeight.Bold)
3286      Button('Subscribe to Screen Pixel Density Changes')
3287        .margin({ bottom: 10 })
3288        .onClick(() => {
3289          this.message = 'Listener registered'
3290          this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback);
3291        })
3292      Button('Unsubscribe from Screen Pixel Density Changes')
3293        .onClick(() => {
3294          this.message = 'Listener not registered'
3295          this.getUIContext().getUIObserver().off('densityUpdate', this.densityUpdateCallback);
3296        })
3297    }
3298  }
3299}
3300```
3301
3302### on('willDraw')<sup>12+</sup>
3303
3304on(type: 'willDraw', callback: Callback\<void\>): void
3305
3306Subscribes to the dispatch of drawing instructions in each frame.
3307
3308**Atomic service API**: This API can be used in atomic services since API version 12.
3309
3310**System capability**: SystemCapability.ArkUI.ArkUI.Full
3311
3312**Parameters**
3313
3314| Name  | Type                                                        | Mandatory| Description                                                        |
3315| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3316| type     | string                                                       | Yes  | Event event. The value **'willDraw'** indicates whether drawing is about to occur.|
3317| callback | Callback\<void\>        | Yes  | Callback used to return the result.                |
3318
3319```ts
3320import { uiObserver } from '@kit.ArkUI';
3321
3322@Entry
3323@Component
3324struct Index {
3325  willDrawCallback = () => {
3326    console.info("willDraw instruction dispatched.")
3327  }
3328  build() {
3329    Column() {
3330      Button('Subscribe to Drawing Instruction Dispatch')
3331        .onClick(() => {
3332          this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback);
3333        })
3334    }
3335  }
3336}
3337```
3338
3339### off('willDraw')<sup>12+</sup>
3340
3341off(type: 'willDraw', callback?: Callback\<void\>): void
3342
3343Unsubscribes from the dispatch of drawing instructions in each frame.
3344
3345**Atomic service API**: This API can be used in atomic services since API version 12.
3346
3347**System capability**: SystemCapability.ArkUI.ArkUI.Full
3348
3349**Parameters**
3350
3351| Name  | Type                                                        | Mandatory| Description                                                        |
3352| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3353| type     | string                                                       | Yes  | Event event. The value **'willDraw'** indicates whether drawing is about to occur.|
3354| callback | Callback\<void\>        | No  | Callback to be unregistered.                 |
3355
3356```ts
3357import { uiObserver } from '@kit.ArkUI';
3358
3359@Entry
3360@Component
3361struct Index {
3362  willDrawCallback = () => {
3363    console.info("willDraw instruction dispatched.")
3364  }
3365
3366  build() {
3367    Column() {
3368      Button('Subscribe to Drawing Instruction Dispatch')
3369        .margin({ bottom: 10 })
3370        .onClick(() => {
3371          this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback);
3372        })
3373      Button('Unsubscribe from Drawing Instruction Dispatch')
3374        .onClick(() => {
3375          this.getUIContext().getUIObserver().off('willDraw', this.willDrawCallback);
3376        })
3377    }
3378  }
3379}
3380```
3381
3382### on('didLayout')<sup>12+</sup>
3383
3384on(type: 'didLayout', callback: Callback\<void\>): void
3385
3386Subscribes to layout completion status in each frame.
3387
3388**Atomic service API**: This API can be used in atomic services since API version 12.
3389
3390**System capability**: SystemCapability.ArkUI.ArkUI.Full
3391
3392**Parameters**
3393
3394| Name  | Type                                                        | Mandatory| Description                                                        |
3395| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3396| type     | string                                                       | Yes  | Event type. The value **'didLayout'** indicates whether the layout has been completed.|
3397| callback | Callback\<void\>        | Yes  | Callback used to return the result.                |
3398
3399```ts
3400import { uiObserver } from '@kit.ArkUI';
3401
3402@Entry
3403@Component
3404struct Index {
3405  didLayoutCallback = () => {
3406    console.info("Layout completed.");
3407  }
3408  build() {
3409    Column() {
3410      Button('Subscribe to Layout Completion')
3411        .onClick(() => {
3412          this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback);
3413        })
3414    }
3415  }
3416}
3417```
3418
3419### off('didLayout')<sup>12+</sup>
3420
3421off(type: 'didLayout', callback?: Callback\<void\>): void
3422
3423Unsubscribes from layout completion status in each frame.
3424
3425**Atomic service API**: This API can be used in atomic services since API version 12.
3426
3427**System capability**: SystemCapability.ArkUI.ArkUI.Full
3428
3429**Parameters**
3430
3431| Name  | Type                                                        | Mandatory| Description                                                        |
3432| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3433| type     | string                                                       | Yes  | Event event. The value **'didLayout'** indicates whether the layout has been completed.|
3434| callback | Callback\<void\>        | No  | Callback to be unregistered.                 |
3435
3436```ts
3437import { uiObserver } from '@kit.ArkUI';
3438
3439@Entry
3440@Component
3441struct Index {
3442  didLayoutCallback = () => {
3443    console.info("Layout completed.")
3444  }
3445
3446  build() {
3447    Column() {
3448      Button('Subscribe to Layout Completion')
3449        .margin({ bottom: 10 })
3450        .onClick(() => {
3451          this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback);
3452        })
3453      Button('Unsubscribe from Layout Completion')
3454        .onClick(() => {
3455          this.getUIContext().getUIObserver().off('didLayout', this.didLayoutCallback);
3456        })
3457    }
3458  }
3459}
3460```
3461
3462### on('navDestinationSwitch')<sup>12+</sup>
3463
3464on(type: 'navDestinationSwitch', callback: Callback\<observer.NavDestinationSwitchInfo\>): void
3465
3466Subscribes to the page switching event of the **Navigation** component.
3467
3468**Atomic service API**: This API can be used in atomic services since API version 12.
3469
3470**System capability**: SystemCapability.ArkUI.ArkUI.Full
3471
3472**Parameters**
3473
3474| Name  | Type                                                        | Mandatory| Description                                                        |
3475| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3476| type     | string                                                       | Yes  | Event type. The value **'navDestinationSwitch'** indicates the page switching event of the **Navigation** component.|
3477| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\>        | Yes  | Callback used to return the information about the page switching event.                |
3478
3479**Example**
3480
3481```ts
3482// Index.ets
3483// UIObserver.on('navDestinationSwitch', callback) demo
3484// UIObserver.off('navDestinationSwitch', callback)
3485import { uiObserver } from '@kit.ArkUI';
3486
3487@Component
3488struct PageOne {
3489  build() {
3490    NavDestination() {
3491      Text("pageOne")
3492    }.title("pageOne")
3493  }
3494}
3495
3496function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) {
3497  console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`)
3498}
3499
3500@Entry
3501@Component
3502struct Index {
3503  private stack: NavPathStack = new NavPathStack();
3504
3505  @Builder
3506  PageBuilder(name: string) {
3507    PageOne()
3508  }
3509
3510  aboutToAppear() {
3511    let obs = this.getUIContext().getUIObserver();
3512    obs.on('navDestinationSwitch', callBackFunc);
3513  }
3514
3515  aboutToDisappear() {
3516    let obs = this.getUIContext().getUIObserver();
3517    obs.off('navDestinationSwitch', callBackFunc);
3518  }
3519
3520  build() {
3521    Column() {
3522      Navigation(this.stack) {
3523        Button("push").onClick(() => {
3524          this.stack.pushPath({name: "pageOne"});
3525        })
3526      }
3527      .title("Navigation")
3528      .navDestination(this.PageBuilder)
3529    }
3530    .width('100%')
3531    .height('100%')
3532  }
3533}
3534```
3535
3536### off('navDestinationSwitch')<sup>12+</sup>
3537
3538off(type: 'navDestinationSwitch', callback?: Callback\<observer.NavDestinationSwitchInfo\>): void
3539
3540Unsubscribes from the page switching event of the **Navigation** component.
3541
3542**Atomic service API**: This API can be used in atomic services since API version 12.
3543
3544**System capability**: SystemCapability.ArkUI.ArkUI.Full
3545
3546**Parameters**
3547
3548| Name  | Type                                                        | Mandatory| Description                                                        |
3549| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3550| type     | string                                                       | Yes  | Event type. The value **'navDestinationSwitch'** indicates the page switching event of the **Navigation** component.|
3551| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\>        | No  | Callback to be unregistered.                |
3552
3553For the sample code, see the sample code of the **UIObserver.on('navDestinationSwitch')** API.
3554
3555### on('navDestinationSwitch')<sup>12+</sup>
3556
3557on(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback: Callback\<observer.NavDestinationSwitchInfo\>): void
3558
3559Subscribes to the page switching event of the **Navigation** component.
3560
3561**Atomic service API**: This API can be used in atomic services since API version 12.
3562
3563**System capability**: SystemCapability.ArkUI.ArkUI.Full
3564
3565**Parameters**
3566
3567| Name  | Type                                                        | Mandatory| Description                                                        |
3568| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3569| type     | string                                                       | Yes  | Event type. The value **'navDestinationSwitch'** indicates the page switching event of the **Navigation** component.|
3570| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12)        | Yes  | Observer options.  |
3571| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\>        | Yes  | Callback used to return the information about the page switching event.                |
3572
3573**Example**
3574
3575```ts
3576// Index.ets
3577// Demo UIObserver.on('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback)
3578// UIObserver.off('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback)
3579import { uiObserver } from '@kit.ArkUI';
3580
3581@Component
3582struct PageOne {
3583  build() {
3584    NavDestination() {
3585      Text("pageOne")
3586    }.title("pageOne")
3587  }
3588}
3589
3590function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) {
3591  console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`)
3592}
3593
3594@Entry
3595@Component
3596struct Index {
3597  private stack: NavPathStack = new NavPathStack();
3598
3599  @Builder
3600  PageBuilder(name: string) {
3601    PageOne()
3602  }
3603
3604  aboutToAppear() {
3605    let obs = this.getUIContext().getUIObserver();
3606    obs.on('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc)
3607  }
3608
3609  aboutToDisappear() {
3610    let obs = this.getUIContext().getUIObserver();
3611    obs.off('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc)
3612  }
3613
3614  build() {
3615    Column() {
3616      Navigation(this.stack) {
3617        Button("push").onClick(() => {
3618          this.stack.pushPath({name: "pageOne"});
3619        })
3620      }
3621      .id("myNavId")
3622      .title("Navigation")
3623      .navDestination(this.PageBuilder)
3624    }
3625    .width('100%')
3626    .height('100%')
3627  }
3628}
3629```
3630
3631### off('navDestinationSwitch')<sup>12+</sup>
3632
3633off(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback?: Callback\<observer.NavDestinationSwitchInfo\>): void
3634
3635Unsubscribes from the page switching event of the **Navigation** component.
3636
3637**Atomic service API**: This API can be used in atomic services since API version 12.
3638
3639**System capability**: SystemCapability.ArkUI.ArkUI.Full
3640
3641**Parameters**
3642
3643| Name  | Type                                                        | Mandatory| Description                                                        |
3644| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3645| type     | string                                                       | Yes  | Event type. The value **'navDestinationSwitch'** indicates the page switching event of the **Navigation** component.|
3646| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12)        | Yes  | Observer options.  |
3647| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\>        | No  | Callback to be unregistered.                |
3648
3649For the sample code, see the sample code of the **UIObserver.on('navDestinationSwitch')** API.
3650
3651### on('willClick')<sup>12+</sup>
3652
3653on(type: 'willClick', callback: GestureEventListenerCallback): void
3654
3655Subscribes to the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3656
3657**Atomic service API**: This API can be used in atomic services since API version 12.
3658
3659**System capability**: SystemCapability.ArkUI.ArkUI.Full
3660
3661**Parameters**
3662
3663| Name  | Type                                                        | Mandatory| Description                                                        |
3664| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3665| 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.|
3666| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | Yes  | Callback used to return the **GestureEvent** object of the click event and the FrameNode of the component. |
3667
3668**Example**
3669
3670```ts
3671// Used in page components.
3672import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3673
3674// callback is a callback defined by you.
3675let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
3676let observer: UIObserver = this.getUIContext().getUIObserver();
3677observer.on('willClick', callback);
3678```
3679
3680### off('willClick')<sup>12+</sup>
3681
3682off(type: 'willClick', callback?: GestureEventListenerCallback): void
3683
3684Unsubscribes from the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3685
3686**Atomic service API**: This API can be used in atomic services since API version 12.
3687
3688**System capability**: SystemCapability.ArkUI.ArkUI.Full
3689
3690**Parameters**
3691
3692| Name  | Type                                                        | Mandatory| Description                                                 |
3693| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
3694| type     | string                                                       | Yes  | Event type. The value **'willClick'** indicates the dispatch of click event instructions.|
3695| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | No  | Callback to be unregistered.                               |
3696
3697**Example**
3698
3699```ts
3700// Used in page components.
3701import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3702
3703// callback is a callback defined by you.
3704let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
3705let observer: UIObserver = this.getUIContext().getUIObserver();
3706observer.off('willClick', callback);
3707```
3708
3709### on('didClick')<sup>12+</sup>
3710
3711on(type: 'didClick', callback: GestureEventListenerCallback): void
3712
3713Subscribes to the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3714
3715**Atomic service API**: This API can be used in atomic services since API version 12.
3716
3717**System capability**: SystemCapability.ArkUI.ArkUI.Full
3718
3719**Parameters**
3720
3721| Name  | Type                                                        | Mandatory| Description                                                        |
3722| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3723| 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.|
3724| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | Yes  | Callback used to return the **GestureEvent** object of the click event and the FrameNode of the component. |
3725
3726**Example**
3727
3728```ts
3729// Used in page components.
3730import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3731
3732// callback is a callback defined by you.
3733let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
3734let observer: UIObserver = this.getUIContext().getUIObserver();
3735observer.on('didClick', callback);
3736```
3737
3738### off('didClick')<sup>12+</sup>
3739
3740off(type: 'didClick', callback?: GestureEventListenerCallback): void
3741
3742Unsubscribes from the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3743
3744**Atomic service API**: This API can be used in atomic services since API version 12.
3745
3746**System capability**: SystemCapability.ArkUI.ArkUI.Full
3747
3748**Parameters**
3749
3750| Name  | Type                                                        | Mandatory| Description                                                |
3751| -------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------- |
3752| type     | string                                                       | Yes  | Event type. The value **'didClick'** indicates the dispatch of click event instructions.|
3753| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | No  | Callback to be unregistered.                              |
3754
3755**Example**
3756
3757```ts
3758// Used in page components.
3759import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3760
3761// callback is a callback defined by you.
3762let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
3763let observer: UIObserver = this.getUIContext().getUIObserver();
3764observer.off('didClick', callback);
3765```
3766
3767### on('willClick')<sup>12+</sup>
3768
3769on(type: 'willClick', callback: ClickEventListenerCallback): void
3770
3771Subscribes to the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3772
3773**Atomic service API**: This API can be used in atomic services since API version 12.
3774
3775**System capability**: SystemCapability.ArkUI.ArkUI.Full
3776
3777**Parameters**
3778
3779| Name  | Type                                                       | Mandatory| Description                                                        |
3780| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
3781| 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.|
3782| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | Yes  | Callback used to return the **ClickEvent** object and the FrameNode of the component.   |
3783
3784**Example**
3785
3786```ts
3787// Used in page components.
3788import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3789
3790// callback is a callback defined by you.
3791let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
3792let observer: UIObserver = this.getUIContext().getUIObserver();
3793observer.on('willClick', callback);
3794```
3795
3796### off('willClick')<sup>12+</sup>
3797
3798off(type: 'willClick', callback?: ClickEventListenerCallback): void
3799
3800Unsubscribes from the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3801
3802**Atomic service API**: This API can be used in atomic services since API version 12.
3803
3804**System capability**: SystemCapability.ArkUI.ArkUI.Full
3805
3806**Parameters**
3807
3808| Name  | Type                                                       | Mandatory| Description                                                 |
3809| -------- | ----------------------------------------------------------- | ---- | ----------------------------------------------------- |
3810| type     | string                                                      | Yes  | Event type. The value **'willClick'** indicates the dispatch of click event instructions.|
3811| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | No  | Callback to be unregistered.                               |
3812
3813**Example**
3814
3815```ts
3816// Used in page components.
3817import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3818
3819// callback is a callback defined by you.
3820let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
3821let observer: UIObserver = this.getUIContext().getUIObserver();
3822observer.off('willClick', callback);
3823```
3824
3825### on('didClick')<sup>12+</sup>
3826
3827on(type: 'didClick', callback: ClickEventListenerCallback): void
3828
3829Subscribes to the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3830
3831**Atomic service API**: This API can be used in atomic services since API version 12.
3832
3833**System capability**: SystemCapability.ArkUI.ArkUI.Full
3834
3835**Parameters**
3836
3837| Name  | Type                                                       | Mandatory| Description                                                        |
3838| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
3839| 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.|
3840| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | Yes  | Callback used to return the **ClickEvent** object and the FrameNode of the component.   |
3841
3842**Example**
3843
3844```ts
3845// Used in page components.
3846import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3847
3848// callback is a callback defined by you.
3849let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
3850let observer: UIObserver = this.getUIContext().getUIObserver();
3851observer.on('didClick', callback);
3852```
3853
3854### off('didClick')<sup>12+</sup>
3855
3856off(type: 'didClick', callback?: ClickEventListenerCallback): void
3857
3858Unsubscribes from the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported.
3859
3860**Atomic service API**: This API can be used in atomic services since API version 12.
3861
3862**System capability**: SystemCapability.ArkUI.ArkUI.Full
3863
3864**Parameters**
3865
3866| Name  | Type                                                       | Mandatory| Description                                                |
3867| -------- | ----------------------------------------------------------- | ---- | ---------------------------------------------------- |
3868| type     | string                                                      | Yes  | Event type. The value **'didClick'** indicates the dispatch of click event instructions.|
3869| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | No  | Callback to be unregistered.                              |
3870
3871**Example**
3872
3873```ts
3874// Used in page components.
3875import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
3876
3877// callback is a callback defined by you.
3878let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
3879let observer: UIObserver = this.getUIContext().getUIObserver();
3880observer.off('didClick', callback);
3881```
3882
3883### on('tabContentUpdate')<sup>12+</sup>
3884
3885on(type: 'tabContentUpdate', callback: Callback\<observer.TabContentInfo\>): void
3886
3887Subscribes to the **TabContent** switching event.
3888
3889**Atomic service API**: This API can be used in atomic services since API version 12.
3890
3891**System capability**: SystemCapability.ArkUI.ArkUI.Full
3892
3893**Parameters**
3894
3895| Name  | Type                                                        | Mandatory| Description                                                        |
3896| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3897| type     | string                                                       | Yes  | Event type. The value **'tabContentUpdate'** indicates the **TabContent** switching event.|
3898| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | Yes  | Callback used to return the information about the **TabContent** switching event.|
3899
3900**Example**
3901
3902```ts
3903import { uiObserver } from '@kit.ArkUI';
3904
3905function callbackFunc(info: uiObserver.TabContentInfo) {
3906  console.info('tabContentUpdate', JSON.stringify(info));
3907}
3908
3909@Entry
3910@Component
3911struct TabsExample {
3912
3913  aboutToAppear(): void {
3914    let observer = this.getUIContext().getUIObserver();
3915    observer.on('tabContentUpdate', callbackFunc);
3916  }
3917
3918  aboutToDisappear(): void {
3919    let observer = this.getUIContext().getUIObserver();
3920    observer.off('tabContentUpdate', callbackFunc);
3921  }
3922
3923  build() {
3924    Column() {
3925      Tabs() {
3926        TabContent() {
3927          Column().width('100%').height('100%').backgroundColor('#00CB87')
3928        }.tabBar('green').id('tabContentId0')
3929
3930        TabContent() {
3931          Column().width('100%').height('100%').backgroundColor('#007DFF')
3932        }.tabBar('blue').id('tabContentId1')
3933
3934        TabContent() {
3935          Column().width('100%').height('100%').backgroundColor('#FFBF00')
3936        }.tabBar('yellow').id('tabContentId2')
3937
3938        TabContent() {
3939          Column().width('100%').height('100%').backgroundColor('#E67C92')
3940        }.tabBar('pink').id('tabContentId3')
3941      }
3942      .width(360)
3943      .height(296)
3944      .backgroundColor('#F1F3F5')
3945      .id('tabsId')
3946    }.width('100%')
3947  }
3948}
3949```
3950
3951### off('tabContentUpdate')<sup>12+</sup>
3952
3953off(type: 'tabContentUpdate', callback?: Callback\<observer.TabContentInfo\>): void
3954
3955Unsubscribes from the **TabContent** switching event.
3956
3957**Atomic service API**: This API can be used in atomic services since API version 12.
3958
3959**System capability**: SystemCapability.ArkUI.ArkUI.Full
3960
3961**Parameters**
3962
3963| Name  | Type                                                        | Mandatory| Description                                                        |
3964| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3965| type     | string                                                       | Yes  | Event type. The value **'tabContentUpdate'** indicates the **TabContent** switching event.|
3966| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | No  | Callback to be unregistered.|
3967
3968**Example**
3969
3970See the example of [on('tabContentUpdate')](#ontabcontentupdate12).
3971
3972### on('tabContentUpdate')<sup>12+</sup>
3973
3974on(type: 'tabContentUpdate', options: observer.ObserverOptions, callback: Callback\<observer.TabContentInfo\>): void
3975
3976Subscribes to the **TabContent** switching event.
3977
3978**Atomic service API**: This API can be used in atomic services since API version 12.
3979
3980**System capability**: SystemCapability.ArkUI.ArkUI.Full
3981
3982**Parameters**
3983
3984| Name  | Type                                                        | Mandatory| Description                                                        |
3985| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
3986| type     | string                                                       | Yes  | Event type. The value **'tabContentUpdate'** indicates the **TabContent** switching event.|
3987| options  | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | Yes  | ID of the target **Tabs** component.|
3988| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | Yes  | Callback used to return the information about the **TabContent** switching event.|
3989
3990**Example**
3991
3992```ts
3993import { uiObserver } from '@kit.ArkUI';
3994
3995function callbackFunc(info: uiObserver.TabContentInfo) {
3996  console.info('tabContentUpdate', JSON.stringify(info));
3997}
3998
3999@Entry
4000@Component
4001struct TabsExample {
4002
4003  aboutToAppear(): void {
4004    let observer = this.getUIContext().getUIObserver();
4005    observer.on('tabContentUpdate', { id: 'tabsId' }, callbackFunc);
4006  }
4007
4008  aboutToDisappear(): void {
4009    let observer = this.getUIContext().getUIObserver();
4010    observer.off('tabContentUpdate', { id: 'tabsId' }, callbackFunc);
4011  }
4012
4013  build() {
4014    Column() {
4015      Tabs() {
4016        TabContent() {
4017          Column().width('100%').height('100%').backgroundColor('#00CB87')
4018        }.tabBar('green').id('tabContentId0')
4019
4020        TabContent() {
4021          Column().width('100%').height('100%').backgroundColor('#007DFF')
4022        }.tabBar('blue').id('tabContentId1')
4023
4024        TabContent() {
4025          Column().width('100%').height('100%').backgroundColor('#FFBF00')
4026        }.tabBar('yellow').id('tabContentId2')
4027
4028        TabContent() {
4029          Column().width('100%').height('100%').backgroundColor('#E67C92')
4030        }.tabBar('pink').id('tabContentId3')
4031      }
4032      .width(360)
4033      .height(296)
4034      .backgroundColor('#F1F3F5')
4035      .id('tabsId')
4036    }.width('100%')
4037  }
4038}
4039```
4040
4041### off('tabContentUpdate')<sup>12+</sup>
4042
4043off(type: 'tabContentUpdate', options: observer.ObserverOptions, callback?: Callback\<observer.TabContentInfo\>): void
4044
4045Unsubscribes from the **TabContent** switching event.
4046
4047**Atomic service API**: This API can be used in atomic services since API version 12.
4048
4049**System capability**: SystemCapability.ArkUI.ArkUI.Full
4050
4051**Parameters**
4052
4053| Name  | Type                                                        | Mandatory| Description                                                        |
4054| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
4055| type     | string                                                       | Yes  | Event type. The value **'tabContentUpdate'** indicates the **TabContent** switching event.|
4056| options  | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | Yes  | ID of the target **Tabs** component.|
4057| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | No  | Callback to be unregistered.|
4058
4059**Example**
4060
4061See the example of [on('tabContentUpdate')](#ontabcontentupdate12-1).
4062
4063## GestureEventListenerCallback<sup>12+</sup>
4064type GestureEventListenerCallback = (event: GestureEvent, node?: FrameNode) => void
4065
4066Defines a callback for gesture events in ArkTS.
4067
4068**Atomic service API**: This API can be used in atomic services since API version 12.
4069
4070**System capability**: SystemCapability.ArkUI.ArkUI.Full
4071
4072**Parameters**
4073
4074| Name | Type  | Mandatory| Description                         |
4075| ------- | ------ | ---- | --------------------------- |
4076| event | [GestureEvent](../apis-arkui/arkui-ts/ts-gesture-settings.md#gestureevent)| Yes| Information about the gesture event that triggers the callback.|
4077| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | No| Component bound to the gesture event.|
4078
4079## ClickEventListenerCallback<sup>12+</sup>
4080type ClickEventListenerCallback = (event: ClickEvent, node?: FrameNode) => void
4081
4082Defines a callback for click events in ArkTS.
4083
4084**Atomic service API**: This API can be used in atomic services since API version 12.
4085
4086**System capability**: SystemCapability.ArkUI.ArkUI.Full
4087
4088**Parameters**
4089
4090| Name | Type  | Mandatory| Description                         |
4091| ------- | ------ | ---- | --------------------------- |
4092| event | [ClickEvent](../apis-arkui/arkui-ts/ts-universal-events-click.md#clickevent)| Yes| Information about the click event that triggers the callback.|
4093| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | No| Component bound to the click event.|
4094
4095## MediaQuery
4096
4097In 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.
4098
4099### matchMediaSync
4100
4101matchMediaSync(condition: string): mediaQuery.MediaQueryListener
4102
4103Sets the media query criteria and returns the corresponding listening handle.
4104
4105**Atomic service API**: This API can be used in atomic services since API version 11.
4106
4107**System capability**: SystemCapability.ArkUI.ArkUI.Full
4108
4109**Parameters**
4110
4111| Name      | Type    | Mandatory  | Description                                      |
4112| --------- | ------ | ---- | ---------------------------------------- |
4113| condition | string | Yes   | Media query condition. For details, see [Syntax](../../ui/arkts-layout-development-media-query.md#syntax).|
4114
4115**Return value**
4116
4117| Type                                                        | Description                                        |
4118| ------------------------------------------------------------ | -------------------------------------------- |
4119| [mediaQuery.MediaQueryListener](js-apis-mediaquery.md#mediaquerylistener) | Listening handle to a media event, which is used to register or unregister the listening callback.|
4120
4121**Example**
4122
4123<!--code_no_check-->
4124```ts
4125import { MediaQuery } from '@kit.ArkUI';
4126
4127let mediaquery: MediaQuery = uiContext.getMediaQuery();
4128let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events.
4129```
4130
4131## Router
4132
4133In 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.
4134
4135### pushUrl
4136
4137pushUrl(options: router.RouterOptions): Promise&lt;void&gt;
4138
4139Navigates to a specified page in the application. This API uses a promise to return the result.
4140
4141**Atomic service API**: This API can be used in atomic services since API version 11.
4142
4143**System capability**: SystemCapability.ArkUI.ArkUI.Full
4144
4145**Parameters**
4146
4147| Name    | Type                                      | Mandatory  | Description       |
4148| ------- | ---------------------------------------- | ---- | --------- |
4149| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Page routing parameters.|
4150
4151**Return value**
4152
4153| Type                 | Description     |
4154| ------------------- | ------- |
4155| Promise&lt;void&gt; | Promise used to return the result.|
4156
4157**Error codes**
4158
4159For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4160
4161| ID | Error Message                              |
4162| ------ | ---------------------------------- |
4163| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4164| 100001 | Internal error. |
4165| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist.           |
4166| 100003 | Page stack error. Too many pages are pushed.  |
4167
4168**Example**
4169
4170```ts
4171import { BusinessError } from '@kit.BasicServicesKit'
4172
4173@Entry
4174@Component
4175struct Index {
4176  async routePage() {
4177    this.getUIContext().getRouter().pushUrl({
4178        url: 'pages/routerpage2',
4179        params: {
4180          data1: 'message',
4181          data2: {
4182            data3: [123, 456, 789]
4183          }
4184        }
4185      })
4186      .then(() => {
4187        console.info('succeeded')
4188      })
4189      .catch((error: BusinessError) => {
4190        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
4191      })
4192  }
4193
4194  build() {
4195    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4196      Button() {
4197        Text('next page')
4198          .fontSize(25)
4199          .fontWeight(FontWeight.Bold)
4200      }.type(ButtonType.Capsule)
4201      .margin({ top: 20 })
4202      .backgroundColor('#ccc')
4203      .onClick(() => {
4204        this.routePage()
4205      })
4206    }
4207    .width('100%')
4208    .height('100%')
4209  }
4210}
4211```
4212
4213### pushUrl
4214
4215pushUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;): void
4216
4217Navigates to a specified page in the application.
4218
4219**Atomic service API**: This API can be used in atomic services since API version 11.
4220
4221**System capability**: SystemCapability.ArkUI.ArkUI.Full
4222
4223**Parameters**
4224
4225| Name     | Type                                      | Mandatory  | Description       |
4226| -------- | ---------------------------------------- | ---- | --------- |
4227| options  | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Page routing parameters.|
4228| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.  |
4229
4230**Error codes**
4231
4232For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4233
4234| ID | Error Message                              |
4235| ------ | ---------------------------------- |
4236| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4237| 100001 | Internal error. |
4238| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist.           |
4239| 100003 | Page stack error. Too many pages are pushed.  |
4240
4241**Example**
4242
4243```ts
4244import { BusinessError } from '@kit.BasicServicesKit'
4245
4246@Entry
4247@Component
4248struct Index {
4249  async routePage() {
4250    this.getUIContext().getRouter().pushUrl({
4251      url: 'pages/routerpage2',
4252      params: {
4253        data1: 'message',
4254        data2: {
4255          data3: [123, 456, 789]
4256        }
4257      }
4258    }, (err: Error) => {
4259      if (err) {
4260        let message = (err as BusinessError).message;
4261        let code = (err as BusinessError).code;
4262        console.error(`pushUrl failed, code is ${code}, message is ${message}`);
4263        return;
4264      }
4265      console.info('pushUrl success');
4266    })
4267  }
4268
4269  build() {
4270    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4271      Button() {
4272        Text('next page')
4273          .fontSize(25)
4274          .fontWeight(FontWeight.Bold)
4275      }.type(ButtonType.Capsule)
4276      .margin({ top: 20 })
4277      .backgroundColor('#ccc')
4278      .onClick(() => {
4279        this.routePage()
4280      })
4281    }
4282    .width('100%')
4283    .height('100%')
4284  }
4285}
4286```
4287
4288### pushUrl
4289
4290pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
4291
4292Navigates to a specified page in the application. This API uses a promise to return the result.
4293
4294**Atomic service API**: This API can be used in atomic services since API version 11.
4295
4296**System capability**: SystemCapability.ArkUI.ArkUI.Full
4297
4298**Parameters**
4299
4300| Name    | Type                                      | Mandatory  | Description        |
4301| ------- | ---------------------------------------- | ---- | ---------- |
4302| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Page routing parameters. |
4303| mode    | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
4304
4305**Return value**
4306
4307| Type                 | Description     |
4308| ------------------- | ------- |
4309| Promise&lt;void&gt; | Promise used to return the result.|
4310
4311**Error codes**
4312
4313For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4314
4315| ID | Error Message                              |
4316| ------ | ---------------------------------- |
4317| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4318| 100001 | Internal error. |
4319| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist.           |
4320| 100003 | Page stack error. Too many pages are pushed.  |
4321
4322**Example**
4323
4324```ts
4325import { router } from '@kit.ArkUI';
4326import { BusinessError } from '@kit.BasicServicesKit'
4327
4328class RouterTmp {
4329  Standard: router.RouterMode = router.RouterMode.Standard
4330}
4331
4332let rtm: RouterTmp = new RouterTmp()
4333
4334@Entry
4335@Component
4336struct Index {
4337  async routePage() {
4338    this.getUIContext().getRouter().pushUrl({
4339        url: 'pages/routerpage2',
4340        params: {
4341          data1: 'message',
4342          data2: {
4343            data3: [123, 456, 789]
4344          }
4345        }
4346      }, rtm.Standard)
4347      .then(() => {
4348        console.info('succeeded')
4349      })
4350      .catch((error: BusinessError) => {
4351        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
4352      })
4353  }
4354
4355  build() {
4356    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4357      Button() {
4358        Text('next page')
4359          .fontSize(25)
4360          .fontWeight(FontWeight.Bold)
4361      }.type(ButtonType.Capsule)
4362      .margin({ top: 20 })
4363      .backgroundColor('#ccc')
4364      .onClick(() => {
4365        this.routePage()
4366      })
4367    }
4368    .width('100%')
4369    .height('100%')
4370  }
4371}
4372```
4373
4374### pushUrl
4375
4376pushUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
4377
4378Navigates to a specified page in the application.
4379
4380**Atomic service API**: This API can be used in atomic services since API version 11.
4381
4382**System capability**: SystemCapability.ArkUI.ArkUI.Full
4383
4384**Parameters**
4385
4386| Name     | Type                                      | Mandatory  | Description        |
4387| -------- | ---------------------------------------- | ---- | ---------- |
4388| options  | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Page routing parameters. |
4389| mode     | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
4390| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.   |
4391
4392**Error codes**
4393
4394For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4395
4396| ID | Error Message                              |
4397| ------ | ---------------------------------- |
4398| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4399| 100001 | Internal error. |
4400| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist.           |
4401| 100003 | Page stack error. Too many pages are pushed.  |
4402
4403**Example**
4404
4405```ts
4406import { router } from '@kit.ArkUI';
4407import { BusinessError } from '@kit.BasicServicesKit'
4408
4409class RouterTmp {
4410  Standard: router.RouterMode = router.RouterMode.Standard
4411}
4412
4413let rtm: RouterTmp = new RouterTmp()
4414
4415@Entry
4416@Component
4417struct Index {
4418  async routePage() {
4419    this.getUIContext().getRouter().pushUrl({
4420      url: 'pages/routerpage2',
4421      params: {
4422        data1: 'message',
4423        data2: {
4424          data3: [123, 456, 789]
4425        }
4426      }
4427    }, rtm.Standard, (err) => {
4428      if (err) {
4429        let message = (err as BusinessError).message;
4430        let code = (err as BusinessError).code;
4431        console.error(`pushUrl failed, code is ${code}, message is ${message}`);
4432        return;
4433      }
4434      console.info('pushUrl success');
4435    })
4436  }
4437
4438  build() {
4439    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4440      Button() {
4441        Text('next page')
4442          .fontSize(25)
4443          .fontWeight(FontWeight.Bold)
4444      }.type(ButtonType.Capsule)
4445      .margin({ top: 20 })
4446      .backgroundColor('#ccc')
4447      .onClick(() => {
4448        this.routePage()
4449      })
4450    }
4451    .width('100%')
4452    .height('100%')
4453  }
4454}
4455```
4456
4457### replaceUrl
4458
4459replaceUrl(options: router.RouterOptions): Promise&lt;void&gt;
4460
4461Replaces the current page with another one in the application and destroys the current page. This API uses a promise to return the result.
4462
4463**Atomic service API**: This API can be used in atomic services since API version 11.
4464
4465**System capability**: SystemCapability.ArkUI.ArkUI.Full
4466
4467**Parameters**
4468
4469| Name    | Type                                      | Mandatory  | Description       |
4470| ------- | ---------------------------------------- | ---- | --------- |
4471| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Description of the new page.|
4472
4473**Return value**
4474
4475| Type                 | Description     |
4476| ------------------- | ------- |
4477| Promise&lt;void&gt; | Promise used to return the result.|
4478
4479**Error codes**
4480
4481For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4482
4483| ID | Error Message                                    |
4484| ------ | ---------------------------------------- |
4485| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4486| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
4487| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist.                 |
4488
4489**Example**
4490
4491```ts
4492import { BusinessError } from '@kit.BasicServicesKit'
4493
4494@Entry
4495@Component
4496struct Index {
4497  async routePage() {
4498    this.getUIContext().getRouter().replaceUrl({
4499        url: 'pages/detail',
4500        params: {
4501          data1: 'message'
4502        }
4503      })
4504      .then(() => {
4505        console.info('succeeded')
4506      })
4507      .catch((error: BusinessError) => {
4508        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
4509      })
4510  }
4511
4512  build() {
4513    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4514      Button() {
4515        Text('next page')
4516          .fontSize(25)
4517          .fontWeight(FontWeight.Bold)
4518      }.type(ButtonType.Capsule)
4519      .margin({ top: 20 })
4520      .backgroundColor('#ccc')
4521      .onClick(() => {
4522        this.routePage()
4523      })
4524    }
4525    .width('100%')
4526    .height('100%')
4527  }
4528}
4529```
4530
4531### replaceUrl
4532
4533replaceUrl(options: router.RouterOptions, callback: AsyncCallback&lt;void&gt;): void
4534
4535Replaces the current page with another one in the application and destroys the current page.
4536
4537**Atomic service API**: This API can be used in atomic services since API version 11.
4538
4539**System capability**: SystemCapability.ArkUI.ArkUI.Full
4540
4541**Parameters**
4542
4543| Name     | Type                                      | Mandatory  | Description       |
4544| -------- | ---------------------------------------- | ---- | --------- |
4545| options  | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Description of the new page.|
4546| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.  |
4547
4548**Error codes**
4549
4550For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4551
4552| ID | Error Message                                    |
4553| ------ | ---------------------------------------- |
4554| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4555| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
4556| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. |
4557
4558**Example**
4559
4560```ts
4561import { BusinessError } from '@kit.BasicServicesKit'
4562
4563@Entry
4564@Component
4565struct Index {
4566  async routePage() {
4567    this.getUIContext().getRouter().replaceUrl({
4568      url: 'pages/detail',
4569      params: {
4570        data1: 'message'
4571      }
4572    }, (err: Error) => {
4573      if (err) {
4574        let message = (err as BusinessError).message;
4575        let code = (err as BusinessError).code;
4576        console.error(`replaceUrl failed, code is ${code}, message is ${message}`);
4577        return;
4578      }
4579      console.info('replaceUrl success');
4580    })
4581  }
4582
4583  build() {
4584    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4585      Button() {
4586        Text('next page')
4587          .fontSize(25)
4588          .fontWeight(FontWeight.Bold)
4589      }.type(ButtonType.Capsule)
4590      .margin({ top: 20 })
4591      .backgroundColor('#ccc')
4592      .onClick(() => {
4593        this.routePage()
4594      })
4595    }
4596    .width('100%')
4597    .height('100%')
4598  }
4599}
4600```
4601
4602### replaceUrl
4603
4604replaceUrl(options: router.RouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
4605
4606Replaces the current page with another one in the application and destroys the current page. This API uses a promise to return the result.
4607
4608**Atomic service API**: This API can be used in atomic services since API version 11.
4609
4610**System capability**: SystemCapability.ArkUI.ArkUI.Full
4611
4612**Parameters**
4613
4614| Name    | Type                                      | Mandatory  | Description        |
4615| ------- | ---------------------------------------- | ---- | ---------- |
4616| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Description of the new page. |
4617| mode    | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
4618
4619**Return value**
4620
4621| Type                 | Description     |
4622| ------------------- | ------- |
4623| Promise&lt;void&gt; | Promise used to return the result.|
4624
4625**Error codes**
4626
4627For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4628
4629| ID | Error Message                                    |
4630| ------ | ---------------------------------------- |
4631| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4632| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. |
4633| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist.                 |
4634
4635**Example**
4636
4637```ts
4638import { router } from '@kit.ArkUI';
4639import { BusinessError } from '@kit.BasicServicesKit'
4640
4641class RouterTmp {
4642  Standard: router.RouterMode = router.RouterMode.Standard
4643}
4644
4645let rtm: RouterTmp = new RouterTmp()
4646
4647@Entry
4648@Component
4649struct Index {
4650  async routePage() {
4651    this.getUIContext().getRouter().replaceUrl({
4652        url: 'pages/detail',
4653        params: {
4654          data1: 'message'
4655        }
4656      }, rtm.Standard)
4657      .then(() => {
4658        console.info('succeeded')
4659      })
4660      .catch((error: BusinessError) => {
4661        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
4662      })
4663  }
4664
4665  build() {
4666    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4667      Button() {
4668        Text('next page')
4669          .fontSize(25)
4670          .fontWeight(FontWeight.Bold)
4671      }.type(ButtonType.Capsule)
4672      .margin({ top: 20 })
4673      .backgroundColor('#ccc')
4674      .onClick(() => {
4675        this.routePage()
4676      })
4677    }
4678    .width('100%')
4679    .height('100%')
4680  }
4681}
4682```
4683
4684### replaceUrl
4685
4686replaceUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
4687
4688Replaces the current page with another one in the application and destroys the current page.
4689
4690**Atomic service API**: This API can be used in atomic services since API version 11.
4691
4692**System capability**: SystemCapability.ArkUI.ArkUI.Full
4693
4694**Parameters**
4695
4696| Name     | Type                                      | Mandatory  | Description        |
4697| -------- | ---------------------------------------- | ---- | ---------- |
4698| options  | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes   | Description of the new page. |
4699| mode     | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
4700| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.   |
4701
4702**Error codes**
4703
4704For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4705
4706| ID | Error Message                                    |
4707| ------ | ---------------------------------------- |
4708| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4709| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
4710| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist.               |
4711
4712**Example**
4713
4714```ts
4715import { router } from '@kit.ArkUI';
4716import { BusinessError } from '@kit.BasicServicesKit';
4717
4718class RouterTmp {
4719  Standard: router.RouterMode = router.RouterMode.Standard
4720}
4721
4722let rtm: RouterTmp = new RouterTmp()
4723
4724@Entry
4725@Component
4726struct Index {
4727  async routePage() {
4728    this.getUIContext().getRouter().replaceUrl({
4729      url: 'pages/detail',
4730      params: {
4731        data1: 'message'
4732      }
4733    }, rtm.Standard, (err: Error) => {
4734      if (err) {
4735        let message = (err as BusinessError).message;
4736        let code = (err as BusinessError).code;
4737        console.error(`replaceUrl failed, code is ${code}, message is ${message}`);
4738        return;
4739      }
4740      console.info('replaceUrl success');
4741    });
4742  }
4743
4744  build() {
4745    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4746      Button() {
4747        Text('next page')
4748          .fontSize(25)
4749          .fontWeight(FontWeight.Bold)
4750      }.type(ButtonType.Capsule)
4751      .margin({ top: 20 })
4752      .backgroundColor('#ccc')
4753      .onClick(() => {
4754        this.routePage()
4755      })
4756    }
4757    .width('100%')
4758    .height('100%')
4759  }
4760}
4761```
4762
4763### pushNamedRoute
4764
4765pushNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt;
4766
4767Navigates to a page using the named route. This API uses a promise to return the result.
4768
4769**Atomic service API**: This API can be used in atomic services since API version 11.
4770
4771**System capability**: SystemCapability.ArkUI.ArkUI.Full
4772
4773**Parameters**
4774
4775| Name    | Type                                      | Mandatory  | Description       |
4776| ------- | ---------------------------------------- | ---- | --------- |
4777| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Page routing parameters.|
4778
4779**Return value**
4780
4781| Type                 | Description     |
4782| ------------------- | ------- |
4783| Promise&lt;void&gt; | Promise used to return the result.|
4784
4785**Error codes**
4786
4787For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4788
4789| ID | Error Message                              |
4790| ------ | ---------------------------------- |
4791| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4792| 100001 | Internal error. |
4793| 100003 | Page stack error. Too many pages are pushed.  |
4794| 100004 | Named route error. The named route does not exist.   |
4795
4796**Example**
4797
4798```ts
4799import { BusinessError } from '@kit.BasicServicesKit'
4800
4801@Entry
4802@Component
4803struct Index {
4804  async routePage() {
4805    this.getUIContext().getRouter().pushNamedRoute({
4806        name: 'myPage',
4807        params: {
4808          data1: 'message',
4809          data2: {
4810            data3: [123, 456, 789]
4811          }
4812        }
4813      })
4814      .then(() => {
4815        console.info('succeeded')
4816      })
4817      .catch((error: BusinessError) => {
4818        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
4819      })
4820  }
4821
4822  build() {
4823    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4824      Button() {
4825        Text('next page')
4826          .fontSize(25)
4827          .fontWeight(FontWeight.Bold)
4828      }.type(ButtonType.Capsule)
4829      .margin({ top: 20 })
4830      .backgroundColor('#ccc')
4831      .onClick(() => {
4832        this.routePage()
4833      })
4834    }
4835    .width('100%')
4836    .height('100%')
4837  }
4838}
4839```
4840
4841### pushNamedRoute
4842
4843pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt;void&gt;): void
4844
4845Navigates to a page using the named route. This API uses a promise to return the result.
4846
4847**Atomic service API**: This API can be used in atomic services since API version 11.
4848
4849**System capability**: SystemCapability.ArkUI.ArkUI.Full
4850
4851**Parameters**
4852
4853| Name     | Type                                      | Mandatory  | Description       |
4854| -------- | ---------------------------------------- | ---- | --------- |
4855| options  | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Page routing parameters.|
4856| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.  |
4857
4858**Error codes**
4859
4860For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4861
4862| ID | Error Message                              |
4863| ------ | ---------------------------------- |
4864| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4865| 100001 | Internal error. |
4866| 100003 | Page stack error. Too many pages are pushed.  |
4867| 100004 | Named route error. The named route does not exist.  |
4868
4869**Example**
4870
4871```ts
4872import { BusinessError } from '@kit.BasicServicesKit';
4873
4874@Entry
4875@Component
4876struct Index {
4877  async routePage() {
4878    this.getUIContext().getRouter().pushNamedRoute({
4879      name: 'myPage',
4880      params: {
4881        data1: 'message',
4882        data2: {
4883          data3: [123, 456, 789]
4884        }
4885      }
4886    }, (err: Error) => {
4887      if (err) {
4888        let message = (err as BusinessError).message;
4889        let code = (err as BusinessError).code;
4890        console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
4891        return;
4892      }
4893      console.info('pushNamedRoute success');
4894    })
4895  }
4896
4897  build() {
4898    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4899      Button() {
4900        Text('next page')
4901          .fontSize(25)
4902          .fontWeight(FontWeight.Bold)
4903      }.type(ButtonType.Capsule)
4904      .margin({ top: 20 })
4905      .backgroundColor('#ccc')
4906      .onClick(() => {
4907        this.routePage()
4908      })
4909    }
4910    .width('100%')
4911    .height('100%')
4912  }
4913}
4914```
4915### pushNamedRoute
4916
4917pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
4918
4919Navigates to a page using the named route. This API uses a promise to return the result.
4920
4921**Atomic service API**: This API can be used in atomic services since API version 11.
4922
4923**System capability**: SystemCapability.ArkUI.ArkUI.Full
4924
4925**Parameters**
4926
4927| Name    | Type                                      | Mandatory  | Description        |
4928| ------- | ---------------------------------------- | ---- | ---------- |
4929| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Page routing parameters. |
4930| mode    | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
4931
4932**Return value**
4933
4934| Type                 | Description     |
4935| ------------------- | ------- |
4936| Promise&lt;void&gt; | Promise used to return the result.|
4937
4938**Error codes**
4939
4940For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
4941
4942| ID | Error Message                              |
4943| ------ | ---------------------------------- |
4944| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
4945| 100001 | Internal error. |
4946| 100003 | Page stack error. Too many pages are pushed.  |
4947| 100004 | Named route error. The named route does not exist.  |
4948
4949**Example**
4950
4951```ts
4952import { router } from '@kit.ArkUI';
4953import { BusinessError } from '@kit.BasicServicesKit';
4954
4955class RouterTmp{
4956  Standard:router.RouterMode = router.RouterMode.Standard
4957}
4958let rtm:RouterTmp = new RouterTmp()
4959
4960@Entry
4961@Component
4962struct Index {
4963  async routePage() {
4964    this.getUIContext().getRouter().pushNamedRoute({
4965        name: 'myPage',
4966        params: {
4967          data1: 'message',
4968          data2: {
4969            data3: [123, 456, 789]
4970          }
4971        }
4972      }, rtm.Standard)
4973      .then(() => {
4974        console.info('succeeded')
4975      })
4976      .catch((error: BusinessError) => {
4977        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
4978      })
4979  }
4980
4981  build() {
4982    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
4983      Button() {
4984        Text('next page')
4985          .fontSize(25)
4986          .fontWeight(FontWeight.Bold)
4987      }.type(ButtonType.Capsule)
4988      .margin({ top: 20 })
4989      .backgroundColor('#ccc')
4990      .onClick(() => {
4991        this.routePage()
4992      })
4993    }
4994    .width('100%')
4995    .height('100%')
4996  }
4997}
4998```
4999
5000### pushNamedRoute
5001
5002pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
5003
5004Navigates to a page using the named route. This API uses a promise to return the result.
5005
5006**Atomic service API**: This API can be used in atomic services since API version 11.
5007
5008**System capability**: SystemCapability.ArkUI.ArkUI.Full
5009
5010**Parameters**
5011
5012| Name     | Type                                      | Mandatory  | Description        |
5013| -------- | ---------------------------------------- | ---- | ---------- |
5014| options  | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Page routing parameters. |
5015| mode     | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
5016| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.   |
5017
5018**Error codes**
5019
5020For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5021
5022| ID | Error Message                              |
5023| ------ | ---------------------------------- |
5024| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5025| 100001 | Internal error. |
5026| 100003 | Page stack error. Too many pages are pushed.  |
5027| 100004 | Named route error. The named route does not exist.   |
5028
5029**Example**
5030
5031```ts
5032import { router } from '@kit.ArkUI';
5033import { BusinessError } from '@kit.BasicServicesKit';
5034
5035class RouterTmp {
5036  Standard: router.RouterMode = router.RouterMode.Standard
5037}
5038
5039let rtm: RouterTmp = new RouterTmp()
5040
5041@Entry
5042@Component
5043struct Index {
5044  async routePage() {
5045    this.getUIContext().getRouter().pushNamedRoute({
5046      name: 'myPage',
5047      params: {
5048        data1: 'message',
5049        data2: {
5050          data3: [123, 456, 789]
5051        }
5052      }
5053    }, rtm.Standard, (err: Error) => {
5054      if (err) {
5055        let message = (err as BusinessError).message;
5056        let code = (err as BusinessError).code;
5057        console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
5058        return;
5059      }
5060      console.info('pushNamedRoute success');
5061    })
5062  }
5063
5064  build() {
5065    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5066      Button() {
5067        Text('next page')
5068          .fontSize(25)
5069          .fontWeight(FontWeight.Bold)
5070      }.type(ButtonType.Capsule)
5071      .margin({ top: 20 })
5072      .backgroundColor('#ccc')
5073      .onClick(() => {
5074        this.routePage()
5075      })
5076    }
5077    .width('100%')
5078    .height('100%')
5079  }
5080}
5081```
5082
5083### replaceNamedRoute
5084
5085replaceNamedRoute(options: router.NamedRouterOptions): Promise&lt;void&gt;
5086
5087Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.
5088
5089**Atomic service API**: This API can be used in atomic services since API version 11.
5090
5091**System capability**: SystemCapability.ArkUI.ArkUI.Full
5092
5093**Parameters**
5094
5095| Name    | Type                                      | Mandatory  | Description       |
5096| ------- | ---------------------------------------- | ---- | --------- |
5097| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Description of the new page.|
5098
5099**Return value**
5100
5101| Type                 | Description     |
5102| ------------------- | ------- |
5103| Promise&lt;void&gt; | Promise used to return the result.|
5104
5105**Error codes**
5106
5107For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5108
5109| ID | Error Message                                    |
5110| ------ | ---------------------------------------- |
5111| 401      | if the number of parameters is less than 1 or the type of the url parameter is not string. |
5112| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
5113| 100004 | Named route error. The named route does not exist.        |
5114
5115**Example**
5116
5117```ts
5118import { BusinessError } from '@kit.BasicServicesKit';
5119
5120@Entry
5121@Component
5122struct Index {
5123  async routePage() {
5124    this.getUIContext().getRouter().replaceNamedRoute({
5125        name: 'myPage',
5126        params: {
5127          data1: 'message'
5128        }
5129      })
5130      .then(() => {
5131        console.info('succeeded')
5132      })
5133      .catch((error: BusinessError) => {
5134        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
5135      })
5136  }
5137
5138  build() {
5139    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5140      Button() {
5141        Text('next page')
5142          .fontSize(25)
5143          .fontWeight(FontWeight.Bold)
5144      }.type(ButtonType.Capsule)
5145      .margin({ top: 20 })
5146      .backgroundColor('#ccc')
5147      .onClick(() => {
5148        this.routePage()
5149      })
5150    }
5151    .width('100%')
5152    .height('100%')
5153  }
5154}
5155```
5156
5157### replaceNamedRoute
5158
5159replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback&lt;void&gt;): void
5160
5161Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.
5162
5163**Atomic service API**: This API can be used in atomic services since API version 11.
5164
5165**System capability**: SystemCapability.ArkUI.ArkUI.Full
5166
5167**Parameters**
5168
5169| Name     | Type                                      | Mandatory  | Description       |
5170| -------- | ---------------------------------------- | ---- | --------- |
5171| options  | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Description of the new page.|
5172| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.  |
5173
5174**Error codes**
5175
5176For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5177
5178| ID | Error Message                                    |
5179| ------ | ---------------------------------------- |
5180| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5181| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
5182| 100004 | Named route error. The named route does not exist.         |
5183
5184**Example**
5185
5186```ts
5187import { BusinessError } from '@kit.BasicServicesKit';
5188
5189@Entry
5190@Component
5191struct Index {
5192  async routePage() {
5193    this.getUIContext().getRouter().replaceNamedRoute({
5194      name: 'myPage',
5195      params: {
5196        data1: 'message'
5197      }
5198    }, (err: Error) => {
5199      if (err) {
5200        let message = (err as BusinessError).message;
5201        let code = (err as BusinessError).code;
5202        console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`);
5203        return;
5204      }
5205      console.info('replaceNamedRoute success');
5206    })
5207  }
5208
5209  build() {
5210    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5211      Button() {
5212        Text('next page')
5213          .fontSize(25)
5214          .fontWeight(FontWeight.Bold)
5215      }.type(ButtonType.Capsule)
5216      .margin({ top: 20 })
5217      .backgroundColor('#ccc')
5218      .onClick(() => {
5219        this.routePage()
5220      })
5221    }
5222    .width('100%')
5223    .height('100%')
5224  }
5225}
5226```
5227
5228### replaceNamedRoute
5229
5230replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise&lt;void&gt;
5231
5232Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.
5233
5234**Atomic service API**: This API can be used in atomic services since API version 11.
5235
5236**System capability**: SystemCapability.ArkUI.ArkUI.Full
5237
5238**Parameters**
5239
5240| Name    | Type                                      | Mandatory  | Description        |
5241| ------- | ---------------------------------------- | ---- | ---------- |
5242| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Description of the new page. |
5243| mode    | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
5244
5245
5246**Return value**
5247
5248| Type                 | Description     |
5249| ------------------- | ------- |
5250| Promise&lt;void&gt; | Promise used to return the result.|
5251
5252**Error codes**
5253
5254For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5255
5256| ID | Error Message                                    |
5257| ------ | ---------------------------------------- |
5258| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5259| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. |
5260| 100004 | Named route error. The named route does not exist.       |
5261
5262**Example**
5263
5264```ts
5265import { router } from '@kit.ArkUI';
5266import { BusinessError } from '@kit.BasicServicesKit';
5267
5268class RouterTmp {
5269  Standard: router.RouterMode = router.RouterMode.Standard
5270}
5271
5272let rtm: RouterTmp = new RouterTmp()
5273
5274@Entry
5275@Component
5276struct Index {
5277  async routePage() {
5278    this.getUIContext().getRouter().replaceNamedRoute({
5279        name: 'myPage',
5280        params: {
5281          data1: 'message'
5282        }
5283      }, rtm.Standard)
5284      .then(() => {
5285        console.info('succeeded')
5286      })
5287      .catch((error: BusinessError) => {
5288        console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
5289      })
5290  }
5291
5292  build() {
5293    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5294      Button() {
5295        Text('next page')
5296          .fontSize(25)
5297          .fontWeight(FontWeight.Bold)
5298      }.type(ButtonType.Capsule)
5299      .margin({ top: 20 })
5300      .backgroundColor('#ccc')
5301      .onClick(() => {
5302        this.routePage()
5303      })
5304    }
5305    .width('100%')
5306    .height('100%')
5307  }
5308}
5309```
5310
5311### replaceNamedRoute
5312
5313replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback&lt;void&gt;): void
5314
5315Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.
5316
5317**Atomic service API**: This API can be used in atomic services since API version 11.
5318
5319**System capability**: SystemCapability.ArkUI.ArkUI.Full
5320
5321**Parameters**
5322
5323| Name     | Type                                      | Mandatory  | Description        |
5324| -------- | ---------------------------------------- | ---- | ---------- |
5325| options  | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes   | Description of the new page. |
5326| mode     | [router.RouterMode](js-apis-router.md#routermode9) | Yes   | Routing mode.|
5327| callback | AsyncCallback&lt;void&gt;                | Yes   | Callback used to return the result.   |
5328
5329**Error codes**
5330
5331For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5332
5333| ID | Error Message                                    |
5334| ------ | ---------------------------------------- |
5335| 401      | if the number of parameters is less than 1 or the type of the url parameter is not string. |
5336| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
5337| 100004 | Named route error. The named route does not exist.        |
5338
5339**Example**
5340
5341```ts
5342import { router } from '@kit.ArkUI';
5343import { BusinessError } from '@kit.BasicServicesKit';
5344
5345class RouterTmp {
5346  Standard: router.RouterMode = router.RouterMode.Standard
5347}
5348
5349let rtm: RouterTmp = new RouterTmp()
5350
5351@Entry
5352@Component
5353struct Index {
5354  async routePage() {
5355    this.getUIContext().getRouter().replaceNamedRoute({
5356      name: 'myPage',
5357      params: {
5358        data1: 'message'
5359      }
5360    }, rtm.Standard, (err: Error) => {
5361      if (err) {
5362        let message = (err as BusinessError).message;
5363        let code = (err as BusinessError).code;
5364        console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`);
5365        return;
5366      }
5367      console.info('replaceNamedRoute success');
5368    })
5369  }
5370
5371  build() {
5372    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
5373      Button() {
5374        Text('next page')
5375          .fontSize(25)
5376          .fontWeight(FontWeight.Bold)
5377      }.type(ButtonType.Capsule)
5378      .margin({ top: 20 })
5379      .backgroundColor('#ccc')
5380      .onClick(() => {
5381        this.routePage()
5382      })
5383    }
5384    .width('100%')
5385    .height('100%')
5386  }
5387}
5388```
5389
5390### back
5391
5392back(options?: router.RouterOptions ): void
5393
5394Returns to the previous page or a specified page.
5395
5396**Atomic service API**: This API can be used in atomic services since API version 11.
5397
5398**System capability**: SystemCapability.ArkUI.ArkUI.Full
5399
5400**Parameters**
5401
5402| Name    | Type                                      | Mandatory  | Description                                      |
5403| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
5404| 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.|
5405
5406**Example**
5407
5408```ts
5409import { Router } from '@kit.ArkUI';
5410let router: Router = uiContext.getRouter();
5411router.back({url:'pages/detail'});
5412```
5413
5414### back<sup>12+</sup>
5415
5416back(index: number, params?: Object): void;
5417
5418Returns to the specified page.
5419
5420**Atomic service API**: This API can be used in atomic services since API version 12.
5421
5422**System capability**: SystemCapability.ArkUI.ArkUI.Full
5423
5424**Parameters**
5425
5426| Name    | Type                             | Mandatory  | Description        |
5427| ------- | ------------------------------- | ---- | ---------- |
5428| index | number | Yes   | Index of the target page to navigate to. |
5429| params    | Object      | No   | Parameters carried when returning to the page.|
5430
5431**Example**
5432
5433```ts
5434import { Router } from '@kit.ArkUI';
5435
5436let router: Router = uiContext.getRouter();
5437router.back(1);
5438```
5439
5440```ts
5441import { Router } from '@kit.ArkUI';
5442
5443let router: Router = uiContext.getRouter();
5444router.back(1, {info:'From Home'}); // Returning with parameters.
5445```
5446
5447### clear
5448
5449clear(): void
5450
5451Clears all historical pages in the stack and retains only the current page at the top of the stack.
5452
5453**Atomic service API**: This API can be used in atomic services since API version 11.
5454
5455**System capability**: SystemCapability.ArkUI.ArkUI.Full
5456
5457**Example**
5458
5459```ts
5460import { Router } from '@kit.ArkUI';
5461
5462let router: Router = uiContext.getRouter();
5463router.clear();
5464```
5465
5466### getLength
5467
5468getLength(): string
5469
5470Obtains the number of pages in the current stack.
5471
5472**Atomic service API**: This API can be used in atomic services since API version 11.
5473
5474**System capability**: SystemCapability.ArkUI.ArkUI.Full
5475
5476**Return value**
5477
5478| Type    | Description                |
5479| ------ | ------------------ |
5480| string | Number of pages in the stack. The maximum value is **32**.|
5481
5482**Example**
5483
5484```ts
5485import { Router } from '@kit.ArkUI';
5486
5487let router: Router = uiContext.getRouter();
5488let size = router.getLength();
5489console.info('pages stack size = ' + size);
5490```
5491
5492### getState
5493
5494getState(): router.RouterState
5495
5496Obtains state information about the current page.
5497
5498**Atomic service API**: This API can be used in atomic services since API version 11.
5499
5500**System capability**: SystemCapability.ArkUI.ArkUI.Full
5501
5502**Return value**
5503
5504| Type                                      | Description     |
5505| ---------------------------------------- | ------- |
5506| router.[RouterState](js-apis-router.md#routerstate) | Page routing state.|
5507
5508**Example**
5509
5510<!--code_no_check-->
5511```ts
5512import { Router } from '@kit.ArkUI';
5513
5514let router: Router = uiContext.getRouter();
5515let page = router.getState();
5516console.info('current index = ' + page.index);
5517console.info('current name = ' + page.name);
5518console.info('current path = ' + page.path);
5519```
5520
5521### getStateByIndex<sup>12+</sup>
5522
5523getStateByIndex(index: number): router.RouterState | undefined
5524
5525Obtains the status information about a page by its index.
5526
5527**Atomic service API**: This API can be used in atomic services since API version 12.
5528
5529**System capability**: SystemCapability.ArkUI.ArkUI.Full
5530
5531**Parameters**
5532
5533| Name    | Type                             | Mandatory  | Description        |
5534| ------- | ------------------------------- | ---- | ---------- |
5535| index    | number | Yes  | Index of the target page. |
5536
5537**Return value**
5538
5539| Type                         | Description     |
5540| --------------------------- | ------- |
5541| router.[RouterState](js-apis-router.md#routerstate) \| undefined | State information about the target page. **undefined** if the specified index does not exist.|
5542
5543**Example**
5544
5545<!--code_no_check-->
5546```ts
5547import { Router } from '@kit.ArkUI';
5548
5549let router: Router = uiContext.getRouter();
5550let options: router.RouterState | undefined = router.getStateByIndex(1);
5551if (options != undefined) {
5552  console.info('index = ' + options.index);
5553  console.info('name = ' + options.name);
5554  console.info('path = ' + options.path);
5555  console.info('params = ' + options.params);
5556}
5557```
5558### getStateByUrl<sup>12+</sup>
5559
5560getStateByUrl(url: string): Array<router.[RouterState](js-apis-router.md#routerstate)>
5561
5562Obtains the status information about a page by its URL.
5563
5564**Atomic service API**: This API can be used in atomic services since API version 12.
5565
5566**System capability**: SystemCapability.ArkUI.ArkUI.Full
5567
5568**Parameters**
5569
5570| Name    | Type                             | Mandatory  | Description        |
5571| ------- | ------------------------------- | ---- | ---------- |
5572| url    | string | Yes  | URL of the target page. |
5573
5574**Return value**
5575
5576| Type                         | Description     |
5577| --------------------------- | ------- |
5578| Array<router.[RouterState](js-apis-router.md#routerstate)> | Page routing state.|
5579
5580**Example**
5581
5582<!--code_no_check-->
5583```ts
5584import { Router } from '@kit.ArkUI';
5585let router: Router = uiContext.getRouter();
5586let options:Array<router.RouterState> = router.getStateByUrl('pages/index');
5587for (let i: number = 0; i < options.length; i++) {
5588  console.info('index = ' + options[i].index);
5589  console.info('name = ' + options[i].name);
5590  console.info('path = ' + options[i].path);
5591  console.info('params = ' + options[i].params);
5592}
5593```
5594
5595### showAlertBeforeBackPage
5596
5597showAlertBeforeBackPage(options: router.EnableAlertOptions): void
5598
5599Enables the display of a confirm dialog box before returning to the previous page.
5600
5601**Atomic service API**: This API can be used in atomic services since API version 11.
5602
5603**System capability**: SystemCapability.ArkUI.ArkUI.Full
5604
5605**Parameters**
5606
5607| Name    | Type                                      | Mandatory  | Description       |
5608| ------- | ---------------------------------------- | ---- | --------- |
5609| options | [router.EnableAlertOptions](js-apis-router.md#enablealertoptions) | Yes   | Description of the dialog box.|
5610
5611**Error codes**
5612
5613For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md).
5614
5615| ID | Error Message                              |
5616| ------ | ---------------------------------- |
5617| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5618| 100001 | Internal error. |
5619
5620**Example**
5621
5622<!--code_no_check-->
5623```ts
5624import { Router } from '@kit.ArkUI';
5625import { BusinessError } from '@kit.BasicServicesKit';
5626
5627let router: Router = uiContext.getRouter();
5628try {
5629  router.showAlertBeforeBackPage({
5630    message: 'Message Info'
5631  });
5632} catch(error) {
5633  let message = (error as BusinessError).message;
5634  let code = (error as BusinessError).code;
5635  console.error(`showAlertBeforeBackPage failed, code is ${code}, message is ${message}`);
5636}
5637```
5638
5639### hideAlertBeforeBackPage
5640
5641hideAlertBeforeBackPage(): void
5642
5643Disables the display of a confirm dialog box before returning to the previous page.
5644
5645**Atomic service API**: This API can be used in atomic services since API version 11.
5646
5647**System capability**: SystemCapability.ArkUI.ArkUI.Full
5648
5649**Example**
5650
5651<!--code_no_check-->
5652```ts
5653import { Router } from '@kit.ArkUI';
5654
5655let router: Router = uiContext.getRouter();
5656router.hideAlertBeforeBackPage();
5657```
5658
5659### getParams
5660
5661getParams(): Object
5662
5663Obtains the parameters passed from the page that initiates redirection to the current page.
5664
5665**Atomic service API**: This API can be used in atomic services since API version 11.
5666
5667**System capability**: SystemCapability.ArkUI.ArkUI.Full
5668
5669**Return value**
5670
5671| Type    | Description               |
5672| ------ | ----------------- |
5673| Object | Parameters passed from the page that initiates redirection to the current page.|
5674
5675**Example**
5676
5677<!--code_no_check-->
5678
5679```ts
5680import { Router } from '@kit.ArkUI';
5681
5682let router: Router = uiContext.getRouter();
5683router.getParams();
5684```
5685
5686## CustomBuilderWithId<sup>18+</sup>
5687
5688type CustomBuilderWithId = (id: number) =&gt; void
5689
5690The **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.
5691
5692**Atomic service API**: This API can be used in atomic services since API version 18.
5693
5694**System capability**: SystemCapability.ArkUI.ArkUI.Full
5695
5696**Parameters**
5697
5698| Name| Type| Mandatory| Description|
5699| -------- | -------- | -------- | -------- |
5700| id | number | Yes| Component ID.|
5701
5702## TargetInfo<sup>18+</sup>
5703
5704Specifies the target node for component binding.
5705
5706**Atomic service API**: This API can be used in atomic services since API version 18.
5707
5708**System capability**: SystemCapability.ArkUI.ArkUI.Full
5709
5710**Parameters**
5711
5712| Name| Type| Mandatory| Description|
5713| -------- | -------- | -------- | -------- |
5714| 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.|
5715| 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.|
5716
5717## PromptAction
5718
5719In 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.
5720
5721### showToast
5722
5723showToast(options: promptAction.ShowToastOptions): void
5724
5725Shows a toast in the given settings.
5726
5727**Atomic service API**: This API can be used in atomic services since API version 11.
5728
5729**System capability**: SystemCapability.ArkUI.ArkUI.Full
5730
5731**Parameters**
5732
5733| Name    | Type                                      | Mandatory  | Description     |
5734| ------- | ---------------------------------------- | ---- | ------- |
5735| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | Yes   | Toast options.|
5736
5737**Error codes**
5738
5739For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
5740
5741| ID | Error Message                              |
5742| ------ | ---------------------------------- |
5743| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5744| 100001 | Internal error. |
5745
5746**Example**
5747
5748<!--code_no_check-->
5749```ts
5750import { PromptAction } from '@kit.ArkUI';
5751import { BusinessError } from '@kit.BasicServicesKit';
5752
5753let promptAction: PromptAction = uiContext.getPromptAction();
5754try {
5755  promptAction.showToast({
5756    message: 'Message Info',
5757    duration: 2000
5758  });
5759} catch (error) {
5760  let message = (error as BusinessError).message;
5761  let code = (error as BusinessError).code;
5762  console.error(`showToast args error code is ${code}, message is ${message}`);
5763};
5764```
5765
5766### openToast<sup>18+</sup>
5767
5768openToast(options: ShowToastOptions): Promise&lt;number&gt;
5769
5770**Atomic service API**: This API can be used in atomic services since API version 18.
5771
5772**System capability**: SystemCapability.ArkUI.ArkUI.Full
5773
5774**Parameters**
5775
5776| Name | Type                                                        | Mandatory| Description          |
5777| ------- | ------------------------------------------------------------ | ---- | -------------- |
5778| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | Yes  | Toast options.|
5779
5780**Return value**
5781
5782| Type            | Description                                |
5783| ---------------- | ------------------------------------ |
5784| Promise&lt;number&gt; | ID of the toast, which is required in **closeToast**.|
5785
5786**Error codes**
5787
5788For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
5789
5790| ID| Error Message                                                    |
5791| -------- | ------------------------------------------------------------ |
5792| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
5793| 100001   | Internal error.                                              |
5794
5795**Example**
5796
5797```ts
5798import { PromptAction } from '@kit.ArkUI';
5799import { BusinessError } from '@kit.BasicServicesKit';
5800
5801@Entry
5802@Component
5803struct toastExample {
5804  @State toastId: number = 0;
5805  promptAction: PromptAction = this.getUIContext().getPromptAction()
5806
5807  build() {
5808    Column() {
5809      Button('Open Toast')
5810        .height(100)
5811        .onClick(() => {
5812          this.promptAction.openToast({
5813            message: 'Toast Massage',
5814            duration: 10000,
5815          }).then((toastId: number) => {
5816            this.toastId = toastId;
5817          })
5818            .catch((error: BusinessError) => {
5819              console.error(`openToast error code is ${error.code}, message is ${error.message}`)
5820            })
5821        })
5822      Blank().height(50);
5823      Button('Close Toast')
5824        .height(100)
5825        .onClick(() => {
5826          try {
5827            this.promptAction.closeToast(this.toastId);
5828          } catch (error) {
5829            let message = (error as BusinessError).message;
5830            let code = (error as BusinessError).code;
5831            console.error(`CloseToast error code is ${code}, message is ${message}`);
5832          };
5833        })
5834    }.height('100%').width('100%').justifyContent(FlexAlign.Center)
5835  }
5836}
5837```
5838
5839### closeToast<sup>18+</sup>
5840
5841closeToast(toastId: number): void
5842
5843**Atomic service API**: This API can be used in atomic services since API version 18.
5844
5845**System capability**: SystemCapability.ArkUI.ArkUI.Full
5846
5847**Parameters**
5848
5849| Name | Type  | Mandatory| Description                         |
5850| ------- | ------ | ---- | ----------------------------- |
5851| toastId | number | Yes  | ID of the toast to close, which is returned by **openToast**.|
5852
5853**Error codes**
5854
5855For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
5856
5857| ID| Error Message                                                    |
5858| -------- | ------------------------------------------------------------ |
5859| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
5860| 100001   | Internal error.                                              |
5861
5862**Example**
5863
5864See the example for [openToaset18](#opentoast18).
5865
5866### showDialog
5867
5868showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback&lt;promptAction.ShowDialogSuccessResponse&gt;): void
5869
5870Shows a dialog box in the given settings. This API uses an asynchronous callback to return the result.
5871
5872**Atomic service API**: This API can be used in atomic services since API version 11.
5873
5874**System capability**: SystemCapability.ArkUI.ArkUI.Full
5875
5876**Parameters**
5877
5878| Name     | Type                                      | Mandatory  | Description          |
5879| -------- | ---------------------------------------- | ---- | ------------ |
5880| options  | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes   | Dialog box options.|
5881| callback | AsyncCallback&lt;[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)&gt; | Yes   | Callback used to return the dialog box response result.  |
5882
5883**Error codes**
5884
5885For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
5886
5887| ID | Error Message                              |
5888| ------ | ---------------------------------- |
5889| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5890| 100001 | Internal error. |
5891
5892**Example**
5893
5894<!--code_no_check-->
5895
5896```ts
5897import { PromptAction } from '@kit.ArkUI';
5898import { BusinessError } from '@kit.BasicServicesKit';
5899
5900let promptAction: PromptAction = uiContext.getPromptAction();
5901try {
5902  promptAction.showDialog({
5903    title: 'showDialog Title Info',
5904    message: 'Message Info',
5905    buttons: [
5906      {
5907        text: 'button1',
5908        color: '#000000'
5909      },
5910      {
5911        text: 'button2',
5912        color: '#000000'
5913      }
5914    ]
5915  }, (err, data) => {
5916    if (err) {
5917      console.error('showDialog err: ' + err);
5918      return;
5919    }
5920    console.info('showDialog success callback, click button: ' + data.index);
5921  });
5922} catch (error) {
5923  let message = (error as BusinessError).message;
5924  let code = (error as BusinessError).code;
5925  console.error(`showDialog args error code is ${code}, message is ${message}`);
5926};
5927```
5928
5929### showDialog
5930
5931showDialog(options: promptAction.ShowDialogOptions): Promise&lt;promptAction.ShowDialogSuccessResponse&gt;
5932
5933Shows a dialog box. This API uses a promise to return the result.
5934
5935**Atomic service API**: This API can be used in atomic services since API version 11.
5936
5937**System capability**: SystemCapability.ArkUI.ArkUI.Full
5938
5939**Parameters**
5940
5941| Name    | Type                                      | Mandatory  | Description    |
5942| ------- | ---------------------------------------- | ---- | ------ |
5943| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes   | Dialog box options.|
5944
5945**Return value**
5946
5947| Type                                      | Description      |
5948| ---------------------------------------- | -------- |
5949| Promise&lt;[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)&gt; | Promise used to return the dialog box response result.|
5950
5951**Error codes**
5952
5953For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
5954
5955| ID | Error Message                              |
5956| ------ | ---------------------------------- |
5957| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
5958| 100001 | Internal error. |
5959
5960**Example**
5961
5962<!--code_no_check-->
5963```ts
5964import { PromptAction } from '@kit.ArkUI';
5965
5966let promptAction: PromptAction = uiContext.getPromptAction();
5967promptAction.showDialog({
5968  title: 'Title Info',
5969  message: 'Message Info',
5970  buttons: [
5971    {
5972      text: 'button1',
5973      color: '#000000'
5974    },
5975    {
5976      text: 'button2',
5977      color: '#000000'
5978    }
5979  ],
5980})
5981  .then(data => {
5982    console.info('showDialog success, click button: ' + data.index);
5983  })
5984  .catch((err: Error) => {
5985    console.error('showDialog error: ' + err);
5986  })
5987```
5988
5989### showActionMenu<sup>11+</sup>
5990
5991showActionMenu(options: promptAction.ActionMenuOptions, callback: AsyncCallback&lt;[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)&gt;):void
5992
5993Shows an action menu in the given settings. This API uses an asynchronous callback to return the result.
5994
5995**Atomic service API**: This API can be used in atomic services since API version 11.
5996
5997**System capability**: SystemCapability.ArkUI.ArkUI.Full
5998
5999**Parameters**
6000
6001| Name  | Type                                                        | Mandatory| Description              |
6002| -------- | ------------------------------------------------------------ | ---- | ------------------ |
6003| options  | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes  | Action menu options.    |
6004| callback | AsyncCallback&lt;[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)&gt; | Yes  | Callback used to return the action menu response result.|
6005
6006**Error codes**
6007
6008For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6009
6010| ID| Error Message                          |
6011| -------- | ---------------------------------- |
6012| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6013| 100001   | Internal error. |
6014
6015**Example**
6016
6017<!--code_no_check-->
6018```ts
6019import { PromptAction, promptAction  } from '@kit.ArkUI';
6020import { BusinessError } from '@kit.BasicServicesKit';
6021
6022let promptActionF: PromptAction = uiContext.getPromptAction();
6023try {
6024  promptActionF.showActionMenu({
6025    title: 'Title Info',
6026    buttons: [
6027      {
6028        text: 'item1',
6029        color: '#666666'
6030      },
6031      {
6032        text: 'item2',
6033        color: '#000000'
6034      }
6035    ]
6036  }, (err:BusinessError, data:promptAction.ActionMenuSuccessResponse) => {
6037    if (err) {
6038      console.error('showDialog err: ' + err);
6039      return;
6040    }
6041    console.info('showDialog success callback, click button: ' + data.index);
6042  });
6043} catch (error) {
6044  let message = (error as BusinessError).message;
6045  let code = (error as BusinessError).code;
6046  console.error(`showActionMenu args error code is ${code}, message is ${message}`);
6047};
6048```
6049
6050### showActionMenu<sup>(deprecated)</sup>
6051
6052showActionMenu(options: promptAction.ActionMenuOptions, callback: [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)):void
6053
6054Shows an action menu in the given settings. This API uses an asynchronous callback to return the result.
6055
6056This API is deprecated since API version 11. You are advised to use [showActionMenu](#showactionmenu11) instead.
6057
6058**System capability**: SystemCapability.ArkUI.ArkUI.Full
6059
6060**Parameters**
6061
6062| Name  | Type                                                        | Mandatory| Description              |
6063| -------- | ------------------------------------------------------------ | ---- | ------------------ |
6064| options  | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes  | Action menu options.    |
6065| callback | [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse) | Yes  | Callback used to return the action menu response result.|
6066
6067**Error codes**
6068
6069For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6070
6071| ID | Error Message                              |
6072| ------ | ---------------------------------- |
6073| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6074| 100001 | Internal error. |
6075
6076**Example**
6077
6078<!--code_no_check-->
6079```ts
6080import { PromptAction,promptAction  } from '@kit.ArkUI';
6081import { BusinessError } from '@kit.BasicServicesKit';
6082
6083let promptActionF: PromptAction = uiContext.getPromptAction();
6084try {
6085  promptActionF.showActionMenu({
6086    title: 'Title Info',
6087    buttons: [
6088      {
6089        text: 'item1',
6090        color: '#666666'
6091      },
6092      {
6093        text: 'item2',
6094        color: '#000000'
6095      }
6096    ]
6097  }, { index:0 });
6098} catch (error) {
6099  let message = (error as BusinessError).message;
6100  let code = (error as BusinessError).code;
6101  console.error(`showActionMenu args error code is ${code}, message is ${message}`);
6102};
6103```
6104
6105### showActionMenu
6106
6107showActionMenu(options: promptAction.ActionMenuOptions): Promise&lt;promptAction.ActionMenuSuccessResponse&gt;
6108
6109Shows an action menu. This API uses a promise to return the result.
6110
6111**Atomic service API**: This API can be used in atomic services since API version 11.
6112
6113**System capability**: SystemCapability.ArkUI.ArkUI.Full
6114
6115**Parameters**
6116
6117| Name    | Type                                      | Mandatory  | Description     |
6118| ------- | ---------------------------------------- | ---- | ------- |
6119| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes   | Action menu options.|
6120
6121**Return value**
6122
6123| Type                                      | Description     |
6124| ---------------------------------------- | ------- |
6125| Promise&lt;[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)&gt; | Promise used to return the action menu response result.|
6126
6127**Error codes**
6128
6129For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6130
6131| ID | Error Message                              |
6132| ------ | ---------------------------------- |
6133| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6134| 100001 | Internal error. |
6135
6136**Example**
6137
6138<!--code_no_check-->
6139```ts
6140import { PromptAction } from '@kit.ArkUI';
6141
6142let promptAction: PromptAction = uiContext.getPromptAction();
6143promptAction.showActionMenu({
6144  title: 'showActionMenu Title Info',
6145  buttons: [
6146    {
6147      text: 'item1',
6148      color: '#666666'
6149    },
6150    {
6151      text: 'item2',
6152      color: '#000000'
6153    },
6154  ]
6155})
6156  .then(data => {
6157    console.info('showActionMenu success, click button: ' + data.index);
6158  })
6159  .catch((err: Error) => {
6160    console.error('showActionMenu error: ' + err);
6161  })
6162```
6163
6164### openCustomDialog<sup>12+</sup>
6165
6166openCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>, options?: promptAction.BaseDialogOptions): Promise&lt;void&gt;
6167
6168Opens 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.
6169
6170**Atomic service API**: This API can be used in atomic services since API version 12.
6171
6172**System capability**: SystemCapability.ArkUI.ArkUI.Full
6173
6174**Parameters**
6175
6176| Name    | Type                                      | Mandatory  | Description     |
6177| ------- | ---------------------------------------- | ---- | ------- |
6178| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content of the custom dialog box.|
6179| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | No   |   Dialog box style.|
6180
6181**Return value**
6182
6183| Type                                      | Description     |
6184| ---------------------------------------- | ------- |
6185|   Promise&lt;void&gt;           |    Promise used to return the result.|
6186
6187**Error codes**
6188
6189For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6190
6191| ID | Error Message                              |
6192| ------ | ---------------------------------- |
6193| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6194| 103301 | The ComponentContent is incorrect. |
6195| 103302 | Dialog content already exists.|
6196
6197**Example**
6198
6199```ts
6200import { BusinessError } from '@kit.BasicServicesKit';
6201import { ComponentContent } from '@kit.ArkUI';
6202
6203class Params {
6204  text: string = ""
6205
6206  constructor(text: string) {
6207    this.text = text;
6208  }
6209}
6210
6211@Builder
6212function buildText(params: Params) {
6213  Column() {
6214    Text(params.text)
6215      .fontSize(50)
6216      .fontWeight(FontWeight.Bold)
6217      .margin({ bottom: 36 })
6218  }.backgroundColor('#FFF0F0F0')
6219}
6220
6221@Entry
6222@Component
6223struct Index {
6224  @State message: string = "hello"
6225
6226  build() {
6227    Row() {
6228      Column() {
6229        Button("click me")
6230          .onClick(() => {
6231            let uiContext = this.getUIContext();
6232            let promptAction = uiContext.getPromptAction();
6233            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
6234            promptAction.openCustomDialog(contentNode)
6235              .then(() => {
6236                console.info('succeeded')
6237              })
6238              .catch((error: BusinessError) => {
6239                console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`);
6240              })
6241          })
6242      }
6243      .width('100%')
6244      .height('100%')
6245    }
6246    .height('100%')
6247  }
6248}
6249```
6250
6251### openCustomDialogWithController<sup>18+</sup>
6252
6253openCustomDialogWithController\<T extends Object>(dialogContent: ComponentContent\<T>, controller: promptAction.DialogController, options?: promptAction.BaseDialogOptions): Promise&lt;void&gt;
6254
6255Opens 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.
6256
6257The 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**.
6258
6259Note that using **[isModal](js-apis-promptAction.md#basedialogoptions11) = true** and **[showInSubWindow](js-apis-promptAction.md#basedialogoptions11) = true** together is not supported.
6260
6261**Atomic service API**: This API can be used in atomic services since API version 18.
6262
6263**System capability**: SystemCapability.ArkUI.ArkUI.Full
6264
6265**Parameters**
6266
6267| Name    | Type                                      | Mandatory  | Description     |
6268| ------- | ---------------------------------------- | ---- | ------- |
6269| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content of the custom dialog box.|
6270| controller | [promptAction.DialogController](js-apis-promptAction.md#dialogcontroller18) | Yes| Controller of the custom dialog box.|
6271| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | No   | Style of the custom dialog box.|
6272
6273**Return value**
6274
6275| Type                                      | Description     |
6276| ---------------------------------------- | ------- |
6277|   Promise&lt;void&gt;           |    Promise used to return the result.|
6278
6279**Error codes**
6280
6281For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6282
6283| ID | Error Message                              |
6284| ------ | ---------------------------------- |
6285| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6286| 103301 | The ComponentContent is incorrect. |
6287| 103302 | Dialog content already exists.|
6288
6289**Example**
6290
6291```ts
6292import { BusinessError } from '@kit.BasicServicesKit';
6293import { ComponentContent, promptAction } from '@kit.ArkUI';
6294
6295class Params {
6296  text: string = ""
6297  dialogController: promptAction.DialogController = new promptAction.DialogController();
6298
6299  constructor(text: string, dialogController: promptAction.DialogController) {
6300    this.text = text;
6301    this.dialogController = dialogController;
6302  }
6303}
6304
6305@Builder
6306function buildText(params: Params) {
6307  Column() {
6308    Text(params.text)
6309      .fontSize(50)
6310      .fontWeight(FontWeight.Bold)
6311      .margin({ bottom: 36 })
6312    Button('Close by DialogController')
6313      .onClick(() => {
6314        if (params.dialogController != undefined) {
6315          params.dialogController.close()
6316        }
6317      })
6318  }.backgroundColor('#FFF0F0F0')
6319}
6320
6321@Entry
6322@ComponentV2
6323struct Index {
6324  @Local message: string = "hello"
6325  private dialogController: promptAction.DialogController = new promptAction.DialogController()
6326
6327  build() {
6328    Row() {
6329      Column() {
6330        Button("click me")
6331          .onClick(() => {
6332            let uiContext = this.getUIContext();
6333            let promptAction = uiContext.getPromptAction();
6334            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText),
6335              new Params(this.message, this.dialogController));
6336            promptAction.openCustomDialogWithController(contentNode, this.dialogController)
6337              .then(() => {
6338                console.info('succeeded')
6339              })
6340              .catch((error: BusinessError) => {
6341                console.error(`OpenCustomDialogWithController args error code is ${error.code}, message is ${error.message}`);
6342              })
6343          })
6344      }
6345      .width('100%')
6346      .height('100%')
6347    }
6348    .height('100%')
6349  }
6350}
6351```
6352
6353### closeCustomDialog<sup>12+</sup>
6354
6355closeCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>): Promise&lt;void&gt;
6356
6357Closes a custom dialog box corresponding to **dialogContent**. This API uses a promise to return the result.
6358
6359**Atomic service API**: This API can be used in atomic services since API version 12.
6360
6361**System capability**: SystemCapability.ArkUI.ArkUI.Full
6362
6363**Parameters**
6364
6365| Name    | Type                                      | Mandatory  | Description     |
6366| ------- | ---------------------------------------- | ---- | ------- |
6367| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content of the custom dialog box.|
6368
6369**Return value**
6370
6371| Type                                      | Description     |
6372| ---------------------------------------- | ------- |
6373|   Promise&lt;void&gt;           |    Promise used to return the result.|
6374
6375**Error codes**
6376
6377For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6378
6379| ID | Error Message                              |
6380| ------ | ---------------------------------- |
6381| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6382| 103301 | The ComponentContent is incorrect. |
6383| 103303 | The ComponentContent cannot be found. |
6384
6385**Example**
6386
6387```ts
6388import { BusinessError } from '@kit.BasicServicesKit';
6389import { ComponentContent } from '@kit.ArkUI';
6390
6391class Params {
6392  text: string = ""
6393
6394  constructor(text: string) {
6395    this.text = text;
6396  }
6397}
6398
6399@Builder
6400function buildText(params: Params) {
6401  Column() {
6402    Text(params.text)
6403      .fontSize(50)
6404      .fontWeight(FontWeight.Bold)
6405      .margin({ bottom: 36 })
6406  }.backgroundColor('#FFF0F0F0')
6407}
6408
6409@Entry
6410@Component
6411struct Index {
6412  @State message: string = "hello"
6413
6414  build() {
6415    Row() {
6416      Column() {
6417        Button("click me")
6418          .onClick(() => {
6419            let uiContext = this.getUIContext();
6420            let promptAction = uiContext.getPromptAction();
6421            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
6422            promptAction.openCustomDialog(contentNode)
6423              .then(() => {
6424                console.info('succeeded')
6425              })
6426              .catch((error: BusinessError) => {
6427                console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`);
6428              })
6429            setTimeout(() => {
6430              promptAction.closeCustomDialog(contentNode)
6431                .then(() => {
6432                  console.info('succeeded')
6433                })
6434                .catch((error: BusinessError) => {
6435                  console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`);
6436                })
6437            }, 2000); // Automatically close the dialog box after 2 seconds.
6438          })
6439      }
6440      .width('100%')
6441      .height('100%')
6442    }
6443    .height('100%')
6444  }
6445}
6446```
6447
6448### updateCustomDialog<sup>12+</sup>
6449
6450updateCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>, options: promptAction.BaseDialogOptions): Promise&lt;void&gt;
6451
6452Updates a custom dialog box corresponding to **dialogContent**. This API uses a promise to return the result.
6453
6454**Atomic service API**: This API can be used in atomic services since API version 12.
6455
6456**System capability**: SystemCapability.ArkUI.ArkUI.Full
6457
6458**Parameters**
6459
6460| Name    | Type                                      | Mandatory  | Description     |
6461| ------- | ---------------------------------------- | ---- | ------- |
6462| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content of the custom dialog box.|
6463| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | Yes   |   Dialog box style. Currently, only **alignment**, **offset**, **autoCancel**, and **maskColor** can be updated.|
6464
6465**Return value**
6466
6467| Type                                      | Description     |
6468| ---------------------------------------- | ------- |
6469|   Promise&lt;void&gt;           |    Promise used to return the result.|
6470
6471**Error codes**
6472
6473For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6474
6475| ID | Error Message                              |
6476| ------ | ---------------------------------- |
6477| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6478| 103301 | The ComponentContent is incorrect. |
6479| 103303 | The ComponentContent cannot be found. |
6480
6481**Example**
6482
6483```ts
6484import { BusinessError } from '@kit.BasicServicesKit';
6485import { ComponentContent } from '@kit.ArkUI';
6486
6487class Params {
6488  text: string = ""
6489
6490  constructor(text: string) {
6491    this.text = text;
6492  }
6493}
6494
6495@Builder
6496function buildText(params: Params) {
6497  Column() {
6498    Text(params.text)
6499      .fontSize(50)
6500      .fontWeight(FontWeight.Bold)
6501      .margin({ bottom: 36 })
6502  }.backgroundColor('#FFF0F0F0')
6503}
6504
6505@Entry
6506@Component
6507struct Index {
6508  @State message: string = "hello"
6509
6510  build() {
6511    Row() {
6512      Column() {
6513        Button("click me")
6514          .onClick(() => {
6515            let uiContext = this.getUIContext();
6516            let promptAction = uiContext.getPromptAction();
6517            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message))
6518            promptAction.openCustomDialog(contentNode)
6519              .then(() => {
6520                console.info('succeeded')
6521              })
6522              .catch((error: BusinessError) => {
6523                console.error(`updateCustomDialog args error code is ${error.code}, message is ${error.message}`)
6524              })
6525
6526            setTimeout(() => {
6527              promptAction.updateCustomDialog(contentNode, { alignment: DialogAlignment.CenterEnd })
6528                .then(() => {
6529                  console.info('succeeded')
6530                })
6531                .catch((error: BusinessError) => {
6532                  console.error(`updateCustomDialog args error code is ${error.code}, message is ${error.message}`)
6533                })
6534            }, 2000); // Automatically update the dialog box position after 2 seconds.
6535          })
6536      }
6537      .width('100%')
6538      .height('100%')
6539    }
6540    .height('100%')
6541  }
6542}
6543```
6544
6545### openCustomDialog<sup>12+</sup>
6546
6547openCustomDialog(options: promptAction.CustomDialogOptions): Promise\<number>
6548
6549Creates 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.
6550
6551**Atomic service API**: This API can be used in atomic services since API version 12.
6552
6553**System capability**: SystemCapability.ArkUI.ArkUI.Full
6554
6555**Parameters**
6556
6557| Name | Type                                                        | Mandatory| Description              |
6558| ------- | ------------------------------------------------------------ | ---- | ------------------ |
6559| options | [promptAction.CustomDialogOptions](js-apis-promptAction.md#customdialogoptions11) | Yes  | Content of the custom dialog box.|
6560
6561**Return value**
6562
6563| Type               | Description                                   |
6564| ------------------- | --------------------------------------- |
6565| Promise&lt;void&gt; | ID of the custom dialog box, which can be used with **closeCustomDialog**.|
6566
6567**Error codes**
6568
6569For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6570
6571| ID| Error Message                                                    |
6572| -------- | ------------------------------------------------------------ |
6573| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
6574| 100001   | Internal error.                                              |
6575
6576### presentCustomDialog<sup>18+</sup>
6577
6578presentCustomDialog(builder: CustomBuilder \| CustomBuilderWithId, controller?: promptAction.DialogController, options?: promptAction.DialogOptions): Promise\<number>
6579
6580Creates and displays a custom dialog box. This API uses a promise to return the dialog box ID, which can be used with **closeCustomDialog**.
6581
6582The 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.
6583
6584**isModal = true** and **showInSubWindow = true** cannot be used at the same time.
6585
6586**Atomic service API**: This API can be used in atomic services since API version 18.
6587
6588**System capability**: SystemCapability.ArkUI.ArkUI.Full
6589
6590**Parameters**
6591
6592| Name | Type                                                        | Mandatory| Description              |
6593| ------- | ------------------------------------------------------------ | ---- | ------------------ |
6594| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [CustomBuilderWithId](#custombuilderwithid18) | Yes  | Content of the custom dialog box.|
6595| controller | [promptAction.DialogController](js-apis-promptAction.md#dialogcontroller18) | No| Controller of the custom dialog box.|
6596| options | [promptAction.DialogOptions](js-apis-promptAction.md#dialogoptions18) | No| Style of the custom dialog box.|
6597
6598**Return value**
6599
6600| Type               | Description                                   |
6601| ------------------- | --------------------------------------- |
6602| Promise&lt;number&gt; | Promise used to return the custom dialog box ID.|
6603
6604**Error codes**
6605
6606For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6607
6608| ID| Error Message                                                    |
6609| -------- | ------------------------------------------------------------ |
6610| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
6611| 100001   | Internal error.                                              |
6612
6613**Example**
6614
6615```ts
6616import { BusinessError } from '@kit.BasicServicesKit';
6617import { PromptAction, promptAction } from '@kit.ArkUI';
6618
6619@Entry
6620@ComponentV2
6621struct Index {
6622  @Local message: string = "hello"
6623  private ctx: UIContext = this.getUIContext()
6624  private promptAction: PromptAction = this.ctx.getPromptAction()
6625  private dialogController: promptAction.DialogController = new promptAction.DialogController()
6626
6627  private customDialogComponentId: number = 0
6628  @Builder customDialogComponent() {
6629    Column() {
6630      Text(this.message).fontSize(30)
6631      Row({ space: 10 }) {
6632        Button("Close by DialogId").onClick(() => {
6633          this.promptAction.closeCustomDialog(this.customDialogComponentId)
6634        })
6635        Button("Close by DialogController").onClick(() => {
6636          this.dialogController.close()
6637        })
6638      }
6639    }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
6640  }
6641
6642  @Builder customDialogComponentWithId(dialogId: number) {
6643    Column() {
6644      Text(this.message).fontSize(30)
6645      Row({ space: 10 }) {
6646        Button("Close by DialogId").onClick(() => {
6647          this.promptAction.closeCustomDialog(dialogId)
6648        })
6649        Button("Close by DialogController").onClick(() => {
6650          this.dialogController.close()
6651        })
6652      }
6653    }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
6654  }
6655
6656  build() {
6657    Row() {
6658      Column({ space: 10 }) {
6659        Button('presentCustomDialog')
6660          .fontSize(20)
6661          .onClick(() => {
6662            this.promptAction.presentCustomDialog(() => {
6663              this.customDialogComponent()
6664            }, this.dialogController)
6665              .then((dialogId: number) => {
6666                this.customDialogComponentId = dialogId
6667              })
6668              .catch((err: BusinessError) => {
6669                console.error("presentCustomDialog error: " + err.code + " " + err.message)
6670              })
6671          })
6672        Button('presentCustomDialog with id')
6673          .fontSize(20)
6674          .onClick(() => {
6675            this.promptAction.presentCustomDialog((dialogId: number) => {
6676              this.customDialogComponentWithId(dialogId)
6677            }, this.dialogController)
6678              .catch((err: BusinessError) => {
6679                console.error("presentCustomDialog with id error: " + err.code + " " + err.message)
6680              })
6681          })
6682      }
6683      .width('100%')
6684      .height('100%')
6685    }
6686    .height('100%')
6687  }
6688}
6689```
6690
6691### closeCustomDialog<sup>12+</sup>
6692
6693closeCustomDialog(dialogId: number): void
6694
6695Closes the specified custom dialog box.
6696
6697**Atomic service API**: This API can be used in atomic services since API version 12.
6698
6699**System capability**: SystemCapability.ArkUI.ArkUI.Full
6700
6701**Parameters**
6702
6703| Name  | Type  | Mandatory| Description                            |
6704| -------- | ------ | ---- | -------------------------------- |
6705| dialogId | number | Yes  | ID of the custom dialog box to close. It is returned from **openCustomDialog**.|
6706
6707**Error codes**
6708
6709For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6710
6711| ID| Error Message                                                    |
6712| -------- | ------------------------------------------------------------ |
6713| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
6714| 100001   | Internal error.                                              |
6715
6716**Example**
6717
6718```ts
6719import { PromptAction } from '@kit.ArkUI';
6720
6721@Entry
6722@Component
6723struct Index {
6724  promptAction: PromptAction = this.getUIContext().getPromptAction()
6725  private customDialogComponentId: number = 0
6726
6727  @Builder
6728  customDialogComponent() {
6729    Column() {
6730      Text('Dialog box').fontSize(30)
6731      Row({ space: 50 }) {
6732        Button("OK").onClick(() => {
6733          this.promptAction.closeCustomDialog(this.customDialogComponentId)
6734        })
6735        Button("Cancel").onClick(() => {
6736          this.promptAction.closeCustomDialog(this.customDialogComponentId)
6737        })
6738      }
6739    }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
6740  }
6741
6742  build() {
6743    Row() {
6744      Column() {
6745        Button("click me")
6746          .onClick(() => {
6747            this.promptAction.openCustomDialog({
6748              builder: () => {
6749                this.customDialogComponent()
6750              },
6751              onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
6752                console.info("reason" + JSON.stringify(dismissDialogAction.reason))
6753                console.log("dialog onWillDismiss")
6754                if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
6755                  dismissDialogAction.dismiss()
6756                }
6757                if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
6758                  dismissDialogAction.dismiss()
6759                }
6760              }
6761            }).then((dialogId: number) => {
6762              this.customDialogComponentId = dialogId
6763            })
6764          })
6765      }
6766      .width('100%')
6767      .height('100%')
6768    }
6769    .height('100%')
6770  }
6771}
6772```
6773
6774### getTopOrder<sup>18+</sup>
6775
6776getTopOrder(): LevelOrder
6777
6778Obtains the order of the topmost dialog box.
6779
6780This 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.
6781
6782**Atomic service API**: This API can be used in atomic services since API version 18.
6783
6784**System capability**: SystemCapability.ArkUI.ArkUI.Full
6785
6786**Return value**
6787
6788| Type               | Description                                   |
6789| ------------------- | --------------------------------------- |
6790| [LevelOrder](js-apis-promptAction.md#levelorder18) | Order of the topmost dialog box.|
6791
6792**Example**
6793
6794This example shows how to use **getTopOrder** to obtain the order of the dialog box currently at the top layer.
6795
6796```ts
6797import { ComponentContent, PromptAction, LevelOrder, promptAction, UIContext } from '@kit.ArkUI';
6798import { BusinessError } from '@kit.BasicServicesKit';
6799
6800class Params {
6801  text: string = ""
6802  constructor(text: string) {
6803    this.text = text;
6804  }
6805}
6806
6807@Builder
6808function buildText(params: Params) {
6809  Column({ space: 20 }) {
6810    Text(params.text)
6811      .fontSize(50)
6812      .fontWeight(FontWeight.Bold)
6813      .margin({ bottom: 36 })
6814  }.backgroundColor('#FFF0F0F0')
6815}
6816
6817@Entry
6818@Component
6819struct Index {
6820  @State message: string = 'Dialog box'
6821  private ctx: UIContext = this.getUIContext()
6822  private promptAction: PromptAction = this.ctx.getPromptAction()
6823  private contentNode: ComponentContent<Object> =
6824    new ComponentContent(this.ctx, wrapBuilder(buildText), new Params(this.message))
6825
6826  private baseDialogOptions: promptAction.BaseDialogOptions = {
6827    showInSubWindow: false,
6828    levelOrder: LevelOrder.clamp(30.1),
6829  }
6830
6831  build() {
6832    Row() {
6833      Column({ space: 10 }) {
6834        Button('Open Dialog Box')
6835          .fontSize(20)
6836          .onClick(() => {
6837            this.promptAction.openCustomDialog(this.contentNode, this.baseDialogOptions)
6838              .catch((err: BusinessError) => {
6839                console.error("openCustomDialog error: " + err.code + " " + err.message)
6840              })
6841              .then(() => {
6842                let topOrder: LevelOrder = this.promptAction.getTopOrder();
6843                if (topOrder !== undefined) {
6844                  console.error('topOrder: ' + topOrder.getOrder());
6845                }
6846              })
6847          })
6848      }.width('100%')
6849    }.height('100%')
6850  }
6851}
6852```
6853
6854### getBottomOrder<sup>18+</sup>
6855
6856getBottomOrder(): LevelOrder
6857
6858Obtains the order of the bottommost dialog box.
6859
6860This 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.
6861
6862**Atomic service API**: This API can be used in atomic services since API version 18.
6863
6864**System capability**: SystemCapability.ArkUI.ArkUI.Full
6865
6866**Return value**
6867
6868| Type               | Description                                   |
6869| ------------------- | --------------------------------------- |
6870| [LevelOrder](js-apis-promptAction.md#levelorder18) | Order of the topmost dialog box.|
6871
6872**Example**
6873
6874This example shows how to use **getBottomOrder** to obtain the order of the dialog box currently at the bottom layer.
6875
6876```ts
6877import { ComponentContent, PromptAction, LevelOrder, promptAction, UIContext } from '@kit.ArkUI';
6878import { BusinessError } from '@kit.BasicServicesKit';
6879
6880class Params {
6881  text: string = ""
6882  constructor(text: string) {
6883    this.text = text;
6884  }
6885}
6886
6887@Builder
6888function buildText(params: Params) {
6889  Column({ space: 20 }) {
6890    Text(params.text)
6891      .fontSize(50)
6892      .fontWeight(FontWeight.Bold)
6893      .margin({ bottom: 36 })
6894  }.backgroundColor('#FFF0F0F0')
6895}
6896
6897@Entry
6898@Component
6899struct Index {
6900  @State message: string = 'Dialog box'
6901  private ctx: UIContext = this.getUIContext()
6902  private promptAction: PromptAction = this.ctx.getPromptAction()
6903  private contentNode: ComponentContent<Object> =
6904    new ComponentContent(this.ctx, wrapBuilder(buildText), new Params(this.message))
6905
6906  private baseDialogOptions: promptAction.BaseDialogOptions = {
6907    showInSubWindow: false,
6908    levelOrder: LevelOrder.clamp(30.1),
6909  }
6910
6911  build() {
6912    Row() {
6913      Column({ space: 10 }) {
6914        Button('Open Dialog Box')
6915          .fontSize(20)
6916          .onClick(() => {
6917            this.promptAction.openCustomDialog(this.contentNode, this.baseDialogOptions)
6918              .catch((err: BusinessError) => {
6919                console.error("openCustomDialog error: " + err.code + " " + err.message)
6920              })
6921              .then(() => {
6922                let bottomOrder: LevelOrder = this.promptAction.getBottomOrder();
6923                if (bottomOrder !== undefined) {
6924                  console.error('bottomOrder: ' + bottomOrder.getOrder());
6925                }
6926              })
6927          })
6928      }.width('100%')
6929    }.height('100%')
6930  }
6931}
6932```
6933
6934### openPopup<sup>18+</sup>
6935
6936openPopup\<T extends Object>(content: ComponentContent\<T>, target: TargetInfo, options?: PopupCommonOptions): Promise&lt;void&gt;
6937
6938Opens a popup with the specified content. This API uses a promise to return the result.
6939
6940> **NOTE**
6941>
6942> 1. If an invalid **target** is provided, the popup will not be displayed.
6943>
6944> 2. You must maintain the provided **content**, on which [updatePopup](#updatepopup18) and [closePopup](#closepopup18) rely to identify the target popup.
6945>
6946> 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 }**.
6947
6948**Atomic service API**: This API can be used in atomic services since API version 18.
6949
6950**System capability**: SystemCapability.ArkUI.ArkUI.Full
6951
6952**Parameters**
6953
6954| Name    | Type                                      | Mandatory  | Description     |
6955| ------- | ---------------------------------------- | ---- | ------- |
6956| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed in the popup.|
6957| target | [TargetInfo](#targetinfo18) | Yes| Information about the target component to be bound to the popup.|
6958| options | [PopupCommonOptions](arkui-ts/ts-universal-attributes-popup.md#popupcommonoptions18) | No| Style of the popup.|
6959
6960**Return value**
6961
6962| Type                                      | Description     |
6963| ---------------------------------------- | ------- |
6964|   Promise&lt;void&gt;           |    Promise used to return the result.|
6965
6966**Error codes**
6967
6968For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
6969
6970| ID | Error Message                              |
6971| ------ | ---------------------------------- |
6972| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
6973| 103301 | The ComponentContent is incorrect. |
6974| 103302 | The ComponentContent already exists. |
6975| 103304 | The targetId does not exist. |
6976| 103305 | The node of targetId is not in the component tree. |
6977
6978**Example**
6979
6980```ts
6981import { ComponentContent, FrameNode } from '@kit.ArkUI';
6982import { BusinessError } from '@kit.BasicServicesKit';
6983
6984interface PopupParam {
6985  updateFunc?: () => void
6986  closeFunc?: () => void
6987}
6988
6989export function showPopup(context: UIContext, uniqueId: number, contentNode: ComponentContent<PopupParam>,
6990  popupParam: PopupParam) {
6991  const promptAction = context.getPromptAction();
6992  let frameNode: FrameNode | null = context.getFrameNodeByUniqueId(uniqueId);
6993  let targetId = frameNode?.getFirstChild()?.getUniqueId();
6994  promptAction.openPopup(contentNode, { id: targetId }, {
6995    radius: 16,
6996    enableArrow: true
6997  })
6998    .then(() => {
6999      console.info('openPopup success');
7000    })
7001    .catch((err: BusinessError) => {
7002      console.info('openPopup error: ' + err.code + ' ' + err.message);
7003    })
7004  popupParam.updateFunc = () => {
7005    promptAction.updatePopup(contentNode, {
7006      enableArrow: false
7007    }, true)
7008      .then(() => {
7009        console.info('updatePopup success');
7010      })
7011      .catch((err: BusinessError) => {
7012        console.info('updatePopup error: ' + err.code + ' ' + err.message);
7013      })
7014  }
7015  popupParam.closeFunc = () => {
7016    promptAction.closePopup(contentNode)
7017      .then(() => {
7018        console.info('closePopup success');
7019      })
7020      .catch((err: BusinessError) => {
7021        console.info('closePopup error: ' + err.code + ' ' + err.message);
7022      })
7023  }
7024}
7025
7026@Builder
7027function buildText(param?: PopupParam) {
7028  Column() {
7029    Text('popup')
7030    Button('Update Popup')
7031      .fontSize(20)
7032      .onClick(() => {
7033        param?.updateFunc?.();
7034      })
7035    Button('Close Popup')
7036      .fontSize(20)
7037      .onClick(() => {
7038        param?.closeFunc?.();
7039      })
7040  }
7041}
7042
7043@Entry
7044@Component
7045struct Index {
7046  build() {
7047    Column() {
7048      Button('Open Popup')
7049        .fontSize(20)
7050        .onClick(() => {
7051          let context = this.getUIContext()
7052          const popupParam: PopupParam = {};
7053          const contentNode = new ComponentContent(context, wrapBuilder(buildText), popupParam);
7054          showPopup(context, this.getUniqueId(), contentNode, popupParam)
7055        })
7056    }
7057  }
7058}
7059```
7060
7061### updatePopup<sup>18+</sup>
7062
7063updatePopup\<T extends Object>(content: ComponentContent\<T>, options: PopupCommonOptions, partialUpdate?: boolean ): Promise&lt;void&gt;
7064
7065Updates the style of the popup corresponding to the provided **content**. This API uses a promise to return the result.
7066
7067> **NOTE**
7068>
7069> Updating the following properties is not supported: **showInSubWindow**, **focusable**, **onStateChange**, **onWillDismiss**, and **transition**.
7070>
7071
7072**Atomic service API**: This API can be used in atomic services since API version 18.
7073
7074**System capability**: SystemCapability.ArkUI.ArkUI.Full
7075
7076**Parameters**
7077
7078| Name    | Type                                      | Mandatory  | Description     |
7079| ------- | ---------------------------------------- | ---- | ------- |
7080| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed in the popup.|
7081| 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**.|
7082| 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.|
7083
7084**Return value**
7085
7086| Type                                      | Description     |
7087| ---------------------------------------- | ------- |
7088|   Promise&lt;void&gt;           |    Promise used to return the result.|
7089
7090**Error codes**
7091
7092For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
7093
7094| ID | Error Message                              |
7095| ------ | ---------------------------------- |
7096| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
7097| 103301 | The ComponentContent is incorrect. |
7098| 103303 | The ComponentContent cannot be found. |
7099
7100**Example**
7101
7102See the example for [openPopup](#openpopup18).
7103
7104### closePopup<sup>18+</sup>
7105
7106closePopup\<T extends Object>(content: ComponentContent\<T>): Promise&lt;void&gt;
7107
7108Closes the popup corresponding to the provided **content**. This API uses a promise to return the result.
7109
7110**Atomic service API**: This API can be used in atomic services since API version 18.
7111
7112**System capability**: SystemCapability.ArkUI.ArkUI.Full
7113
7114**Parameters**
7115
7116| Name    | Type                                      | Mandatory  | Description     |
7117| ------- | ---------------------------------------- | ---- | ------- |
7118| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed in the popup.|
7119
7120**Return value**
7121
7122| Type                                      | Description     |
7123| ---------------------------------------- | ------- |
7124|   Promise&lt;void&gt;           |    Promise used to return the result.|
7125
7126**Error codes**
7127
7128For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
7129
7130| ID | Error Message                              |
7131| ------ | ---------------------------------- |
7132| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
7133| 103301 | The ComponentContent is incorrect. |
7134| 103303 | The ComponentContent cannot be found. |
7135
7136**Example**
7137
7138See the example for [openPopup](#openpopup18).
7139
7140### openMenu<sup>18+</sup>
7141
7142openMenu\<T extends Object>(content: ComponentContent\<T>, target: TargetInfo, options?: MenuOptions): Promise&lt;void&gt;
7143
7144Opens a menu with the specified content. This API uses a promise to return the result.
7145
7146> **NOTE**
7147>
7148> 1. If an invalid **target** is provided, the menu will not be displayed.
7149>
7150> 2. You must maintain the provided **content**, on which [updateMenu](#updatemenu18) and [closeMenu](#closemenu18) rely to identify the target menu.
7151>
7152> 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 }**.
7153
7154**Atomic service API**: This API can be used in atomic services since API version 18.
7155
7156**System capability**: SystemCapability.ArkUI.ArkUI.Full
7157
7158**Parameters**
7159
7160| Name    | Type                                      | Mandatory  | Description     |
7161| ------- | ---------------------------------------- | ---- | ------- |
7162| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed in the menu.|
7163| target | [TargetInfo](#targetinfo18) | Yes| Information about the target component to be bound to the popup.|
7164| 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.|
7165
7166**Return value**
7167
7168| Type                                      | Description     |
7169| ---------------------------------------- | ------- |
7170|   Promise&lt;void&gt;           |    Promise used to return the result.|
7171
7172**Error codes**
7173
7174For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
7175
7176| ID | Error Message                              |
7177| ------ | ---------------------------------- |
7178| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
7179| 103301 | The ComponentContent is incorrect. |
7180| 103302 | The ComponentContent already exists. |
7181| 103304 | The targetId does not exist. |
7182| 103305 | The node of targetId is not in the component tree. |
7183
7184**Example**
7185
7186```ts
7187import { ComponentContent, FrameNode } from '@kit.ArkUI';
7188
7189export function doSomething(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) {
7190  showMenu(context, uniqueId, contentNode);
7191}
7192
7193@Builder
7194
7195function MyMenu() {
7196  Column() {
7197    Menu(){
7198      MenuItem({ startIcon: $r("app.media.startIcon"), content: "Menu item 1" })
7199      MenuItem({ startIcon: $r("app.media.startIcon"), content: "Menu item 2" })
7200    }
7201  }
7202  .width('80%')
7203  .padding('20lpx')
7204}
7205
7206export function showMenu(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) {
7207
7208  const promptAction = context.getPromptAction();
7209  let frameNode: FrameNode | null = context.getFrameNodeByUniqueId(uniqueId);
7210  let frameNodeTarget = frameNode?.getFirstChild();
7211  frameNodeTarget = frameNodeTarget?.getChild(0);
7212  let targetId = frameNodeTarget?.getUniqueId();
7213
7214  promptAction.openMenu(contentNode, {id: targetId},{
7215    enableArrow: true,
7216  });
7217}
7218
7219@Entry
7220@Component
7221struct Index {
7222  build() {
7223    Column(){
7224      Button('OpenMenu', { type: ButtonType.Normal, stateEffect: true })
7225        .borderRadius('16lpx')
7226        .width('80%')
7227        .margin(10)
7228        .onClick(() => {
7229          let context = this.getUIContext()
7230          const contentNode = new ComponentContent(context, wrapBuilder(MyMenu));
7231          doSomething(context, this.getUniqueId(), contentNode)
7232        })
7233    }
7234  }
7235}
7236```
7237
7238### updateMenu<sup>18+</sup>
7239
7240updateMenu\<T extends Object>(content: ComponentContent\<T>, options: MenuOptions, partialUpdate?: boolean ): Promise&lt;void&gt;
7241
7242Updates the style of the menu corresponding to the provided **content**. This API uses a promise to return the result.
7243
7244> **NOTE**
7245>
7246> Updating the following properties is not supported: **showInSubWindow**, **preview**, **previewAnimationOptions**, **transition**, **onAppear**, **aboutToAppear**, **onDisappear **and **aboutToDisappear**.
7247>
7248
7249**Atomic service API**: This API can be used in atomic services since API version 18.
7250
7251**System capability**: SystemCapability.ArkUI.ArkUI.Full
7252
7253**Parameters**
7254
7255| Name    | Type                                      | Mandatory  | Description     |
7256| ------- | ---------------------------------------- | ---- | ------- |
7257| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed in the menu.|
7258| 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**.|
7259| 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.|
7260
7261**Return value**
7262
7263| Type                                      | Description     |
7264| ---------------------------------------- | ------- |
7265|   Promise&lt;void&gt;           |    Promise used to return the result.|
7266
7267**Error codes**
7268
7269For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
7270
7271| ID | Error Message                              |
7272| ------ | ---------------------------------- |
7273| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
7274| 103301 | The ComponentContent is incorrect. |
7275| 103303 | The ComponentContent cannot be found. |
7276
7277**Example**
7278
7279```ts
7280import { ComponentContent, FrameNode } from '@kit.ArkUI';
7281
7282export function doSomething(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) {
7283  showMenu(context, uniqueId, contentNode);
7284}
7285
7286@Builder
7287
7288function MyMenu() {
7289  Column() {
7290    Menu(){
7291      MenuItem({ startIcon: $r("app.media.startIcon"), content: "Menu item 1" })
7292      MenuItem({ startIcon: $r("app.media.startIcon"), content: "Menu item 2" })
7293    }
7294  }
7295  .width('80%')
7296  .padding('20lpx')
7297}
7298
7299export function showMenu(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) {
7300
7301  const promptAction = context.getPromptAction();
7302  let frameNode: FrameNode | null = context.getFrameNodeByUniqueId(uniqueId);
7303  let frameNodeTarget = frameNode?.getFirstChild();
7304  frameNodeTarget = frameNodeTarget?.getChild(0);
7305  let targetId = frameNodeTarget?.getUniqueId();
7306
7307  promptAction.openMenu(contentNode, {id: targetId},{
7308    enableArrow: true,
7309  });
7310
7311  setTimeout(() => {
7312    promptAction.updateMenu(contentNode, {
7313      enableArrow: false,
7314    });
7315  }, 2000)
7316}
7317
7318@Entry
7319@Component
7320struct Index {
7321  build() {
7322    Column(){
7323      Button('OpenMenu', { type: ButtonType.Normal, stateEffect: true })
7324        .borderRadius('16lpx')
7325        .width('80%')
7326        .margin(10)
7327        .onClick(() => {
7328          let context = this.getUIContext()
7329          const contentNode = new ComponentContent(context, wrapBuilder(MyMenu));
7330          doSomething(context, this.getUniqueId(), contentNode)
7331        })
7332    }
7333  }
7334}
7335```
7336
7337### closeMenu<sup>18+</sup>
7338
7339closeMenu\<T extends Object>(content: ComponentContent\<T>): Promise&lt;void&gt;
7340
7341Closes the menu corresponding to the provided content. This API uses a promise to return the result.
7342
7343**Atomic service API**: This API can be used in atomic services since API version 18.
7344
7345**System capability**: SystemCapability.ArkUI.ArkUI.Full
7346
7347**Parameters**
7348
7349| Name    | Type                                      | Mandatory  | Description     |
7350| ------- | ---------------------------------------- | ---- | ------- |
7351| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed in the menu.|
7352
7353**Return value**
7354
7355| Type                                      | Description     |
7356| ---------------------------------------- | ------- |
7357|   Promise&lt;void&gt;           |    Promise used to return the result.|
7358
7359**Error codes**
7360
7361For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md).
7362
7363| ID | Error Message                              |
7364| ------ | ---------------------------------- |
7365| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
7366| 103301 | The ComponentContent is incorrect. |
7367| 103303 | The ComponentContent cannot be found. |
7368
7369**Example**
7370
7371```ts
7372import { ComponentContent, FrameNode } from '@kit.ArkUI';
7373
7374export function doSomething(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) {
7375  showMenu(context, uniqueId, contentNode);
7376}
7377
7378@Builder
7379
7380function MyMenu() {
7381  Column() {
7382    Menu(){
7383      MenuItem({ startIcon: $r("app.media.startIcon"), content: "Menu item 1" })
7384      MenuItem({ startIcon: $r("app.media.startIcon"), content: "Menu item 2" })
7385    }
7386  }
7387  .width('80%')
7388  .padding('20lpx')
7389}
7390
7391export function showMenu(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) {
7392
7393  const promptAction = context.getPromptAction();
7394  let frameNode: FrameNode | null = context.getFrameNodeByUniqueId(uniqueId);
7395  let frameNodeTarget = frameNode?.getFirstChild();
7396  frameNodeTarget = frameNodeTarget?.getChild(0);
7397  let targetId = frameNodeTarget?.getUniqueId();
7398
7399  promptAction.openMenu(contentNode, {id: targetId},{
7400    enableArrow: true,
7401  });
7402
7403  setTimeout(() => {
7404    promptAction.closeMenu(contentNode);
7405  }, 2000)
7406}
7407
7408@Entry
7409@Component
7410struct Index {
7411  build() {
7412    Column(){
7413      Button('OpenMenu', { type: ButtonType.Normal, stateEffect: true })
7414        .borderRadius('16lpx')
7415        .width('80%')
7416        .margin(10)
7417        .onClick(() => {
7418          let context = this.getUIContext()
7419          const contentNode = new ComponentContent(context, wrapBuilder(MyMenu));
7420          doSomething(context, this.getUniqueId(), contentNode)
7421        })
7422    }
7423  }
7424}
7425```
7426
7427## DragController<sup>11+</sup>
7428In 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.
7429
7430### executeDrag<sup>11+</sup>
7431
7432executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo, callback: AsyncCallback&lt;dragController.DragEventParam&gt;): void
7433
7434Executes dragging, by passing in the object to be dragged and the dragging information. This API uses a callback to return the drag event result.
7435
7436**Atomic service API**: This API can be used in atomic services since API version 12.
7437
7438**System capability**: SystemCapability.ArkUI.ArkUI.Full
7439
7440**Parameters**
7441
7442| Name  | Type                                                        | Mandatory| Description                                                        |
7443| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
7444| 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.|
7445| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | Yes  | Dragging information.                                                  |
7446| 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.|
7447
7448**Error codes**
7449For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
7450
7451| ID| Error Message     |
7452| -------- | ------------- |
7453| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
7454| 100001   | Internal handling failed. |
7455
7456**Example**
7457
7458```ts
7459import { dragController } from "@kit.ArkUI"
7460import { unifiedDataChannel } from '@kit.ArkData';
7461
7462@Entry
7463@Component
7464struct DragControllerPage {
7465  @Builder DraggingBuilder() {
7466    Column() {
7467      Text("DraggingBuilder")
7468    }
7469    .width(100)
7470    .height(100)
7471    .backgroundColor(Color.Blue)
7472  }
7473
7474  build() {
7475    Column() {
7476      Button('touch to execute drag')
7477        .onTouch((event?:TouchEvent) => {
7478          if(event){
7479            if (event.type == TouchType.Down) {
7480              let text = new unifiedDataChannel.Text()
7481              let unifiedData = new unifiedDataChannel.UnifiedData(text)
7482
7483              let dragInfo: dragController.DragInfo = {
7484                pointerId: 0,
7485                data: unifiedData,
7486                extraParams: ''
7487              }
7488              class tmp{
7489                event:DragEvent|undefined = undefined
7490                extraParams:string = ''
7491              }
7492              let eve:tmp = new tmp()
7493              dragController.executeDrag(()=>{this.DraggingBuilder()}, dragInfo, (err, eve) => {
7494                if(eve.event){
7495                  if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) {
7496                  // ...
7497                  } else if (eve.event.getResult() == DragResult.DRAG_FAILED) {
7498                  // ...
7499                  }
7500                }
7501              })
7502            }
7503          }
7504        })
7505    }
7506  }
7507}
7508```
7509
7510### executeDrag<sup>11+</sup>
7511
7512executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo): Promise&lt;dragController.DragEventParam&gt;
7513
7514Executes dragging, by passing in the object to be dragged and the dragging information. This API uses a promise to return the drag event result.
7515
7516**Atomic service API**: This API can be used in atomic services since API version 12.
7517
7518**System capability**: SystemCapability.ArkUI.ArkUI.Full
7519
7520**Parameters**
7521
7522| Name  | Type                                                        | Mandatory| Description                            |
7523| -------- | ------------------------------------------------------------ | ---- | -------------------------------- |
7524| custom   | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo) | Yes  | Object to be dragged.|
7525| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo)                                        | Yes  | Dragging information.                      |
7526
7527**Return value**
7528
7529| Type                                                        | Description                                                        |
7530| ------------------------------------------------------------ | ------------------------------------------------------------ |
7531| 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.|
7532
7533**Error codes**
7534For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
7535
7536| ID| Error Message     |
7537| -------- | ------------- |
7538| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
7539| 100001   | Internal handling failed. |
7540
7541**Example**
7542
7543```ts
7544import { dragController, componentSnapshot } from "@kit.ArkUI"
7545import { image } from '@kit.ImageKit';
7546import { unifiedDataChannel } from '@kit.ArkData';
7547
7548@Entry
7549@Component
7550struct DragControllerPage {
7551  @State pixmap: image.PixelMap|null = null
7552
7553  @Builder DraggingBuilder() {
7554    Column() {
7555      Text("DraggingBuilder")
7556    }
7557    .width(100)
7558    .height(100)
7559    .backgroundColor(Color.Blue)
7560  }
7561
7562  @Builder PixmapBuilder() {
7563    Column() {
7564      Text("PixmapBuilder")
7565    }
7566    .width(100)
7567    .height(100)
7568    .backgroundColor(Color.Blue)
7569  }
7570
7571  build() {
7572    Column() {
7573      Button('touch to execute drag')
7574        .onTouch((event?:TouchEvent) => {
7575          if(event){
7576            if (event.type == TouchType.Down) {
7577              let text = new unifiedDataChannel.Text()
7578              let unifiedData = new unifiedDataChannel.UnifiedData(text)
7579
7580              let dragInfo: dragController.DragInfo = {
7581                pointerId: 0,
7582                data: unifiedData,
7583                extraParams: ''
7584              }
7585              let pb:CustomBuilder = ():void=>{this.PixmapBuilder()}
7586              componentSnapshot.createFromBuilder(pb).then((pix: image.PixelMap) => {
7587                this.pixmap = pix;
7588                let dragItemInfo: DragItemInfo = {
7589                  pixelMap: this.pixmap,
7590                  builder: ()=>{this.DraggingBuilder()},
7591                  extraInfo: "DragItemInfoTest"
7592                }
7593
7594                class tmp{
7595                  event:DragResult|undefined = undefined
7596                  extraParams:string = ''
7597                }
7598                let eve:tmp = new tmp()
7599                dragController.executeDrag(dragItemInfo, dragInfo)
7600                  .then((eve) => {
7601                    if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) {
7602                      // ...
7603                    } else if (eve.event.getResult() == DragResult.DRAG_FAILED) {
7604                      // ...
7605                    }
7606                  })
7607                  .catch((err:Error) => {
7608                  })
7609              })
7610            }
7611          }
7612        })
7613    }
7614    .width('100%')
7615    .height('100%')
7616  }
7617}
7618```
7619
7620### createDragAction<sup>11+</sup>
7621
7622createDragAction(customArray: Array&lt;CustomBuilder \| DragItemInfo&gt;, dragInfo: dragController.DragInfo): dragController.DragAction
7623
7624Creates 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.
7625
7626**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.
7627
7628**Atomic service API**: This API can be used in atomic services since API version 12.
7629
7630**System capability**: SystemCapability.ArkUI.ArkUI.Full
7631
7632**Parameters**
7633
7634| Name  | Type                                                        | Mandatory| Description                            |
7635| --------      | ------------------------------------------------------------ | ---- | -------------------------------- |
7636| 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.|
7637| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo)                                | Yes  | Dragging information.                      |
7638
7639**Return value**
7640
7641| Type                                                  | Description              |
7642| ------------------------------------------------------ | ------------------ |
7643| [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.|
7644
7645**Error codes**
7646For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
7647
7648| ID| Error Message     |
7649| -------- | ------------- |
7650| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
7651| 100001   | Internal handling failed. |
7652
7653**Example**
76541. In the **EntryAbility.ets** file, obtain the UI context and save it to LocalStorage.
7655```ts
7656import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
7657import { hilog } from '@kit.PerformanceAnalysisKit';
7658import { window, UIContext } from '@kit.ArkUI';
7659
7660let uiContext: UIContext;
7661let localStorage: LocalStorage = new LocalStorage('uiContext');
7662
7663export default class EntryAbility extends UIAbility {
7664  storage: LocalStorage = localStorage;
7665  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
7666    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
7667  }
7668
7669  onDestroy(): void {
7670    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
7671  }
7672
7673  onWindowStageCreate(windowStage: window.WindowStage): void {
7674    // Main window is created, set main page for this ability
7675    let storage: LocalStorage = new LocalStorage();
7676    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
7677
7678    windowStage.loadContent('pages/Index', storage, (err, data) => {
7679      if (err.code) {
7680        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
7681        return;
7682      }
7683      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
7684      windowStage.getMainWindow((err, data) =>
7685      {
7686        if (err.code) {
7687          console.error('Failed to abtain the main window. Cause:' + err.message);
7688          return;
7689        }
7690        let windowClass: window.Window = data;
7691        uiContext = windowClass.getUIContext();
7692        this.storage.setOrCreate<UIContext>('uiContext', uiContext);
7693        // Obtain a UIContext instance.
7694      })
7695    });
7696  }
7697
7698  onWindowStageDestroy(): void {
7699    // Main window is destroyed, release UI related resources
7700    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
7701  }
7702
7703  onForeground(): void {
7704    // Ability has brought to foreground
7705    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
7706  }
7707
7708  onBackground(): void {
7709    // Ability has back to background
7710    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
7711  }
7712}
7713```
77142. Call **LocalStorage.getShared()** to obtain the UI context and then use the **DragController** object obtained to perform subsequent operations.
7715```ts
7716import { dragController, componentSnapshot, UIContext, DragController } from "@kit.ArkUI"
7717import { image } from '@kit.ImageKit';
7718import { unifiedDataChannel } from '@kit.ArkData';
7719
7720let storages = LocalStorage.getShared();
7721
7722@Entry(storages)
7723@Component
7724struct DragControllerPage {
7725  @State pixmap: image.PixelMap|null = null
7726  private dragAction: dragController.DragAction|null = null;
7727  customBuilders:Array<CustomBuilder | DragItemInfo> = new Array<CustomBuilder | DragItemInfo>();
7728  @Builder DraggingBuilder() {
7729    Column() {
7730      Text("DraggingBuilder")
7731    }
7732    .width(100)
7733    .height(100)
7734    .backgroundColor(Color.Blue)
7735  }
7736
7737  build() {
7738    Column() {
7739
7740      Column() {
7741        Text("Test")
7742      }
7743      .width(100)
7744      .height(100)
7745      .backgroundColor(Color.Red)
7746
7747      Button('Drag Multiple Objects').onTouch((event?:TouchEvent) => {
7748        if(event){
7749          if (event.type == TouchType.Down) {
7750            console.info("muti drag Down by listener");
7751            this.customBuilders.push(()=>{this.DraggingBuilder()});
7752            this.customBuilders.push(()=>{this.DraggingBuilder()});
7753            this.customBuilders.push(()=>{this.DraggingBuilder()});
7754            let text = new unifiedDataChannel.Text()
7755            let unifiedData = new unifiedDataChannel.UnifiedData(text)
7756            let dragInfo: dragController.DragInfo = {
7757              pointerId: 0,
7758              data: unifiedData,
7759              extraParams: ''
7760            }
7761            try{
7762              let uiContext: UIContext = storages.get<UIContext>('uiContext') as UIContext;
7763              this.dragAction = uiContext.getDragController().createDragAction(this.customBuilders, dragInfo)
7764              if(!this.dragAction){
7765                console.info("listener dragAction is null");
7766                return
7767              }
7768              this.dragAction.on('statusChange', (dragAndDropInfo)=>{
7769                if (dragAndDropInfo.status == dragController.DragStatus.STARTED) {
7770                  console.info("drag has start");
7771                } else if (dragAndDropInfo.status == dragController.DragStatus.ENDED){
7772                  console.info("drag has end");
7773                  if (!this.dragAction) {
7774                    return
7775                  }
7776                  this.customBuilders.splice(0, this.customBuilders.length)
7777                  this.dragAction.off('statusChange')
7778                }
7779              })
7780              this.dragAction.startDrag().then(()=>{}).catch((err:Error)=>{
7781                console.error("start drag Error:" + err.message);
7782              })
7783            } catch(err) {
7784              console.error("create dragAction Error:" + err.message);
7785            }
7786          }
7787        }
7788      }).margin({top:20})
7789    }
7790  }
7791}
7792```
7793
7794### getDragPreview<sup>11+</sup>
7795
7796getDragPreview(): dragController.DragPreview
7797
7798Obtains the **DragPreview** object, which represents the preview displayed during a drag.
7799
7800**Atomic service API**: This API can be used in atomic services since API version 12.
7801
7802**System capability**: SystemCapability.ArkUI.ArkUI.Full
7803
7804**Return value**
7805
7806| Type                                                        | Description                                                        |
7807| ------------------------------------------------------------ | ------------------------------------------------------------ |
7808| [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.|
7809
7810**Error codes**: For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md).
7811
7812**Example**
7813
7814For details, see [animate](js-apis-arkui-dragController.md#animate11).
7815
7816### setDragEventStrictReportingEnabled<sup>12+</sup>
7817
7818setDragEventStrictReportingEnabled(enable: boolean): void
7819
7820Sets whether the **onDragLeave** callback of the parent component is triggered when an item is dragged from the parent to the child component.
7821
7822**Atomic service API**: This API can be used in atomic services since API version 12.
7823
7824**System capability**: SystemCapability.ArkUI.ArkUI.Full
7825
7826**Parameters**
7827
7828| Name| Type   | Mandatory| Description                                                        |
7829| ------ | ------- | ---- | ------------------------------------------------------------ |
7830| 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.|
7831
7832**Example**
7833
7834```ts
7835import { UIAbility } from '@kit.AbilityKit';
7836import { window, UIContext } from '@kit.ArkUI';
7837
7838 export default class EntryAbility extends UIAbility {
7839   onWindowStageCreate(windowStage: window.WindowStage): void {
7840       windowStage.loadContent('pages/Index', (err, data) => {
7841         if (err.code) {
7842         return;
7843       }
7844       windowStage.getMainWindow((err, data) => {
7845         if (err.code) {
7846           return;
7847         }
7848         let windowClass: window.Window = data;
7849         let uiContext: UIContext = windowClass.getUIContext();
7850         uiContext.getDragController().setDragEventStrictReportingEnabled(true);
7851     });
7852   });
7853 }
7854}
7855```
7856
7857### cancelDataLoading<sup>15+</sup>
7858
7859cancelDataLoading(key: string): void
7860
7861Cancels the data loading initiated by the [startDataLoading](arkui-ts/ts-universal-events-drag-drop.md#dragevent7) API.
7862
7863**Atomic service API**: This API can be used in atomic services since API version 15.
7864
7865**System capability**: SystemCapability.ArkUI.ArkUI.Full
7866
7867**Parameters**
7868
7869| Name| Type   | Mandatory| Description                                                        |
7870| ------ | ------- | ---- | ------------------------------------------------------------ |
7871| 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.|
7872
7873**Error codes**
7874
7875For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Drag Event Error Codes](./errorcode-drag-event.md).
7876
7877| ID| Error Message                                                    |
7878| -------- | ------------------------------------------------------------ |
7879| 401      | Parameter error. |
7880| 190004      | Operation failed. |
7881
7882### notifyDragStartRequest<sup>18+</sup>
7883
7884notifyDragStartRequest(requestStatus: dragController.DragStartRequestStatus): void
7885
7886Controls whether the application can initiate a drag operation.
7887
7888**Atomic service API**: This API can be used in atomic services since API version 18.
7889
7890**System capability**: SystemCapability.ArkUI.ArkUI.Full
7891
7892**Parameters**
7893
7894| Name| Type  | Mandatory| Description                                                       |
7895| ------ | ------- | ---- | ------------------------------------------------------------ |
7896| requestStatus  | [dragController.DragStartRequestStatus](js-apis-arkui-dragController.md#dragstartrequeststatus18)    | Yes |Whether the application can initiate a drag operation.|
7897
7898**Example**
7899
7900```ts
7901import { unifiedDataChannel } from '@kit.ArkData';
7902import { image } from '@kit.ImageKit';
7903import { dragController } from "@kit.ArkUI";
7904
7905// xxx.ets
7906@Entry
7907@Component
7908struct NormalEts {
7909  @State finished: boolean = false
7910  @State timeout1: number = 1
7911  @State pixmap: image.PixelMap | undefined = undefined
7912  @State unifiedData1: unifiedDataChannel.UnifiedData | undefined = undefined
7913  @State previewData: DragItemInfo | undefined = undefined
7914
7915  loadData() {
7916    let timeout = setTimeout(() => {
7917      this.getUIContext().getComponentSnapshot().get("image1", (error: Error, pixmap: image.PixelMap) => {
7918        this.pixmap = pixmap
7919        this.previewData = {
7920          pixelMap: this.pixmap
7921        }
7922      })
7923
7924      let data: unifiedDataChannel.Image = new unifiedDataChannel.Image();
7925      data.imageUri = "app.media.startIcon";
7926      let unifiedData = new unifiedDataChannel.UnifiedData(data);
7927      this.unifiedData1 = unifiedData
7928
7929      this.getUIContext().getDragController().notifyDragStartRequest(dragController.DragStartRequestStatus.READY)
7930    }, 4000);
7931    this.timeout1 = timeout
7932  }
7933
7934
7935    build() {
7936      Column({space: 20}) {
7937        Image($r("app.media.startIcon"))
7938          .width(300)
7939          .height(200)
7940          .id("image1")
7941          .draggable(true)
7942          .dragPreview(this.previewData)
7943          .onPreDrag((status: PreDragStatus) => {
7944            if (status == PreDragStatus.PREPARING_FOR_DRAG_DETECTION) {
7945              this.loadData()
7946            } else {
7947              clearTimeout(this.timeout1);
7948            }
7949          })
7950          .onDragStart((event: DragEvent) => {
7951            if (this.finished == false) {
7952              this.getUIContext().getDragController().notifyDragStartRequest(dragController.DragStartRequestStatus.WAITING)
7953            } else {
7954              event.setData(this.unifiedData1);
7955            }
7956          })
7957          .onDragEnd(()=>{
7958            this.finished = false
7959          })
7960      }
7961      .height(400)
7962      .backgroundColor(Color.Pink)
7963    }
7964}
7965```
7966
7967## OverlayManager<sup>12+</sup>
7968
7969In 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.
7970> **NOTE**
7971>
7972> The nodes on **OverlayManager** are above the page level, but below such components as created through **Dialog**, **Popup**, **Menu**, **BindSheet**, **BindContentCover**, and **Toast**.
7973>
7974> 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.
7975>
7976> 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.
7977
7978### addComponentContent<sup>12+</sup>
7979
7980addComponentContent(content: ComponentContent, index?: number): void
7981
7982Adds a specified **ComponentContent** node to the **OverlayManager**.
7983
7984**Atomic service API**: This API can be used in atomic services since API version 12.
7985
7986**System capability**: SystemCapability.ArkUI.ArkUI.Full
7987
7988**Parameters**
7989
7990| Name    | Type                                      | Mandatory  | Description         |
7991| ------- | ---------------------------------------- | ---- | ----------- |
7992| 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.|
7993| 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>
7994
7995**Example**
7996
7997```ts
7998import { ComponentContent, OverlayManager, router } from '@kit.ArkUI';
7999
8000class Params {
8001  text: string = ""
8002  offset: Position
8003  constructor(text: string, offset: Position) {
8004    this.text = text
8005    this.offset = offset
8006  }
8007}
8008@Builder
8009function builderText(params: Params) {
8010  Column() {
8011    Text(params.text)
8012      .fontSize(30)
8013      .fontWeight(FontWeight.Bold)
8014  }.offset(params.offset)
8015}
8016
8017@Entry
8018@Component
8019struct OverlayExample {
8020  @State message: string = 'ComponentContent';
8021  private uiContext: UIContext = this.getUIContext()
8022  private overlayNode: OverlayManager = this.uiContext.getOverlayManager()
8023  @StorageLink('contentArray') contentArray: ComponentContent<Params>[] = []
8024  @StorageLink('componentContentIndex') componentContentIndex: number = 0
8025  @StorageLink('arrayIndex') arrayIndex: number = 0
8026  @StorageLink("componentOffset") componentOffset: Position = {x: 0, y: 80}
8027
8028  build() {
8029    Column() {
8030      Button("++componentContentIndex: " + this.componentContentIndex).onClick(()=>{
8031        ++this.componentContentIndex
8032      })
8033      Button("--componentContentIndex: " + this.componentContentIndex).onClick(()=>{
8034        --this.componentContentIndex
8035      })
8036      Button("Add ComponentContent" + this.contentArray.length).onClick(()=>{
8037        let componentContent = new ComponentContent(
8038          this.uiContext, wrapBuilder<[Params]>(builderText),
8039          new Params(this.message + (this.contentArray.length), this.componentOffset)
8040        )
8041        this.contentArray.push(componentContent)
8042        this.overlayNode.addComponentContent(componentContent, this.componentContentIndex)
8043      })
8044      Button("++arrayIndex: " + this.arrayIndex).onClick(()=>{
8045        ++this.arrayIndex
8046      })
8047      Button("--arrayIndex: " + this.arrayIndex).onClick(()=>{
8048        --this.arrayIndex
8049      })
8050      Button("Delete ComponentContent" + this.arrayIndex).onClick(()=>{
8051        if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) {
8052          let componentContent = this.contentArray.splice(this.arrayIndex, 1)
8053          this.overlayNode.removeComponentContent(componentContent.pop())
8054        } else {
8055          console.info("Invalid arrayIndex.")
8056        }
8057      })
8058      Button("Show ComponentContent" + this.arrayIndex).onClick(()=>{
8059        if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) {
8060          let componentContent = this.contentArray[this.arrayIndex]
8061          this.overlayNode.showComponentContent(componentContent)
8062        } else {
8063          console.info("Invalid arrayIndex.")
8064        }
8065      })
8066      Button("Hide ComponentContent" + this.arrayIndex).onClick(()=>{
8067        if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) {
8068          let componentContent = this.contentArray[this.arrayIndex]
8069          this.overlayNode.hideComponentContent(componentContent)
8070        } else {
8071          console.info("Invalid arrayIndex.")
8072        }
8073      })
8074      Button("Show All ComponentContent").onClick(()=>{
8075          this.overlayNode.showAllComponentContents()
8076      })
8077      Button("Hide All ComponentContent").onClick(()=>{
8078        this.overlayNode.hideAllComponentContents()
8079      })
8080
8081      Button("Go").onClick(()=>{
8082        router.pushUrl({
8083          url: 'pages/Second'
8084        })
8085      })
8086    }
8087    .width('100%')
8088    .height('100%')
8089  }
8090}
8091```
8092
8093### addComponentContentWithOrder<sup>18+</sup>
8094
8095addComponentContentWithOrder(content: ComponentContent, levelOrder?: LevelOrder): void
8096
8097Creates a floating layer node with the specified display order.
8098
8099This API allows you to define the stacking order of the nodes when they are created.
8100
8101**Atomic service API**: This API can be used in atomic services since API version 18.
8102
8103**System capability**: SystemCapability.ArkUI.ArkUI.Full
8104
8105**Parameters**
8106
8107| Name    | Type                                      | Mandatory  | Description         |
8108| ------- | ---------------------------------------- | ---- | ----------- |
8109| 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.|
8110| levelOrder | [LevelOrder](js-apis-promptAction.md#levelorder18) | No   | Display order of the new floating layer node.<br>**NOTE**<br>- Default value: **LevelOrder.clamp(0)**|
8111
8112**Example**
8113
8114This example demonstrates how to use **addComponentContentWithOrder** to create a floating layer node with the specified display order.
8115
8116```ts
8117import { ComponentContent, PromptAction, LevelOrder, UIContext, OverlayManager } from '@kit.ArkUI';
8118
8119class Params {
8120  text: string = ""
8121  offset: Position
8122  constructor(text: string, offset: Position) {
8123    this.text = text
8124    this.offset = offset
8125  }
8126}
8127@Builder
8128function builderText(params: Params) {
8129  Column() {
8130    Text(params.text)
8131      .fontSize(30)
8132      .fontWeight(FontWeight.Bold)
8133  }.offset(params.offset)
8134}
8135
8136@Entry
8137@Component
8138struct Index {
8139  @State message: string = 'Dialog box'
8140  private ctx: UIContext = this.getUIContext()
8141  private promptAction: PromptAction = this.ctx.getPromptAction()
8142  private overlayNode: OverlayManager = this.ctx.getOverlayManager()
8143  @StorageLink('contentArray') contentArray: ComponentContent<Params>[] = []
8144  @StorageLink('componentContentIndex') componentContentIndex: number = 0
8145  @StorageLink('arrayIndex') arrayIndex: number = 0
8146  @StorageLink("componentOffset") componentOffset: Position = {x: 0, y: 80}
8147
8148  build() {
8149    Row() {
8150      Column({ space: 10 }) {
8151        Button('OverlayManager Bottom Overlay')
8152          .fontSize(20)
8153          .onClick(() => {
8154            let componentContent = new ComponentContent(
8155              this.ctx, wrapBuilder<[Params]>(builderText),
8156              new Params(this.message + (this.contentArray.length), this.componentOffset)
8157            )
8158            this.contentArray.push(componentContent)
8159            this.overlayNode.addComponentContentWithOrder(componentContent, LevelOrder.clamp(100.1))
8160            let topOrder: LevelOrder = this.promptAction.getTopOrder();
8161            if (topOrder !== undefined) {
8162              console.error('topOrder: ' + topOrder.getOrder());
8163            }
8164            let bottomOrder: LevelOrder = this.promptAction.getBottomOrder();
8165            if (bottomOrder !== undefined) {
8166              console.error('bottomOrder: ' + bottomOrder.getOrder());
8167            }
8168          })
8169        Button('OverlayManager Top Overlay')
8170          .fontSize(20)
8171          .onClick(() => {
8172            let componentContent = new ComponentContent(
8173              this.ctx, wrapBuilder<[Params]>(builderText),
8174              new Params(this.message + (this.contentArray.length), this.componentOffset)
8175            )
8176            this.contentArray.push(componentContent)
8177            this.overlayNode.addComponentContentWithOrder(componentContent, LevelOrder.clamp(100.2))
8178            let topOrder: LevelOrder = this.promptAction.getTopOrder();
8179            if (topOrder !== undefined) {
8180              console.error('topOrder: ' + topOrder.getOrder());
8181            }
8182            let bottomOrder: LevelOrder = this.promptAction.getBottomOrder();
8183            if (bottomOrder !== undefined) {
8184              console.error('bottomOrder: ' + bottomOrder.getOrder());
8185            }
8186          })
8187      }.width('100%')
8188    }.height('100%')
8189  }
8190}
8191```
8192
8193### removeComponentContent<sup>12+</sup>
8194
8195removeComponentContent(content: ComponentContent): void
8196
8197Removes a specified **ComponentContent** node from the **OverlayManager**
8198
8199**Atomic service API**: This API can be used in atomic services since API version 12.
8200
8201**System capability**: SystemCapability.ArkUI.ArkUI.Full
8202
8203**Parameters**
8204
8205| Name    | Type                                      | Mandatory  | Description         |
8206| ------- | ---------------------------------------- | ---- | ----------- |
8207| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | Yes   | Content to remove from the **OverlayManager**.|
8208
8209**Example**
8210
8211See [addComponentContent Example](#addcomponentcontent12).
8212
8213### showComponentContent<sup>12+</sup>
8214
8215showComponentContent(content: ComponentContent): void
8216
8217Shows a specified **ComponentContent** node on the **OverlayManager**.
8218
8219**Atomic service API**: This API can be used in atomic services since API version 12.
8220
8221**System capability**: SystemCapability.ArkUI.ArkUI.Full
8222
8223**Parameters**
8224
8225| Name    | Type                                      | Mandatory  | Description         |
8226| ------- | ---------------------------------------- | ---- | ----------- |
8227| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | Yes   | Content to show on the **OverlayManager**.|
8228
8229**Example**
8230
8231See [addComponentContent Example](#addcomponentcontent12).
8232
8233### hideComponentContent<sup>12+</sup>
8234
8235hideComponentContent(content: ComponentContent): void
8236
8237Hides a specified **ComponentContent** node on the **OverlayManager**.
8238
8239**Atomic service API**: This API can be used in atomic services since API version 12.
8240
8241**System capability**: SystemCapability.ArkUI.ArkUI.Full
8242
8243**Parameters**
8244
8245| Name    | Type                                      | Mandatory  | Description         |
8246| ------- | ---------------------------------------- | ---- | ----------- |
8247| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | Yes   | Content to hide on the **OverlayManager**.|
8248
8249**Example**
8250
8251See [addComponentContent Example](#addcomponentcontent12).
8252
8253### showAllComponentContents<sup>12+</sup>
8254
8255showAllComponentContents(): void
8256
8257Shows all **ComponentContent** nodes on the **OverlayManager**.
8258
8259**Atomic service API**: This API can be used in atomic services since API version 12.
8260
8261**System capability**: SystemCapability.ArkUI.ArkUI.Full
8262
8263**Example**
8264
8265See [addComponentContent Example](#addcomponentcontent12).
8266
8267### hideAllComponentContents<sup>12+</sup>
8268
8269hideAllComponentContents(): void
8270
8271Hides all **ComponentContent** nodes on the **OverlayManager**.
8272
8273**Atomic service API**: This API can be used in atomic services since API version 12.
8274
8275**System capability**: SystemCapability.ArkUI.ArkUI.Full
8276
8277**Example**
8278
8279See [addComponentContent Example](#addcomponentcontent12).
8280
8281## OverlayManagerOptions<sup>15+</sup>
8282
8283Defines the options used to initialize the [OverlayManager](#overlaymanager12).
8284
8285**Atomic service API**: This API can be used in atomic services since API version 15.
8286
8287**System capability**: SystemCapability.ArkUI.ArkUI.Full
8288
8289| Name            | Type               | Mandatory    | Description                    |
8290| --------------- | ---------------------- | ------------ | --------------------- |
8291| 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**.|
8292
8293## AtomicServiceBar<sup>11+</sup>
8294
8295In 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.
8296> **NOTE**
8297>
8298> Since API version 12, the atomic service menu bar style is changed, and the following APIs are obsolete:
8299
8300### setVisible<sup>11+</sup>
8301
8302setVisible(visible: boolean): void
8303
8304Sets whether the atomic service menu bar is visible.
8305> **NOTE**
8306>
8307> 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.
8308
8309**Atomic service API**: This API can be used in atomic services since API version 11.
8310
8311**System capability**: SystemCapability.ArkUI.ArkUI.Full
8312
8313**Parameters**
8314
8315| Name| Type| Mandatory| Description|
8316| ------- | ------- | ------- | ------- |
8317| 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.|
8318
8319
8320**Example**
8321
8322```ts
8323import {UIContext, AtomicServiceBar, window } from '@kit.ArkUI';
8324import { hilog } from '@kit.PerformanceAnalysisKit';
8325
8326onWindowStageCreate(windowStage: window.WindowStage) {
8327  // Main window is created, set main page for this ability
8328  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
8329  windowStage.loadContent('pages/Index', (err, data) => {
8330    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
8331    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
8332    if (atomicServiceBar != undefined) {
8333      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
8334      atomicServiceBar.setVisible(false);
8335    } else {
8336      hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
8337    }
8338  });
8339}
8340```
8341
8342### setBackgroundColor<sup>11+</sup>
8343
8344setBackgroundColor(color:Nullable<Color | number | string>): void
8345
8346Sets the background color of the atomic service menu bar.
8347> **NOTE**
8348>
8349> The background of the atomic service menu bar is hidden by default since API version 12; its color cannot be set using this API.
8350
8351**Atomic service API**: This API can be used in atomic services since API version 12.
8352
8353**System capability**: SystemCapability.ArkUI.ArkUI.Full
8354
8355**Parameters**
8356
8357| Name| Type| Mandatory| Description|
8358| ------ | ------ | ------ | ------ |
8359| 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'**.|
8360
8361**Example**
8362
8363```ts
8364import {UIContext, AtomicServiceBar,window } from '@kit.ArkUI';
8365import { hilog } from '@kit.PerformanceAnalysisKit';
8366onWindowStageCreate(windowStage: window.WindowStage) {
8367  // Main window is created, set main page for this ability
8368  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
8369  windowStage.loadContent('pages/Index', (err, data) => {
8370    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
8371    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
8372    if (atomicServiceBar != undefined) {
8373      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
8374      atomicServiceBar.setBackgroundColor(0x88888888);
8375    } else {
8376      hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
8377    }
8378  });
8379}
8380```
8381
8382### setTitleContent<sup>11+</sup>
8383
8384setTitleContent(content:string): void
8385
8386Sets the title content of the atomic service menu bar.
8387> **NOTE**
8388>
8389> The title of the atomic service menu bar is hidden by default since API version 12; its content cannot be set using this API.
8390
8391**Atomic service API**: This API can be used in atomic services since API version 12.
8392
8393**System capability**: SystemCapability.ArkUI.ArkUI.Full
8394
8395**Parameters**
8396
8397|Name|Type|Mandatory|Description|
8398| ------- | ------- | ------- | ------- |
8399| content | string | Yes| Title content of the atomic service menu bar.|
8400
8401**Example**
8402
8403```ts
8404import {UIContext, AtomicServiceBar,window } from '@kit.ArkUI';
8405import { hilog } from '@kit.PerformanceAnalysisKit';
8406
8407onWindowStageCreate(windowStage: window.WindowStage) {
8408  // Main window is created, set main page for this ability
8409  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
8410  windowStage.loadContent('pages/Index', (err, data) => {
8411    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
8412    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
8413    if (atomicServiceBar != undefined) {
8414      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
8415      atomicServiceBar.setTitleContent('text2');
8416    } else {
8417      hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
8418    }
8419  });
8420}
8421```
8422
8423### setTitleFontStyle<sup>11+</sup>
8424
8425setTitleFontStyle(font:FontStyle):void
8426
8427Sets the font style of the atomic service menu bar.
8428> **NOTE**
8429>
8430> 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.
8431
8432**Atomic service API**: This API can be used in atomic services since API version 12.
8433
8434**System capability**: SystemCapability.ArkUI.ArkUI.Full
8435
8436**Parameters**
8437
8438| Name| Type| Mandatory| Description|
8439| ------ | ------ | ------ | ------ |
8440| font | [FontStyle](arkui-ts/ts-appendix-enums.md#fontstyle) | Yes| Font style of the atomic service menu bar.|
8441
8442**Example**
8443
8444```ts
8445import {UIContext, Font, AtomicServiceBar } from '@kit.ArkUI';
8446import { hilog } from '@kit.PerformanceAnalysisKit';
8447
8448onWindowStageCreate(windowStage: window.WindowStage) {
8449  // Main window is created, set main page for this ability
8450  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
8451  windowStage.loadContent('pages/Index', (err, data) => {
8452    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
8453    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
8454    if (atomicServiceBar != undefined) {
8455      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
8456      atomicServiceBar.setTitleFontStyle(FontStyle.Normal);
8457    } else {
8458      hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
8459    }
8460  });
8461}
8462```
8463
8464### setIconColor<sup>11+</sup>
8465
8466setIconColor(color:Nullable<Color | number | string>): void
8467
8468Sets the color of the atomic service icon.
8469> **NOTE**
8470>
8471> 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.
8472
8473**Atomic service API**: This API can be used in atomic services since API version 12.
8474
8475**System capability**: SystemCapability.ArkUI.ArkUI.Full
8476
8477**Parameters**
8478
8479| Name| Type| Mandatory| Description|
8480| ------- | ------- | ------- | ------- |
8481| 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'**.|
8482
8483
8484**Example**
8485
8486```ts
8487import {UIContext, Font, window } from '@kit.ArkUI';
8488import { hilog } from '@kit.PerformanceAnalysisKit';
8489
8490onWindowStageCreate(windowStage: window.WindowStage) {
8491  // Main window is created, set main page for this ability
8492  hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
8493  windowStage.loadContent('pages/Index', (err, data) => {
8494    let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
8495    let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
8496    if (atomicServiceBar != undefined) {
8497      hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
8498      atomicServiceBar.setIconColor(0x12345678);
8499    } else {
8500      hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
8501    }
8502  });
8503}
8504```
8505
8506### getBarRect<sup>15+</sup>
8507
8508getBarRect(): Frame
8509
8510Obtains the layout information of the atomic service menu bar relative to the window.
8511> **NOTE**
8512>
8513> The layout information includes the left and right margins of the atomic service menu bar.
8514
8515**Atomic service API**: This API can be used in atomic services since API version 15.
8516
8517**System capability**: SystemCapability.ArkUI.ArkUI.Full
8518
8519**Return value**
8520
8521| Type               | Description           |
8522| ----------------- | ------------- |
8523| [Frame](./js-apis-arkui-graphics.md#frame) | Size and position of the atomic service menu bar.|
8524
8525**Example**
8526
8527```ts
8528import { AtomicServiceBar } from '@kit.ArkUI';
8529import { hilog } from '@kit.PerformanceAnalysisKit';
8530@Entry
8531@Component
8532struct Index {
8533  build() {
8534    Button("getBarRect")
8535      .onClick(() => {
8536        let uiContext: UIContext = this.getUIContext();
8537        let currentBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar();
8538        if (currentBar != undefined) {
8539          let rect = currentBar.getBarRect();
8540          hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully. x:' +
8541            rect.x + ' y:' + rect.y + ' width:' + rect.width + ' height:' + rect.height);
8542        } else {
8543          hilog.info(0x0000, 'testTag', 'Get AtomServiceBar failed.');
8544        }
8545      })
8546  }
8547}
8548```
8549
8550## KeyboardAvoidMode<sup>11+</sup>
8551
8552Enumerates the modes in which the layout responds when the keyboard is displayed.
8553
8554**System capability**: SystemCapability.ArkUI.ArkUI.Full
8555
8556| Name  | Value  | Description      |
8557| ------ | ---- | ---------- |
8558| OFFSET | 0    | The layout moves up.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
8559| RESIZE | 1    | The layout is resized.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
8560| 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.|
8561| 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.|
8562| 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.|
8563
8564
8565## FocusController<sup>12+</sup>
8566In 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.
8567
8568### clearFocus<sup>12+</sup>
8569
8570clearFocus(): void
8571
8572Clears 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.
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**Example**
8579
8580```ts
8581@Entry
8582@Component
8583struct ClearFocusExample {
8584  @State inputValue: string = ''
8585  @State btColor: Color = Color.Blue
8586
8587  build() {
8588    Column({ space: 20 }) {
8589      Column({ space: 5 }) {
8590        Button('button1')
8591          .width(200)
8592          .height(70)
8593          .fontColor(Color.White)
8594          .focusOnTouch(true)
8595          .backgroundColor(Color.Blue)
8596        Button('button2')
8597          .width(200)
8598          .height(70)
8599          .fontColor(Color.White)
8600          .focusOnTouch(true)
8601          .backgroundColor(this.btColor)
8602          .defaultFocus(true)
8603          .onFocus(() => {
8604            this.btColor = Color.Red
8605          })
8606          .onBlur(() => {
8607            this.btColor = Color.Blue
8608          })
8609        Button('clearFocus')
8610          .width(200)
8611          .height(70)
8612          .fontColor(Color.White)
8613          .backgroundColor(Color.Blue)
8614          .onClick(() => {
8615            this.getUIContext().getFocusController().clearFocus()
8616          })
8617      }
8618    }
8619    .width('100%')
8620    .height('100%')
8621  }
8622}
8623```
8624
8625### requestFocus<sup>12+</sup>
8626
8627requestFocus(key: string): void
8628
8629Sets focus on the specified entity node in the component tree based on the component ID. This API takes effect in the current frame.
8630
8631**Atomic service API**: This API can be used in atomic services since API version 12.
8632
8633**System capability**: SystemCapability.ArkUI.ArkUI.Full
8634
8635**Parameters**
8636
8637| Name| Type| Mandatory| Description|
8638| ------- | ------- | ------- | ------- |
8639| key | string | Yes| [Component ID](arkui-ts/ts-universal-attributes-component-id.md) of the target node.|
8640
8641**Error codes**
8642
8643For details about the error codes, see [Focus Error Codes](errorcode-focus.md).
8644
8645| ID| Error Message                                       |
8646| -------- | ----------------------------------------------- |
8647| 150001   | the component cannot be focused.                |
8648| 150002   | This component has an unfocusable ancestor.     |
8649| 150003   | the component is not on tree or does not exist. |
8650
8651**Example**
8652
8653```ts
8654@Entry
8655@Component
8656struct RequestExample {
8657  @State btColor: Color = Color.Blue
8658
8659  build() {
8660    Column({ space: 20 }) {
8661      Column({ space: 5 }) {
8662        Button('Button')
8663          .width(200)
8664          .height(70)
8665          .fontColor(Color.White)
8666          .focusOnTouch(true)
8667          .backgroundColor(this.btColor)
8668          .onFocus(() => {
8669            this.btColor = Color.Red
8670          })
8671          .onBlur(() => {
8672            this.btColor = Color.Blue
8673          })
8674          .id("testButton")
8675
8676        Divider()
8677          .vertical(false)
8678          .width("80%")
8679          .backgroundColor(Color.Black)
8680          .height(10)
8681
8682        Button('requestFocus')
8683          .width(200)
8684          .height(70)
8685          .onClick(() => {
8686            this.getUIContext().getFocusController().requestFocus("testButton")
8687          })
8688
8689        Button('requestFocus fail')
8690          .width(200)
8691          .height(70)
8692          .onClick(() => {
8693            try {
8694              this.getUIContext().getFocusController().requestFocus("eee")
8695            } catch (error) {
8696              console.error('requestFocus failed code is ' + error.code + ' message is ' + error.message)
8697            }
8698          })
8699      }
8700    }
8701    .width('100%')
8702    .height('100%')
8703  }
8704}
8705```
8706
8707### activate<sup>14+</sup>
8708
8709activate(isActive: boolean, autoInactive?: boolean): void
8710
8711Sets the [focus activation state](../../ui/arkts-common-events-focus-event.md) of this page.
8712
8713**Atomic service API**: This API can be used in atomic services since API version 14.
8714
8715**System capability**: SystemCapability.ArkUI.ArkUI.Full
8716
8717**Parameters**
8718
8719| Name| Type| Mandatory| Description|
8720| ------- | ------- | ------- | ------- |
8721| 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.|
8722| 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**|
8723
8724```ts
8725// 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.
8726@Entry
8727@Component
8728struct ActivateExample {
8729  aboutToAppear() {
8730    this.getUIContext().getFocusController().activate(true, false)
8731  }
8732
8733  aboutToDisappear() {
8734    this.getUIContext().getFocusController().activate(false)
8735  }
8736
8737  build() {
8738    Row() {
8739      Button('Button1')
8740        .width(200)
8741        .height(70)
8742        .defaultFocus(true)
8743
8744      Button('Button2')
8745        .width(200)
8746        .height(70)
8747
8748      Button('Button3')
8749        .width(200)
8750        .height(70)
8751    }
8752    .padding(10)
8753    .justifyContent(FlexAlign.SpaceBetween)
8754    .width(800)
8755  }
8756}
8757```
8758
8759### setAutoFocusTransfer<sup>14+</sup>
8760
8761setAutoFocusTransfer(isAutoFocusTransfer: boolean): void;
8762
8763Sets whether the new page automatically obtains focus during page switching.
8764
8765**Atomic service API**: This API can be used in atomic services since API version 14.
8766
8767**System capability**: SystemCapability.ArkUI.ArkUI.Full
8768
8769**Parameters**
8770
8771| Name| Type| Mandatory| Description|
8772| ------- | ------- | ------- | ------- |
8773| 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**|
8774
8775```ts
8776@CustomDialog
8777struct CustomDialogExample {
8778  controller?: CustomDialogController
8779  build() {
8780    Column() {
8781      Text('This is a custom dialog box')
8782        .fontSize(30)
8783        .height(100)
8784      Text('The dialog box should not automatically acquire focus')
8785        .fontSize(20)
8786        .height(100)
8787      Button('Close Dialog Box')
8788        .onClick(() => {
8789          if (this.controller != undefined) {
8790            this.getUIContext().getFocusController().setAutoFocusTransfer(true)
8791            this.controller.close()
8792          }
8793        })
8794        .margin(20)
8795    }
8796  }
8797}
8798@Entry
8799@Component
8800struct CustomDialogUser {
8801  dialogController: CustomDialogController | null = new CustomDialogController({
8802    builder: CustomDialogExample({
8803    }),
8804  })
8805  aboutToDisappear() {
8806    this.dialogController = null
8807  }
8808
8809  build() {
8810    Column() {
8811      Button('click me')
8812        .onClick(() => {
8813          if (this.dialogController != null) {
8814            this.getUIContext().getFocusController().setAutoFocusTransfer(false)
8815            this.dialogController.open()
8816          }
8817        }).backgroundColor(0x317aff)
8818    }.width('100%').margin({ top: 5 })
8819  }
8820}
8821```
8822
8823### setKeyProcessingMode<sup>15+</sup>
8824
8825setKeyProcessingMode(mode: KeyProcessingMode): void
8826
8827Sets the mode for processing key events.
8828
8829**Atomic service API**: This API can be used in atomic services since API version 15.
8830
8831**System capability**: SystemCapability.ArkUI.ArkUI.Full
8832
8833**Parameters**
8834
8835| Name| Type| Mandatory| Description|
8836| ------- | ------- | ------- | ------- |
8837| mode | [KeyProcessingMode](./arkui-ts/ts-universal-attributes-focus.md#keyprocessingmode15)| Yes| Mode for processing key events.|
8838
8839```ts
8840
8841// This example demonstrates how to set the focus behavior after the page is loaded.
8842@Entry
8843@Component
8844struct Index {
8845
8846  aboutToAppear() {
8847    this.getUIContext().getFocusController().setKeyProcessingMode(KeyProcessingMode.ANCESTOR_EVENT)
8848  }
8849
8850  build() {
8851    Row() {
8852      Row() {
8853        Button('Button1').id('Button1').onKeyEvent((event) => {
8854          console.log("Button1");
8855          return true
8856        })
8857        Button('Button2').id('Button2').onKeyEvent((event) => {
8858          console.log("Button2");
8859          return true
8860        })
8861      }
8862      .width('100%')
8863      .height('100%')
8864      .id('Row1')
8865      .onKeyEventDispatch((event) => {
8866        let context = this.getUIContext();
8867        context.getFocusController().requestFocus('Button1');
8868        return context.dispatchKeyEvent('Button1', event);
8869      })
8870    }
8871    .height('100%')
8872    .width('100%')
8873    .onKeyEventDispatch((event) => {
8874      if (event.type == KeyType.Down) {
8875        let context = this.getUIContext();
8876        context.getFocusController().requestFocus('Row1');
8877        return context.dispatchKeyEvent('Row1', event);
8878      }
8879      return true;
8880    })
8881  }
8882}
8883```
8884
8885## PointerStyle<sup>12+</sup>
8886
8887type PointerStyle = pointer.PointerStyle
8888
8889Defines the pointer style.
8890
8891**Atomic service API**: This API can be used in atomic services since API version 12.
8892
8893**System capability**: SystemCapability.MultimodalInput.Input.Pointer
8894
8895|Type|Description|
8896| -- | -- |
8897|[pointer.PointerStyle](../apis-input-kit/js-apis-pointer.md#pointerstyle) |Pointer style.|
8898
8899## CursorController<sup>12+</sup>
8900In 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.
8901
8902### restoreDefault<sup>12+</sup>
8903
8904restoreDefault(): void
8905
8906Restores the default cursor style.
8907
8908**Atomic service API**: This API can be used in atomic services since API version 12.
8909
8910**System capability**: SystemCapability.ArkUI.ArkUI.Full
8911
8912**Example**
8913In this example, the **restoreDefault** API of **CursorController** is used to restore the cursor style when the cursor moves out of the green frame.
8914
8915```ts
8916import { pointer } from '@kit.InputKit';
8917import { UIContext, CursorController } from '@kit.ArkUI';
8918
8919@Entry
8920@Component
8921struct CursorControlExample {
8922  @State text: string = ''
8923  cursorCustom: CursorController = this.getUIContext().getCursorController();
8924
8925  build() {
8926    Column() {
8927      Row().height(200).width(200).backgroundColor(Color.Green).position({x: 150 ,y:70})
8928        .onHover((flag) => {
8929          if (flag) {
8930            this.cursorCustom.setCursor(pointer.PointerStyle.EAST)
8931          } else {
8932            console.info("restoreDefault");
8933            this.cursorCustom.restoreDefault();
8934          }
8935        })
8936    }.width('100%')
8937  }
8938}
8939```
8940![cursor-restoreDefault](figures/cursor-restoreDefault.gif)
8941
8942### setCursor<sup>12+</sup>
8943
8944setCursor(value: PointerStyle): void
8945
8946Sets the cursor style.
8947
8948**Atomic service API**: This API can be used in atomic services since API version 12.
8949
8950**System capability**: SystemCapability.ArkUI.ArkUI.Full
8951
8952**Parameters**
8953
8954| Name    | Type                                      | Mandatory  | Description     |
8955| ------- | ---------------------------------------- | ---- | ------- |
8956| value | [PointerStyle](#pointerstyle12) | Yes   | Cursor style.|
8957
8958**Example**
8959In 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.
8960
8961```ts
8962import { pointer } from '@kit.InputKit';
8963import { UIContext, CursorController } from '@kit.ArkUI';
8964
8965@Entry
8966@Component
8967struct CursorControlExample {
8968  @State text: string = ''
8969  cursorCustom: CursorController = this.getUIContext().getCursorController();
8970
8971  build() {
8972    Column() {
8973      Row().height(200).width(200).backgroundColor(Color.Blue).position({x: 100 ,y:70})
8974        .onHover((flag) => {
8975          if (flag) {
8976            this.cursorCustom.setCursor(pointer.PointerStyle.WEST)
8977          } else {
8978            this.cursorCustom.restoreDefault();
8979          }
8980        })
8981    }.width('100%')
8982  }
8983}
8984```
8985![cursor-setCursor](figures/cursor-setCursor.gif)
8986
8987## ContextMenuController<sup>12+</sup>
8988In 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.
8989
8990### close<sup>12+</sup>
8991
8992close(): void
8993
8994Closes this menu.
8995
8996**Atomic service API**: This API can be used in atomic services since API version 12.
8997
8998**System capability**: SystemCapability.ArkUI.ArkUI.Full
8999
9000**Example**
9001This example triggers the **close** API of **ContextMenuController** by a time to close the menu.
9002
9003```ts
9004import { ContextMenuController } from '@kit.ArkUI';
9005
9006@Entry
9007@Component
9008struct Index {
9009  menu: ContextMenuController = this.getUIContext().getContextMenuController();
9010
9011  @Builder MenuBuilder() {
9012    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
9013      Button('Test ContextMenu1 Close')
9014      Divider().strokeWidth(2).margin(5).color(Color.Black)
9015      Button('Test ContextMenu2')
9016      Divider().strokeWidth(2).margin(5).color(Color.Black)
9017      Button('Test ContextMenu3')
9018    }
9019    .width(200)
9020    .height(160)
9021  }
9022
9023  build() {
9024    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
9025      Button("Start Timer").onClick(()=>
9026      {
9027        setTimeout(() => {
9028          this.menu.close();
9029        }, 10000);
9030      })
9031
9032      Column() {
9033        Text("Test ContextMenu close")
9034          .fontSize(20)
9035          .width('100%')
9036          .height(500)
9037          .backgroundColor(0xAFEEEE)
9038          .textAlign(TextAlign.Center)
9039      }
9040      .bindContextMenu(this.MenuBuilder, ResponseType.LongPress)
9041    }
9042    .width('100%')
9043    .height('100%')
9044  }
9045}
9046```
9047
9048![contextMenuController_close](figures/contextMenuController_close.gif)
9049
9050## MeasureUtils<sup>12+</sup>
9051
9052In 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.
9053
9054### measureText<sup>12+</sup>
9055
9056measureText(options: MeasureOptions): number
9057
9058Measures the width of the given single-line text.
9059
9060**Atomic service API**: This API can be used in atomic services since API version 12.
9061
9062**System capability**: SystemCapability.ArkUI.ArkUI.Full
9063
9064**Parameters**
9065
9066| Name    | Type                             | Mandatory  | Description       |
9067| ------- | ------------------------------- | ---- | --------- |
9068| options | [MeasureOptions](js-apis-measure.md#measureoptions) | Yes   | Options of the target text.|
9069
9070**Return value**
9071
9072| Type         | Description      |
9073| ------------  | --------- |
9074| number        | Text width.<br>**NOTE**<br>Unit: px|
9075
9076
9077**Example**
9078This example uses the **measureText** API of **MeasureUtils** to obtain the width of the **"Hello World"** text.
9079
9080```ts
9081import { MeasureUtils } from '@kit.ArkUI';
9082
9083@Entry
9084@Component
9085struct Index {
9086  @State uiContext: UIContext = this.getUIContext();
9087  @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils();
9088  @State textWidth: number = this.uiContextMeasure.measureText({
9089    textContent: "Hello World",
9090    fontSize: '50px'
9091  })
9092
9093  build() {
9094    Row() {
9095      Column() {
9096        Text(`The width of 'Hello World': ${this.textWidth}`)
9097      }
9098      .width('100%')
9099    }
9100    .height('100%')
9101  }
9102}
9103```
9104
9105### measureTextSize<sup>12+</sup>
9106
9107measureTextSize(options: MeasureOptions): SizeOptions
9108
9109Measures the width and height of the given single-line text.
9110
9111**Atomic service API**: This API can be used in atomic services since API version 12.
9112
9113**System capability**: SystemCapability.ArkUI.ArkUI.Full
9114
9115**Parameters**
9116
9117| Name    | Type                             | Mandatory  | Description       |
9118| ------- | ------------------------------- | ---- | --------- |
9119| options | [MeasureOptions](js-apis-measure.md#measureoptions) | Yes   | Options of the target text.|
9120
9121**Return value**
9122
9123| Type         | Description      |
9124| ------------  | --------- |
9125| [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.|
9126
9127
9128**Example**
9129This example uses the **measureTextSize** API of **MeasureUtils** to obtain the width and height of the **"Hello World"** text.
9130
9131```ts
9132import { MeasureUtils } from '@kit.ArkUI';
9133
9134@Entry
9135@Component
9136struct Index {
9137  @State uiContext: UIContext = this.getUIContext();
9138  @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils();
9139  textSize : SizeOptions = this.uiContextMeasure.measureTextSize({
9140    textContent: "Hello World",
9141    fontSize: '50px'
9142  })
9143  build() {
9144    Row() {
9145      Column() {
9146        Text(`The width of 'Hello World': ${this.textSize.width}`)
9147        Text(`The height of 'Hello World': ${this.textSize.height}`)
9148      }
9149      .width('100%')
9150    }
9151    .height('100%')
9152  }
9153}
9154```
9155
9156## ComponentSnapshot<sup>12+</sup>
9157
9158In 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.
9159
9160### get<sup>12+</sup>
9161
9162get(id: string, callback: AsyncCallback<image.PixelMap>, options?: componentSnapshot.SnapshotOptions): void
9163
9164Obtains the snapshot of a component that has been loaded. This API uses an asynchronous callback to return the result.
9165
9166> **NOTE**
9167>
9168> 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.
9169
9170**Atomic service API**: This API can be used in atomic services since API version 12.
9171
9172**System capability**: SystemCapability.ArkUI.ArkUI.Full
9173
9174**Parameters**
9175
9176| Name  | Type                                                        | Mandatory| Description                                                        |
9177| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
9178| id       | string                                                       | Yes  | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.|
9179| 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.                                        |
9180| options<sup>12+</sup>       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | No   | Custom settings of the snapshot.|
9181
9182**Error codes**
9183
9184For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
9185
9186| ID| Error Message                                                    |
9187| -------- | ------------------------------------------------------------ |
9188| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
9189| 100001   | Invalid ID.                                                  |
9190
9191**Example**
9192
9193```ts
9194import { image } from '@kit.ImageKit';
9195import { UIContext } from '@kit.ArkUI';
9196
9197@Entry
9198@Component
9199struct SnapshotExample {
9200  @State pixmap: image.PixelMap | undefined = undefined
9201  uiContext: UIContext = this.getUIContext();
9202  build() {
9203    Column() {
9204      Row() {
9205        Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5)
9206        Image($r('app.media.img')).autoResize(true).width(150).height(150).margin(5).id("root")
9207      }
9208      Button("click to generate UI snapshot")
9209        .onClick(() => {
9210          this.uiContext.getComponentSnapshot().get("root", (error: Error, pixmap: image.PixelMap) => {
9211            if (error) {
9212              console.error("error: " + JSON.stringify(error))
9213              return;
9214            }
9215            this.pixmap = pixmap
9216          }, {scale : 2, waitUntilRenderFinished : true})
9217        }).margin(10)
9218    }
9219    .width('100%')
9220    .height('100%')
9221    .alignItems(HorizontalAlign.Center)
9222  }
9223}
9224```
9225
9226### get<sup>12+</sup>
9227
9228get(id: string, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
9229
9230Obtains the snapshot of a component that has been loaded. This API uses a promise to return the result.
9231
9232> **NOTE**
9233>
9234> 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.
9235
9236**Atomic service API**: This API can be used in atomic services since API version 12.
9237
9238**System capability**: SystemCapability.ArkUI.ArkUI.Full
9239
9240**Parameters**
9241
9242| Name| Type  | Mandatory| Description                                                        |
9243| ------ | ------ | ---- | ------------------------------------------------------------ |
9244| id     | string | Yes  | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.|
9245| options<sup>12+</sup>       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | No   | Custom settings of the snapshot.|
9246
9247**Return value**
9248
9249| Type                                                        | Description            |
9250| ------------------------------------------------------------ | ---------------- |
9251| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | Promise used to return the result.|
9252
9253**Error codes**
9254
9255For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
9256
9257| ID| Error Message                                                    |
9258| -------- | ------------------------------------------------------------ |
9259| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
9260| 100001   | Invalid ID.                                                  |
9261
9262**Example**
9263
9264```ts
9265import { image } from '@kit.ImageKit';
9266import { UIContext } from '@kit.ArkUI';
9267
9268@Entry
9269@Component
9270struct SnapshotExample {
9271  @State pixmap: image.PixelMap | undefined = undefined
9272  uiContext: UIContext = this.getUIContext();
9273
9274  build() {
9275    Column() {
9276      Row() {
9277        Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5)
9278        Image($r('app.media.icon')).autoResize(true).width(150).height(150).margin(5).id("root")
9279      }
9280      Button("click to generate UI snapshot")
9281        .onClick(() => {
9282          this.uiContext.getComponentSnapshot()
9283            .get("root", {scale : 2, waitUntilRenderFinished : true})
9284            .then((pixmap: image.PixelMap) => {
9285              this.pixmap = pixmap
9286            })
9287            .catch((err: Error) => {
9288              console.error("error: " + err)
9289            })
9290        }).margin(10)
9291    }
9292    .width('100%')
9293    .height('100%')
9294    .alignItems(HorizontalAlign.Center)
9295  }
9296}
9297```
9298
9299### createFromBuilder<sup>12+</sup>
9300
9301createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): void
9302
9303Renders 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.
9304> **NOTE**
9305>
9306> 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.
9307>
9308> 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.
9309
9310**Atomic service API**: This API can be used in atomic services since API version 12.
9311
9312**System capability**: SystemCapability.ArkUI.ArkUI.Full
9313
9314**Parameters**
9315
9316| Name  | Type                                                        | Mandatory| Description                                                        |
9317| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
9318| builder  | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8)         | Yes  | Builder for the custom component.<br>**NOTE**<br>The global builder is not supported.     |
9319| 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.|
9320| 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.|
9321| 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**|
9322| options<sup>12+</sup>       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | No   | Custom settings of the snapshot.|
9323
9324**Error codes**
9325
9326For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
9327
9328| ID| Error Message                                                    |
9329| -------- | ------------------------------------------------------------ |
9330| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
9331| 100001   | The builder is not a valid build function.                   |
9332| 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. |
9333
9334**Example**
9335
9336```ts
9337import { image } from '@kit.ImageKit';
9338import { UIContext } from '@kit.ArkUI';
9339
9340@Entry
9341@Component
9342struct ComponentSnapshotExample {
9343  @State pixmap: image.PixelMap | undefined = undefined
9344  uiContext: UIContext = this.getUIContext();
9345  @Builder
9346  RandomBuilder() {
9347    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
9348      Text('Test menu item 1')
9349        .fontSize(20)
9350        .width(100)
9351        .height(50)
9352        .textAlign(TextAlign.Center)
9353      Divider().height(10)
9354      Text('Test menu item 2')
9355        .fontSize(20)
9356        .width(100)
9357        .height(50)
9358        .textAlign(TextAlign.Center)
9359    }
9360    .width(100)
9361    .id("builder")
9362  }
9363
9364  build() {
9365    Column() {
9366      Button("click to generate UI snapshot")
9367        .onClick(() => {
9368          this.uiContext.getComponentSnapshot().createFromBuilder(() => {
9369            this.RandomBuilder()
9370          },
9371            (error: Error, pixmap: image.PixelMap) => {
9372              if (error) {
9373                console.error("error: " + JSON.stringify(error))
9374                return;
9375              }
9376              this.pixmap = pixmap
9377            }, 320, true, {scale : 2, waitUntilRenderFinished : true})
9378        })
9379      Image(this.pixmap)
9380        .margin(10)
9381        .height(200)
9382        .width(200)
9383        .border({ color: Color.Black, width: 2 })
9384    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
9385  }
9386}
9387```
9388
9389### createFromBuilder<sup>12+</sup>
9390
9391createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
9392
9393Renders 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.
9394
9395> **NOTE**
9396>
9397> 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.
9398>
9399> 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.
9400
9401**Atomic service API**: This API can be used in atomic services since API version 12.
9402
9403**System capability**: SystemCapability.ArkUI.ArkUI.Full
9404
9405**Parameters**
9406
9407| Name | Type                                                | Mandatory| Description                                                   |
9408| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- |
9409| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | Yes  | Builder for the custom component.<br>**NOTE**<br>The global builder is not supported.|
9410| 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|
9411| 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**|
9412| options<sup>12+</sup>       | [SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)           | No   | Custom settings of the snapshot.|
9413
9414**Return value**
9415
9416| Type                                                        | Description            |
9417| ------------------------------------------------------------ | ---------------- |
9418| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | Promise used to return the result.|
9419
9420**Error codes**
9421
9422For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
9423
9424| ID| Error Message                                                    |
9425| -------- | ------------------------------------------------------------ |
9426| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
9427| 100001   | The builder is not a valid build function.                   |
9428| 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. |
9429
9430**Example**
9431
9432```ts
9433import { image } from '@kit.ImageKit';
9434import { UIContext } from '@kit.ArkUI';
9435
9436@Entry
9437@Component
9438struct ComponentSnapshotExample {
9439  @State pixmap: image.PixelMap | undefined = undefined
9440  uiContext: UIContext = this.getUIContext();
9441  @Builder
9442  RandomBuilder() {
9443    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
9444      Text('Test menu item 1')
9445        .fontSize(20)
9446        .width(100)
9447        .height(50)
9448        .textAlign(TextAlign.Center)
9449      Divider().height(10)
9450      Text('Test menu item 2')
9451        .fontSize(20)
9452        .width(100)
9453        .height(50)
9454        .textAlign(TextAlign.Center)
9455    }
9456    .width(100)
9457    .id("builder")
9458  }
9459  build() {
9460    Column() {
9461      Button("click to generate UI snapshot")
9462        .onClick(() => {
9463          this.uiContext.getComponentSnapshot()
9464            .createFromBuilder(() => {
9465              this.RandomBuilder()
9466            }, 320, true, {scale : 2, waitUntilRenderFinished : true})
9467            .then((pixmap: image.PixelMap) => {
9468              this.pixmap = pixmap
9469            })
9470            .catch((err: Error) => {
9471              console.error("error: " + err)
9472            })
9473        })
9474      Image(this.pixmap)
9475        .margin(10)
9476        .height(200)
9477        .width(200)
9478        .border({ color: Color.Black, width: 2 })
9479    }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
9480  }
9481}
9482```
9483
9484### getSync<sup>12+</sup>
9485
9486getSync(id: string, options?: componentSnapshot.SnapshotOptions): image.PixelMap
9487
9488Obtains 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.
9489
9490> **NOTE**
9491>
9492> 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.
9493
9494**Atomic service API**: This API can be used in atomic services since API version 12.
9495
9496**System capability**: SystemCapability.ArkUI.ArkUI.Full
9497
9498**Parameters**
9499
9500| Name | Type    | Mandatory  | Description                                      |
9501| ---- | ------ | ---- | ---------------------------------------- |
9502| id   | string | Yes   | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.|
9503| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | No   | Custom settings of the snapshot.|
9504
9505**Return value**
9506
9507| Type                           | Description      |
9508| ----------------------------- | -------- |
9509| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Promise used to return the result.|
9510
9511**Error codes**
9512
9513For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
9514
9515| ID | Error Message               |
9516| ------ | ------------------- |
9517| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.   |
9518| 100001 | Invalid ID. |
9519| 160002 | Timeout. |
9520
9521**Example**
9522
9523```ts
9524import { image } from '@kit.ImageKit';
9525import { UIContext } from '@kit.ArkUI';
9526
9527@Entry
9528@Component
9529struct SnapshotExample {
9530  @State pixmap: image.PixelMap | undefined = undefined
9531
9532  build() {
9533    Column() {
9534      Row() {
9535        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
9536        Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root")
9537      }
9538      Button("click to generate UI snapshot")
9539        .onClick(() => {
9540          try {
9541            let pixelmap = this.getUIContext().getComponentSnapshot().getSync("root", {scale : 2, waitUntilRenderFinished : true})
9542            this.pixmap = pixelmap
9543          } catch (error) {
9544            console.error("getSync errorCode: " + error.code + " message: " + error.message)
9545          }
9546        }).margin(10)
9547    }
9548    .width('100%')
9549    .height('100%')
9550    .alignItems(HorizontalAlign.Center)
9551  }
9552}
9553```
9554
9555### getWithUniqueId<sup>15+</sup>
9556
9557getWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
9558
9559Obtains 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.
9560
9561> **NOTE**
9562>
9563> 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.
9564
9565**Atomic service API**: This API can be used in atomic services since API version 15.
9566
9567**System capability**: SystemCapability.ArkUI.ArkUI.Full
9568
9569**Parameters**
9570
9571| Name | Type    | Mandatory  | Description                                      |
9572| ---- | ------ | ---- | ---------------------------------------- |
9573| uniqueId   | number | Yes   | [Unique ID](js-apis-arkui-frameNode.md#getuniqueid12) of the target component.|
9574| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | No   | Custom settings of the snapshot.|
9575
9576**Return value**
9577
9578| Type                                                        | Description            |
9579| ------------------------------------------------------------ | ---------------- |
9580| Promise&lt;image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)&gt; | Promise used to return the result.|
9581
9582**Error codes**
9583
9584For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
9585
9586| ID| Error Message                                                    |
9587| -------- | ------------------------------------------------------------ |
9588| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
9589| 100001   | Invalid ID.                                                  |
9590
9591**Example**
9592
9593```ts
9594import { NodeController, FrameNode, typeNode } from '@kit.ArkUI';
9595import { image } from '@kit.ImageKit';
9596import { UIContext } from '@kit.ArkUI';
9597
9598class MyNodeController extends NodeController {
9599  public node: FrameNode | null = null;
9600
9601  public imageNode: FrameNode | null = null;
9602
9603  makeNode(uiContext: UIContext): FrameNode | null {
9604    this.node = new FrameNode(uiContext);
9605    this.node.commonAttribute.width('100%').height('100%')
9606
9607    let image = typeNode.createNode(uiContext, 'Image');
9608    image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true)
9609    this.imageNode = image;
9610
9611    this.node.appendChild(image);
9612    return this.node;
9613  }
9614}
9615
9616@Entry
9617@Component
9618struct SnapshotExample {
9619  private myNodeController: MyNodeController = new MyNodeController();
9620
9621  @State pixmap: image.PixelMap | undefined = undefined
9622
9623  build() {
9624    Column() {
9625      Row() {
9626        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
9627        NodeContainer(this.myNodeController).width(200).height(200).margin(5)
9628      }
9629      Button("UniqueId get snapshot")
9630        .onClick(() => {
9631          try {
9632            this.getUIContext()
9633              .getComponentSnapshot()
9634              .getWithUniqueId(this.myNodeController.imageNode?.getUniqueId(), {scale: 2, waitUntilRenderFinished: true})
9635              .then((pixmap: image.PixelMap) => {
9636                this.pixmap = pixmap
9637              })
9638              .catch((err: Error) => {
9639                console.log("error: " + err)
9640              })
9641          } catch (error) {
9642            console.error("UniqueId get snapshot Error: " + JSON.stringify(error))
9643          }
9644        }).margin(10)
9645    }
9646    .width('100%')
9647    .height('100%')
9648    .alignItems(HorizontalAlign.Center)
9649  }
9650}
9651```
9652
9653### getSyncWithUniqueId<sup>15+</sup>
9654
9655getSyncWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): image.PixelMap
9656
9657Obtains 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.
9658
9659> **NOTE**
9660>
9661> 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.
9662
9663**Atomic service API**: This API can be used in atomic services since API version 15.
9664
9665**System capability**: SystemCapability.ArkUI.ArkUI.Full
9666
9667**Parameters**
9668
9669| Name | Type    | Mandatory  | Description                                      |
9670| ---- | ------ | ---- | ---------------------------------------- |
9671| uniqueId   | number | Yes   | [Unique ID](js-apis-arkui-frameNode.md#getuniqueid12) of the target component.|
9672| options       | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12)            | No   | Custom settings of the snapshot.|
9673
9674**Return value**
9675
9676| Type                           | Description      |
9677| ----------------------------- | -------- |
9678| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Promise used to return the result.|
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 | Invalid ID. |
9688| 160002 | Timeout. |
9689
9690**Example**
9691
9692```ts
9693import { NodeController, FrameNode, typeNode } from '@kit.ArkUI';
9694import { image } from '@kit.ImageKit';
9695import { UIContext } from '@kit.ArkUI';
9696
9697class MyNodeController extends NodeController {
9698  public node: FrameNode | null = null;
9699
9700  public imageNode: FrameNode | null = null;
9701
9702  makeNode(uiContext: UIContext): FrameNode | null {
9703    this.node = new FrameNode(uiContext);
9704    this.node.commonAttribute.width('100%').height('100%')
9705
9706    let image = typeNode.createNode(uiContext, 'Image');
9707    image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true)
9708    this.imageNode = image;
9709
9710    this.node.appendChild(image);
9711    return this.node;
9712  }
9713}
9714
9715@Entry
9716@Component
9717struct SnapshotExample {
9718  private myNodeController: MyNodeController = new MyNodeController();
9719
9720  @State pixmap: image.PixelMap | undefined = undefined
9721
9722  build() {
9723    Column() {
9724      Row() {
9725        Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5)
9726        NodeContainer(this.myNodeController).width(200).height(200).margin(5)
9727      }
9728      Button("UniqueId getSync snapshot")
9729        .onClick(() => {
9730          try {
9731            this.pixmap = this.getUIContext()
9732              .getComponentSnapshot()
9733              .getSyncWithUniqueId(this.myNodeController.imageNode?.getUniqueId(), {scale: 2, waitUntilRenderFinished: true})
9734          } catch (error) {
9735            console.error("UniqueId getSync snapshot Error: " + JSON.stringify(error))
9736          }
9737        }).margin(10)
9738    }
9739    .width('100%')
9740    .height('100%')
9741    .alignItems(HorizontalAlign.Center)
9742  }
9743}
9744```
9745
9746### createFromComponent<sup>18+</sup>
9747
9748createFromComponent\<T extends Object>(content: ComponentContent\<T>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap>
9749
9750Takes a snapshot of the provided **content** object. This API uses a promise to return the result.
9751
9752**Atomic service API**: This API can be used in atomic services since API version 18.
9753
9754**System capability**: SystemCapability.ArkUI.ArkUI.Full
9755
9756**Parameters**
9757
9758| Name  | Type                                                        | Mandatory| Description                                                        |
9759| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
9760| content  | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md)         | Yes  | Component content to be captured. This is the content currently displayed in the **UIContext**.     |
9761| 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|
9762| 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**|
9763| 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.|
9764
9765**Error codes**
9766
9767For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Snapshot Error Codes](errorcode-snapshot.md).
9768
9769| ID| Error Message                                                    |
9770| -------- | ------------------------------------------------------------ |
9771| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
9772| 100001   | The builder is not a valid build function.                   |
9773| 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. |
9774
9775**Example**
9776
9777```ts
9778import { image } from '@kit.ImageKit';
9779import { ComponentContent } from '@kit.ArkUI';
9780
9781class Params {
9782  text: string | undefined | null  = "";
9783
9784  constructor(text: string | undefined | null ) {
9785    this.text = text;
9786  }
9787}
9788
9789@Builder
9790function buildText(params: Params) {
9791  ReusableChildComponent({ text: params.text });
9792}
9793
9794@Component
9795struct ReusableChildComponent {
9796  @Prop text: string | undefined | null  = "";
9797
9798  aboutToReuse(params: Record<string, object>) {
9799    console.log("ReusableChildComponent Reusable " + JSON.stringify(params));
9800  }
9801
9802  aboutToRecycle(): void {
9803    console.log("ReusableChildComponent aboutToRecycle " + this.text);
9804  }
9805
9806  build() {
9807    Column() {
9808      Text(this.text)
9809        .fontSize(90)
9810        .fontWeight(FontWeight.Bold)
9811        .margin({ bottom: 36 })
9812        .width('100%')
9813        .height('100%')
9814    }.backgroundColor('#FFF0F0F0')
9815  }
9816}
9817
9818@Entry
9819@Component
9820struct Index {
9821  @State pixmap: image.PixelMap | undefined = undefined
9822  @State message: string | undefined | null = "hello"
9823  uiContext: UIContext = this.getUIContext();
9824
9825  build() {
9826    Row() {
9827      Column() {
9828        Button("Create Component Snapshot")
9829          .onClick(() => {
9830            let uiContext = this.getUIContext();
9831            let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
9832            this.uiContext.getComponentSnapshot()
9833              .createFromComponent(contentNode
9834                , 320, true, {scale : 2, waitUntilRenderFinished : true})
9835              .then((pixmap: image.PixelMap) => {
9836                this.pixmap = pixmap
9837              })
9838              .catch((err: Error) => {
9839                console.error("error: " + err)
9840              })
9841          })
9842        Image(this.pixmap)
9843          .margin(10)
9844          .height(200)
9845          .width(200)
9846          .border({ color: Color.Black, width: 2 })
9847      }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300)
9848    }
9849    .width('100%')
9850    .height('100%')
9851  }
9852}
9853```
9854
9855## FrameCallback<sup>12+</sup>
9856
9857Implements 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.
9858
9859### onFrame<sup>12+</sup>
9860
9861onFrame(frameTimeInNano: number): void
9862
9863Called when the next frame is rendered.
9864
9865**Atomic service API**: This API can be used in atomic services since API version 12.
9866
9867**System capability**: SystemCapability.ArkUI.ArkUI.Full
9868
9869**Parameters**
9870
9871| Name | Type                                                | Mandatory| Description                                                   |
9872| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- |
9873| frameTimeInNano | number | Yes  | Time when the rendering of the next frame starts, in nanoseconds.<br>Value range: [0, +∞)|
9874
9875**Example**
9876
9877```ts
9878import {FrameCallback } from '@kit.ArkUI';
9879
9880class MyFrameCallback extends FrameCallback {
9881  private tag: string;
9882
9883  constructor(tag: string) {
9884    super()
9885    this.tag = tag;
9886  }
9887
9888  onFrame(frameTimeNanos: number) {
9889    console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString());
9890  }
9891}
9892
9893@Entry
9894@Component
9895struct Index {
9896  build() {
9897    Row() {
9898      Column() {
9899        Button('Invoke postFrameCallback')
9900          .onClick(() => {
9901            this.getUIContext().postFrameCallback(new MyFrameCallback("normTask"));
9902          })
9903        Button('Invoke postDelayedFrameCallback')
9904          .onClick(() => {
9905            this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5);
9906          })
9907      }
9908      .width('100%')
9909    }
9910    .height('100%')
9911  }
9912}
9913```
9914
9915### onIdle<sup>12+</sup>
9916
9917onIdle(timeLeftInNano: number): void
9918
9919Called 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.
9920
9921**Atomic service API**: This API can be used in atomic services since API version 12.
9922
9923**System capability**: SystemCapability.ArkUI.ArkUI.Full
9924
9925**Parameters**
9926
9927| Name | Type                                                | Mandatory| Description                                                   |
9928| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- |
9929| timeLeftInNano | number | Yes  | Remaining idle time for the current frame, in nanoseconds.<br>Value range: [0, +∞)|
9930
9931**Example**
9932
9933```ts
9934import { FrameCallback } from '@ohos.arkui.UIContext';
9935
9936class MyIdleCallback extends FrameCallback {
9937  private tag: string;
9938
9939  constructor(tag: string) {
9940    super()
9941    this.tag = tag;
9942  }
9943
9944  onIdle(timeLeftInNano: number) {
9945    console.info('MyIdleCallback ' + this.tag + ' ' + timeLeftInNano.toString());
9946  }
9947}
9948
9949@Entry
9950@Component
9951struct Index {
9952  build() {
9953    Row() {
9954      Column() {
9955        Button('Invoke postFrameCallback')
9956          .onClick(() => {
9957            this.getUIContext().postFrameCallback(new MyIdleCallback("normTask"));
9958          })
9959        Button('Invoke postDelayedFrameCallback')
9960          .onClick(() => {
9961            this.getUIContext().postDelayedFrameCallback(new MyIdleCallback("delayTask"), 5);
9962          })
9963      }
9964      .width('100%')
9965    }
9966    .height('100%')
9967  }
9968}
9969```
9970
9971## DynamicSyncScene<sup>12+</sup>
9972
9973In 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.
9974
9975### setFrameRateRange<sup>12+</sup>
9976
9977setFrameRateRange(range: ExpectedFrameRateRange): void
9978
9979Sets the expected frame rate range.
9980
9981While 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.
9982
9983**Atomic service API**: This API can be used in atomic services since API version 12.
9984
9985**System capability**: SystemCapability.ArkUI.ArkUI.Full
9986
9987**Parameters**
9988
9989| Name     | Type        | Mandatory  | Description  |
9990| -------- | ---------- | ---- | ---- |
9991| 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}**|
9992
9993**Example**
9994
9995```ts
9996import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI'
9997
9998@Entry
9999@Component
10000struct Frame {
10001  @State ANIMATION:ExpectedFrameRateRange = {min:0, max:120, expected: 90}
10002  @State GESTURE:ExpectedFrameRateRange = {min:0, max:120, expected: 30}
10003  private scenes: SwiperDynamicSyncScene[] = []
10004
10005  build() {
10006    Column() {
10007      Text("Animation"+ JSON.stringify(this.ANIMATION))
10008      Text("Responsive"+ JSON.stringify(this.GESTURE))
10009      Row(){
10010        Swiper() {
10011          Text("one")
10012          Text("two")
10013          Text("three")
10014        }
10015        .width('100%')
10016        .height('300vp')
10017        .id("dynamicSwiper")
10018        .backgroundColor(Color.Blue)
10019        .autoPlay(true)
10020        .onAppear(()=>{
10021          this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[]
10022        })
10023      }
10024
10025      Button("set frame")
10026        .onClick(()=>{
10027          this.scenes.forEach((scenes: SwiperDynamicSyncScene) => {
10028
10029            if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) {
10030              scenes.setFrameRateRange(this.ANIMATION)
10031            }
10032
10033            if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) {
10034              scenes.setFrameRateRange(this.GESTURE)
10035            }
10036          });
10037        })
10038    }
10039  }
10040}
10041```
10042
10043### getFrameRateRange<sup>12+</sup>
10044
10045getFrameRateRange(): ExpectedFrameRateRange
10046
10047Obtains the expected frame rate range.
10048
10049**Atomic service API**: This API can be used in atomic services since API version 12.
10050
10051**System capability**: SystemCapability.ArkUI.ArkUI.Full
10052
10053**Return value**
10054
10055| Type                 | Description     |
10056| ------------------- | ------- |
10057| [ExpectedFrameRateRange](../apis-arkui/arkui-ts/ts-explicit-animation.md#expectedframeraterange11) | Expected frame rate range.|
10058
10059**Example**
10060
10061```ts
10062import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI'
10063
10064@Entry
10065@Component
10066struct Frame {
10067  @State ANIMATION:ExpectedFrameRateRange = {min:0, max:120, expected: 90}
10068  @State GESTURE:ExpectedFrameRateRange = {min:0, max:120, expected: 30}
10069  private scenes: SwiperDynamicSyncScene[] = []
10070
10071  build() {
10072    Column() {
10073      Text("Animation"+ JSON.stringify(this.ANIMATION))
10074      Text("Responsive"+ JSON.stringify(this.GESTURE))
10075      Row(){
10076        Swiper() {
10077          Text("one")
10078          Text("two")
10079          Text("three")
10080        }
10081        .width('100%')
10082        .height('300vp')
10083        .id("dynamicSwiper")
10084        .backgroundColor(Color.Blue)
10085        .autoPlay(true)
10086        .onAppear(()=>{
10087          this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[]
10088        })
10089      }
10090
10091      Button("set frame")
10092        .onClick(()=>{
10093          this.scenes.forEach((scenes: SwiperDynamicSyncScene) => {
10094
10095            if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) {
10096              scenes.setFrameRateRange(this.ANIMATION)
10097              scenes.getFrameRateRange()
10098            }
10099
10100            if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) {
10101              scenes.setFrameRateRange(this.GESTURE)
10102              scenes.getFrameRateRange()
10103            }
10104          });
10105        })
10106      }
10107  }
10108}
10109```
10110## SwiperDynamicSyncScene<sup>12+</sup>
10111
10112Inherits from [DynamicSyncScene](#dynamicsyncscene12) and represents the dynamic sync scene of the **Swiper** component.
10113
10114**Atomic service API**: This API can be used in atomic services since API version 12.
10115
10116**System capability**: SystemCapability.ArkUI.ArkUI.Full
10117
10118| Name      | Type                                                     | Read Only| Optional| Description                               |
10119| --------- | --------------------------------------------------------- | ---- | ---- | ---------------------------------- |
10120| type      | [SwiperDynamicSyncSceneType](#swiperdynamicsyncscenetype12) | Yes  | No  | Dynamic sync scene of the **Swiper** component.            |
10121
10122## SwiperDynamicSyncSceneType<sup>12+</sup>
10123
10124Enumerates the dynamic sync scene types.
10125
10126**Atomic service API**: This API can be used in atomic services since API version 12.
10127
10128**System capability**: SystemCapability.ArkUI.ArkUI.Full
10129
10130| Name    | Value  | Description                  |
10131| -------- | ---- | ---------------------- |
10132| GESTURE | 0   | Gesture operation.|
10133| ANIMATION | 1   | Animation transition.|
10134
10135## MarqueeDynamicSyncScene<sup>14+</sup>
10136
10137Inherits from [DynamicSyncScene](#dynamicsyncscene12) and represents the dynamic sync scene of the [Marquee](arkui-ts/ts-basic-components-marquee.md) component.
10138
10139**Atomic service API**: This API can be used in atomic services since API version 14.
10140
10141**System capability**: SystemCapability.ArkUI.ArkUI.Full
10142
10143| Name      | Type                                                     | Read Only| Optional| Description                               |
10144| --------- | --------------------------------------------------------- | ---- | ---- | ---------------------------------- |
10145| type      | [MarqueeDynamicSyncSceneType](#marqueedynamicsyncscenetype14) | Yes  | No  | Dynamic sync scene of the **Marquee** component.            |
10146
10147## MarqueeDynamicSyncSceneType<sup>14+</sup>
10148
10149Enumerates the dynamic sync scene types for the **Marquee** component.
10150
10151**Atomic service API**: This API can be used in atomic services since API version 14.
10152
10153**System capability**: SystemCapability.ArkUI.ArkUI.Full
10154
10155| Name    | Value  | Description                  |
10156| -------- | ---- | ---------------------- |
10157| ANIMATION | 1   | Animation transition.|
10158
10159**Example**
10160
10161```ts
10162import { MarqueeDynamicSyncSceneType, MarqueeDynamicSyncScene } from '@kit.ArkUI';
10163
10164@Entry
10165@Component
10166struct MarqueeExample {
10167  @State start: boolean = false
10168  @State src: string = ''
10169  @State marqueeText: string = 'Running Marquee'
10170  private fromStart: boolean = true
10171  private step: number = 10
10172  private loop: number = Number.POSITIVE_INFINITY
10173  controller: TextClockController = new TextClockController()
10174  convert2time(value: number): string{
10175    let date = new Date(Number(value+'000'));
10176    let hours = date.getHours().toString().padStart(2, '0');
10177    let minutes = date.getMinutes().toString().padStart(2, '0');
10178    let seconds = date.getSeconds().toString().padStart(2, '0');
10179    return hours+ ":" + minutes + ":" + seconds;
10180  }
10181  @State ANIMATION: ExpectedFrameRateRange = {min:0, max:120, expected:30}
10182  private scenes: MarqueeDynamicSyncScene[] = []
10183
10184  build() {
10185    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
10186      Marquee({
10187        start: this.start,
10188        step: this.step,
10189        loop: this.loop,
10190        fromStart: this.fromStart,
10191        src: this.marqueeText + this.src
10192      })
10193        .marqueeUpdateStrategy(MarqueeUpdateStrategy.PRESERVE_POSITION)
10194        .width(300)
10195        .height(80)
10196        .fontColor('#FFFFFF')
10197        .fontSize(48)
10198        .fontWeight(700)
10199        .backgroundColor('#182431')
10200        .margin({ bottom: 40 })
10201        .id('dynamicMarquee')
10202        .onAppear(()=>{
10203          this.scenes = this.getUIContext().requireDynamicSyncScene('dynamicMarquee') as MarqueeDynamicSyncScene[]
10204        })
10205      Button('Start')
10206        .onClick(() => {
10207          this.start = true
10208          this.controller.start()
10209          this.scenes.forEach((scenes: MarqueeDynamicSyncScene) => {
10210            if (scenes.type == MarqueeDynamicSyncSceneType.ANIMATION) {
10211              scenes.setFrameRateRange(this.ANIMATION)
10212            }
10213          });
10214        })
10215        .width(120)
10216        .height(40)
10217        .fontSize(16)
10218        .fontWeight(500)
10219        .backgroundColor('#007DFF')
10220      TextClock({ timeZoneOffset: -8, controller: this.controller })
10221        .format('hms')
10222        .onDateChange((value: number) => {
10223          this.src = this.convert2time(value);
10224        })
10225        .margin(20)
10226        .fontSize(30)
10227    }
10228    .width('100%')
10229    .height('100%')
10230  }
10231}
10232```
10233## TextMenuController<sup>16+</sup>
10234In 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.
10235
10236### setMenuOptions<sup>16+</sup>
10237
10238setMenuOptions(options: TextMenuOptions): void
10239
10240Sets menu options.
10241
10242**Atomic service API**: This API can be used in atomic services since API version 16.
10243
10244**System capability**: SystemCapability.ArkUI.ArkUI.Full
10245
10246**Parameters**
10247
10248| Name     | Type        | Mandatory  | Description  |
10249| -------- | ---------- | ---- | ---- |
10250| options | [TextMenuOptions](../apis-arkui/arkui-ts/ts-text-common.md#textmenuoptions16)| Yes   | Menu options.<br>Default value: **{showMode: TextMenuShowMode.DEFAULT}**|
10251
10252**Example**
10253
10254```ts
10255// xxx.ets
10256@Entry
10257@Component
10258struct Index {
10259  aboutToAppear(): void {
10260    // Set the UIContext to preferentially display the context menu on selection in a separate window.
10261    this.getUIContext()
10262      .getTextMenuController()
10263      .setMenuOptions(
10264        {
10265          showMode: TextMenuShowMode.PREFER_WINDOW
10266        }
10267      )
10268  }
10269
10270  build() {
10271    Row() {
10272      Column() {
10273        TextInput({ text: "This is a TextInput. Long press to display the context menu on selection." })
10274          .height(60)
10275          .fontStyle(FontStyle.Italic)
10276          .fontWeight(FontWeight.Bold)
10277          .textAlign(TextAlign.Center)
10278          .caretStyle({ width: '4vp' })
10279
10280        Text("This is a Text. Long press to display the context menu on selection.")
10281          .height(60)
10282          .copyOption(CopyOptions.InApp)
10283          .fontStyle(FontStyle.Italic)
10284          .fontWeight(FontWeight.Bold)
10285          .textAlign(TextAlign.Center)
10286      }.width('100%')
10287    }
10288    .height('100%')
10289  }
10290}
10291```
10292