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) | No | Parameters for **OverlayManager**.| 215 216**Return value** 217 218| Type | Description | 219| ------- | -------------- | 220| boolean | Whether the setting is successful.| 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 // Modify the property in the animation closure where duration is set to 0. This stops the previous animation and applies the new value. 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### runScopedTask 997 998runScopedTask(callback: () => void): void 999 1000Executes the specified callback in this UI context. 1001 1002**Atomic service API**: This API can be used in atomic services since API version 11. 1003 1004**System capability**: SystemCapability.ArkUI.ArkUI.Full 1005 1006**Parameters** 1007 1008| Name | Type | Mandatory | Description | 1009| -------- | ---------- | ---- | ---- | 1010| callback | () => void | Yes | Callback used to return the result.| 1011 1012**Example** 1013 1014<!--code_no_check--> 1015```ts 1016uiContext.runScopedTask( 1017 () => { 1018 console.info('Succeeded in runScopedTask'); 1019 } 1020); 1021``` 1022 1023### setKeyboardAvoidMode<sup>11+</sup> 1024 1025setKeyboardAvoidMode(value: KeyboardAvoidMode): void 1026 1027Sets the avoidance mode for the virtual keyboard. 1028 1029**Atomic service API**: This API can be used in atomic services since API version 11. 1030 1031**System capability**: SystemCapability.ArkUI.ArkUI.Full 1032 1033**Parameters** 1034 1035| Name | Type | Mandatory | Description | 1036| -------- | ---------- | ---- | ---- | 1037| value | [KeyboardAvoidMode](#keyboardavoidmode11)| Yes | Avoidance mode for the virtual keyboard.<br>Default value: **KeyboardAvoidMode.OFFSET**| 1038 1039**Example** 1040 1041```ts 1042// EntryAbility.ets 1043import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI'; 1044import { hilog } from '@kit.PerformanceAnalysisKit'; 1045 1046onWindowStageCreate(windowStage: window.WindowStage) { 1047 // Main window is created, set main page for this ability 1048 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1049 1050 windowStage.loadContent('pages/Index', (err, data) => { 1051 let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext(); 1052 uiContext.setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE); 1053 if (err.code) { 1054 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1055 return; 1056 } 1057 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1058 }); 1059 } 1060``` 1061 1062### getKeyboardAvoidMode<sup>11+</sup> 1063 1064getKeyboardAvoidMode(): KeyboardAvoidMode 1065 1066Obtains the avoidance mode for the virtual keyboard. 1067 1068**Atomic service API**: This API can be used in atomic services since API version 11. 1069 1070**System capability**: SystemCapability.ArkUI.ArkUI.Full 1071 1072**Return value** 1073 1074| Type | Description | 1075| ---------- | ---- | 1076| [KeyboardAvoidMode](#keyboardavoidmode11)| Avoidance mode for the virtual keyboard.| 1077 1078**Example** 1079 1080```ts 1081// EntryAbility.ets 1082import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI'; 1083import { hilog } from '@kit.PerformanceAnalysisKit'; 1084 1085onWindowStageCreate(windowStage: window.WindowStage) { 1086 // Main window is created, set main page for this ability 1087 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1088 1089 windowStage.loadContent('pages/Index', (err, data) => { 1090 let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext(); 1091 let KeyboardAvoidMode = uiContext.getKeyboardAvoidMode(); 1092 hilog.info(0x0000, "KeyboardAvoidMode:", JSON.stringify(KeyboardAvoidMode)); 1093 if (err.code) { 1094 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1095 return; 1096 } 1097 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1098 }); 1099 } 1100 1101``` 1102 1103### getAtomicServiceBar<sup>11+</sup> 1104 1105getAtomicServiceBar(): Nullable\<AtomicServiceBar> 1106 1107Obtains an **AtomicServiceBar** object, which can be used to set the properties of the atomic service menu bar. 1108 1109**Atomic service API**: This API can be used in atomic services since API version 11. 1110 1111**System capability**: SystemCapability.ArkUI.ArkUI.Full 1112 1113**Return value** 1114 1115| Type | Description | 1116| ------------------------------------------------- | ------------------------------------------------------------ | 1117| Nullable<[AtomicServiceBar](#atomicservicebar11)> | Returns the **AtomicServerBar** type if the service is an atomic service; returns **undefined** type otherwise.| 1118 1119**Example** 1120 1121```ts 1122// EntryAbility.ets 1123import { UIContext, AtomicServiceBar, window } from '@kit.ArkUI'; 1124import { hilog } from '@kit.PerformanceAnalysisKit'; 1125onWindowStageCreate(windowStage: window.WindowStage) { 1126 // Main window is created, set main page for this ability 1127 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 1128 windowStage.loadContent('pages/Index', (err, data) => { 1129 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 1130 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 1131 if (atomicServiceBar != undefined) { 1132 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 1133 } else { 1134 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 1135 } 1136 }); 1137} 1138``` 1139### getDragController<sup>11+</sup> 1140 1141getDragController(): DragController 1142 1143Obtains the **DragController** object, which can be used to create and initiate dragging. 1144 1145**Atomic service API**: This API can be used in atomic services since API version 12. 1146 1147**System capability**: SystemCapability.ArkUI.ArkUI.Full 1148 1149**Return value** 1150 1151|Type|Description| 1152|----|----| 1153|[DragController](js-apis-arkui-dragController.md)| **DragController** object.| 1154 1155**Example** 1156 1157<!--code_no_check--> 1158```ts 1159uiContext.getDragController(); 1160``` 1161 1162### keyframeAnimateTo<sup>11+</sup> 1163 1164keyframeAnimateTo(param: KeyframeAnimateParam, keyframes: Array<KeyframeState>): void 1165 1166Generates a key frame animation. For details about how to use this API, see [keyframeAnimateTo](arkui-ts/ts-keyframeAnimateTo.md). 1167 1168**Atomic service API**: This API can be used in atomic services since API version 12. 1169 1170**System capability**: SystemCapability.ArkUI.ArkUI.Full 1171 1172**Parameters** 1173 1174| Name| Type | Mandatory| Description | 1175| ------------ | ---------------------------------------------------- | ------- | ---------------------------- | 1176| param | [KeyframeAnimateParam](arkui-ts/ts-keyframeAnimateTo.md#keyframeanimateparam) | Yes | Overall animation parameter of the keyframe animation. | 1177| keyframes | Array<[KeyframeState](arkui-ts/ts-keyframeAnimateTo.md#keyframestate)> | Yes | States of all keyframes. | 1178 1179### getFocusController<sup>12+</sup> 1180 1181getFocusController(): FocusController 1182 1183Obtains a [FocusController](js-apis-arkui-UIContext.md#focuscontroller12) object, which can be used to control the focus. 1184 1185**Atomic service API**: This API can be used in atomic services since API version 12. 1186 1187**System capability**: SystemCapability.ArkUI.ArkUI.Full 1188 1189**Return value** 1190 1191|Type|Description| 1192|----|----| 1193|[FocusController](js-apis-arkui-UIContext.md#focuscontroller12)| **FocusController** object.| 1194 1195**Example** 1196 1197<!--code_no_check--> 1198```ts 1199uiContext.getFocusController(); 1200``` 1201 1202### getFilteredInspectorTree<sup>12+</sup> 1203 1204getFilteredInspectorTree(filters?: Array\<string\>): string 1205 1206Obtains the component tree and component attributes. 1207 1208**Atomic service API**: This API can be used in atomic services since API version 12. 1209 1210**System capability**: SystemCapability.ArkUI.ArkUI.Full 1211 1212**Parameters** 1213 1214| Name | Type | Mandatory| Description | 1215| ------- | --------------- | ---- | ------------------------------------------------------------ | 1216| 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.| 1217 1218**Return value** 1219 1220| Type | Description | 1221| ------ | ---------------------------------- | 1222| string | JSON string of the component tree and component attributes.| 1223 1224**Error codes** 1225 1226For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1227 1228| ID| Error Message| 1229| ------- | -------- | 1230| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1231 1232**Example** 1233 1234<!--code_no_check--> 1235```ts 1236uiContext.getFilteredInspectorTree(['id', 'src', 'content']); 1237``` 1238 1239### getFilteredInspectorTreeById<sup>12+</sup> 1240 1241getFilteredInspectorTreeById(id: string, depth: number, filters?: Array\<string\>): string 1242 1243Obtains the attributes of the specified component and its child components. 1244 1245**Atomic service API**: This API can be used in atomic services since API version 12. 1246 1247**System capability**: SystemCapability.ArkUI.ArkUI.Full 1248 1249**Parameters** 1250 1251| Name | Type | Mandatory| Description | 1252| ------- | --------------- | ---- | ------------------------------------------------------------ | 1253| id | string | Yes | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.| 1254| 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.| 1255| 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.| 1256 1257**Return value** 1258 1259| Type | Description | 1260| ------ | -------------------------------------------- | 1261| string | JSON string of the attributes of the specified component and its child components.| 1262 1263 1264**Error codes** 1265 1266For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1267 1268| ID| Error Message| 1269| ------- | -------- | 1270| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1271 1272**Example** 1273 1274<!--code_no_check--> 1275```ts 1276uiContext.getFilteredInspectorTreeById('testId', 0, ['id', 'src', 'content']); 1277``` 1278 1279### getCursorController<sup>12+</sup> 1280 1281getCursorController(): CursorController 1282 1283Obtains a [CursorController](js-apis-arkui-UIContext.md#cursorcontroller12) object, which can be used to control the focus. 1284 1285**Atomic service API**: This API can be used in atomic services since API version 12. 1286 1287**System capability**: SystemCapability.ArkUI.ArkUI.Full 1288 1289**Return value** 1290 1291|Type|Description| 1292|----|----| 1293|[CursorController](js-apis-arkui-UIContext.md#cursorcontroller12)| **CursorController** object.| 1294 1295**Example** 1296 1297<!--code_no_check--> 1298```ts 1299uiContext.CursorController(); 1300``` 1301 1302### getContextMenuController<sup>12+</sup> 1303 1304getContextMenuController(): ContextMenuController 1305 1306Obtains a [ContextMenuController](#contextmenucontroller12) object, which can be used to control menus. 1307 1308**Atomic service API**: This API can be used in atomic services since API version 12. 1309 1310**System capability**: SystemCapability.ArkUI.ArkUI.Full 1311 1312**Return value** 1313 1314|Type|Description| 1315|----|----| 1316|[ContextMenuController](#contextmenucontroller12)| **ContextMenuController** object.| 1317 1318**Example** 1319 1320<!--code_no_check--> 1321```ts 1322uiContext.getContextMenuController(); 1323``` 1324 1325### getMeasureUtils<sup>12+</sup> 1326 1327getMeasureUtils(): MeasureUtils 1328 1329Obtains a **MeasureUtils** object for text calculation. 1330 1331**Atomic service API**: This API can be used in atomic services since API version 12. 1332 1333**System capability**: SystemCapability.ArkUI.ArkUI.Full 1334 1335**Return value** 1336 1337| Type | Description | 1338| ------ | -------------------------------------------- | 1339| [MeasureUtils](js-apis-arkui-UIContext.md#measureutils12) | Text metrics, such as text height and width.| 1340 1341**Example** 1342 1343<!--code_no_check--> 1344```ts 1345uiContext.getMeasureUtils(); 1346``` 1347 1348### getComponentSnapshot<sup>12+</sup> 1349 1350getComponentSnapshot(): ComponentSnapshot 1351 1352Obtains a **ComponentSnapshot** object, which can be used to obtain a component snapshot. 1353 1354**Atomic service API**: This API can be used in atomic services since API version 12. 1355 1356**System capability**: SystemCapability.ArkUI.ArkUI.Full 1357 1358**Return value** 1359 1360| Type | Description | 1361| ------------------------------------------------------------ | --------------------------- | 1362| [ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12) | **ComponentSnapshot** object.| 1363 1364**Example** 1365 1366<!--code_no_check--> 1367```ts 1368uiContext.getComponentSnapshot(); 1369``` 1370 1371### vp2px<sup>12+</sup> 1372 1373vp2px(value : number) : number 1374 1375Converts a value in units of vp to a value in units of px. 1376 1377**Atomic service API**: This API can be used in atomic services since API version 12. 1378 1379**System capability**: SystemCapability.ArkUI.ArkUI.Full 1380 1381**Parameters** 1382 1383| Name| Type | Mandatory| Description | 1384| ------ | ------ | ---- | -------------------------------------- | 1385| value | number | Yes | Value to convert.| 1386 1387**Return value** 1388 1389| Type | Description | 1390| ------ | -------------- | 1391| number | Value after conversion.| 1392 1393**Example** 1394 1395<!--code_no_check--> 1396```ts 1397uiContext.vp2px(200); 1398``` 1399 1400### px2vp<sup>12+</sup> 1401 1402px2vp(value : number) : number 1403 1404Converts a value in units of px to a value in units of vp. 1405 1406**Atomic service API**: This API can be used in atomic services since API version 12. 1407 1408**System capability**: SystemCapability.ArkUI.ArkUI.Full 1409 1410**Parameters** 1411 1412| Name| Type | Mandatory| Description | 1413| ------ | ------ | ---- | -------------------------------------- | 1414| value | number | Yes | Value to convert.| 1415 1416**Return value** 1417 1418| Type | Description | 1419| ------ | -------------- | 1420| number | Value after conversion.| 1421 1422**Example** 1423 1424<!--code_no_check--> 1425```ts 1426uiContext.px2vp(200); 1427``` 1428 1429### fp2px<sup>12+</sup> 1430 1431fp2px(value : number) : number 1432 1433Converts a value in units of fp to a value in units of px. 1434 1435**Atomic service API**: This API can be used in atomic services since API version 12. 1436 1437**System capability**: SystemCapability.ArkUI.ArkUI.Full 1438 1439**Parameters** 1440 1441| Name| Type | Mandatory| Description | 1442| ------ | ------ | ---- | -------------------------------------- | 1443| value | number | Yes | Value to convert.| 1444 1445**Return value** 1446 1447| Type | Description | 1448| ------ | -------------- | 1449| number | Value after conversion.| 1450 1451**Example** 1452 1453<!--code_no_check--> 1454```ts 1455uiContext.fp2px(200); 1456``` 1457 1458### px2fp<sup>12+</sup> 1459 1460px2fp(value : number) : number 1461 1462Converts a value in units of px to a value in units of fp. 1463 1464**Atomic service API**: This API can be used in atomic services since API version 12. 1465 1466**System capability**: SystemCapability.ArkUI.ArkUI.Full 1467 1468**Parameters** 1469 1470| Name| Type | Mandatory| Description | 1471| ------ | ------ | ---- | -------------------------------------- | 1472| value | number | Yes | Value to convert.| 1473 1474**Return value** 1475 1476| Type | Description | 1477| ------ | -------------- | 1478| number | Value after conversion.| 1479 1480**Example** 1481 1482<!--code_no_check--> 1483```ts 1484uiContext.px2fp(200); 1485``` 1486 1487### lpx2px<sup>12+</sup> 1488 1489lpx2px(value : number) : number 1490 1491Converts a value in units of lpx to a value in units of px. 1492 1493**Atomic service API**: This API can be used in atomic services since API version 12. 1494 1495**System capability**: SystemCapability.ArkUI.ArkUI.Full 1496 1497**Parameters** 1498 1499| Name| Type | Mandatory| Description | 1500| ------ | ------ | ---- | --------------------------------------- | 1501| value | number | Yes | Value to convert.| 1502 1503**Return value** 1504 1505| Type | Description | 1506| ------ | -------------- | 1507| number | Value after conversion.| 1508 1509**Example** 1510 1511<!--code_no_check--> 1512```ts 1513uiContext.lpx2px(200); 1514``` 1515 1516### px2lpx<sup>12+</sup> 1517 1518px2lpx(value : number) : number 1519 1520Converts a value in units of px to a value in units of lpx. 1521 1522**Atomic service API**: This API can be used in atomic services since API version 12. 1523 1524**System capability**: SystemCapability.ArkUI.ArkUI.Full 1525 1526**Parameters** 1527 1528| Name| Type | Mandatory| Description | 1529| ------ | ------ | ---- | --------------------------------------- | 1530| value | number | Yes | Value to convert.| 1531 1532**Return value** 1533 1534| Type | Description | 1535| ------ | -------------- | 1536| number | Value after conversion.| 1537 1538**Example** 1539 1540<!--code_no_check--> 1541```ts 1542uiContext.px2lpx(200); 1543``` 1544 1545### getWindowName<sup>12+</sup> 1546 1547getWindowName(): string | undefined 1548 1549Obtains the name of the window where this instance is located. 1550 1551**Atomic service API**: This API can be used in atomic services since API version 12. 1552 1553**System capability**: SystemCapability.ArkUI.ArkUI.Full 1554 1555**Return value** 1556 1557| Type | Description | 1558| ------ | -------------------------------------------- | 1559| string \| undefined | Name of the window where the current instance is located. If the window does not exist, **undefined** is returned.| 1560 1561**Example** 1562 1563```ts 1564import { window } from '@kit.ArkUI'; 1565 1566@Entry 1567@Component 1568struct Index { 1569 @State message: string = 'Hello World' 1570 1571 aboutToAppear() { 1572 const windowName = this.getUIContext().getWindowName(); 1573 console.info('WindowName ' + windowName); 1574 const currWindow = window.findWindow(windowName); 1575 const windowProperties = currWindow.getWindowProperties(); 1576 console.info(`Window width ${windowProperties.windowRect.width}, height ${windowProperties.windowRect.height}`); 1577 } 1578 1579 build() { 1580 Row() { 1581 Column() { 1582 Text(this.message) 1583 .fontSize(50) 1584 .fontWeight(FontWeight.Bold) 1585 } 1586 .width('100%') 1587 } 1588 .height('100%') 1589 } 1590} 1591``` 1592 1593### getWindowWidthBreakpoint<sup>13+</sup> 1594 1595getWindowWidthBreakpoint(): WidthBreakpoint 1596 1597Obtains 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). 1598 1599**Atomic service API**: This API can be used in atomic services since API version 13. 1600 1601**System capability**: SystemCapability.ArkUI.ArkUI.Full 1602 1603**Return value** 1604 1605| Type | Description | 1606| ------ | -------------------------------------------- | 1607| [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.| 1608 1609**Example** 1610 1611```ts 1612import { UIContext } from '@kit.ArkUI'; 1613 1614@Entry 1615@Component 1616struct Index { 1617 @State message: string = 'Hello World'; 1618 1619 build() { 1620 Row() { 1621 Column() { 1622 Text(this.message) 1623 .fontSize(30) 1624 .fontWeight(FontWeight.Bold) 1625 Button() { 1626 Text('test') 1627 .fontSize(30) 1628 } 1629 .onClick(() => { 1630 let uiContext: UIContext = this.getUIContext(); 1631 let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint(); 1632 let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint(); 1633 console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`) 1634 }) 1635 } 1636 .width('100%') 1637 } 1638 .height('100%') 1639 } 1640} 1641``` 1642 1643### getWindowHeightBreakpoint<sup>13+</sup> 1644 1645getWindowHeightBreakpoint(): HeightBreakpoint 1646 1647Obtains 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). 1648 1649**Atomic service API**: This API can be used in atomic services since API version 13. 1650 1651**System capability**: SystemCapability.ArkUI.ArkUI.Full 1652 1653**Return value** 1654 1655| Type | Description | 1656| ------ | -------------------------------------------- | 1657| [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.| 1658 1659**Example** 1660 1661```ts 1662import { UIContext } from '@kit.ArkUI'; 1663 1664@Entry 1665@Component 1666struct Index { 1667 @State message: string = 'Hello World'; 1668 1669 build() { 1670 Row() { 1671 Column() { 1672 Text(this.message) 1673 .fontSize(30) 1674 .fontWeight(FontWeight.Bold) 1675 Button() { 1676 Text('test') 1677 .fontSize(30) 1678 } 1679 .onClick(() => { 1680 let uiContext: UIContext = this.getUIContext(); 1681 let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint(); 1682 let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint(); 1683 console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`) 1684 }) 1685 } 1686 .width('100%') 1687 } 1688 .height('100%') 1689 } 1690} 1691``` 1692 1693### postFrameCallback<sup>12+</sup> 1694 1695postFrameCallback(frameCallback: FrameCallback): void 1696 1697Registers a callback that is executed when the next frame is rendered. 1698 1699**Atomic service API**: This API can be used in atomic services since API version 12. 1700 1701**System capability**: SystemCapability.ArkUI.ArkUI.Full 1702 1703**Parameters** 1704 1705| Name| Type | Mandatory| Description | 1706| ------ | ------ | ---- | --------------------------------------- | 1707| frameCallback | [FrameCallback](#framecallback12) | Yes | Callback to be executed for the next frame.| 1708 1709**Example** 1710 1711```ts 1712import {FrameCallback } from '@kit.ArkUI'; 1713 1714class MyFrameCallback extends FrameCallback { 1715 private tag: string; 1716 1717 constructor(tag: string) { 1718 super() 1719 this.tag = tag; 1720 } 1721 1722 onFrame(frameTimeNanos: number) { 1723 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 1724 } 1725} 1726 1727@Entry 1728@Component 1729struct Index { 1730 build() { 1731 Row() { 1732 Button('Invoke postFrameCallback') 1733 .onClick(() => { 1734 this.getUIContext().postFrameCallback(new MyFrameCallback("normTask")); 1735 }) 1736 } 1737 } 1738} 1739``` 1740 1741### postDelayedFrameCallback<sup>12+</sup> 1742 1743postDelayedFrameCallback(frameCallback: FrameCallback, delayTime: number): void 1744 1745Registers a callback to be executed on the next frame after a delay. 1746 1747**Atomic service API**: This API can be used in atomic services since API version 12. 1748 1749**System capability**: SystemCapability.ArkUI.ArkUI.Full 1750 1751**Parameters** 1752 1753| Name| Type | Mandatory| Description | 1754| ------ | ------ | ---- | --------------------------------------- | 1755| frameCallback | [FrameCallback](#framecallback12) | Yes | Callback to be executed for the next frame.| 1756| 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**.| 1757 1758**Example** 1759 1760```ts 1761import {FrameCallback } from '@kit.ArkUI'; 1762 1763class MyFrameCallback extends FrameCallback { 1764 private tag: string; 1765 1766 constructor(tag: string) { 1767 super() 1768 this.tag = tag; 1769 } 1770 1771 onFrame(frameTimeNanos: number) { 1772 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 1773 } 1774} 1775 1776@Entry 1777@Component 1778struct Index { 1779 build() { 1780 Row() { 1781 Button('Invoke postDelayedFrameCallback') 1782 .onClick(() => { 1783 this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5); 1784 }) 1785 } 1786 } 1787} 1788``` 1789 1790### requireDynamicSyncScene<sup>12+</sup> 1791 1792requireDynamicSyncScene(id: string): Array<DynamicSyncScene> 1793 1794Requests the dynamic sync scene of a component for customizing related frame rate configuration. 1795 1796**Atomic service API**: This API can be used in atomic services since API version 12. 1797 1798**System capability**: SystemCapability.ArkUI.ArkUI.Full 1799 1800**Parameters** 1801 1802| Name| Type | Mandatory| Description | 1803| ------ | ------ | ---- | --------------------------------------- | 1804| id | string | Yes | [Component ID](arkui-ts/ts-universal-attributes-component-id.md) of the target node.| 1805 1806**Return value** 1807 1808| Type | Description | 1809| ------ | -------------------------------------------- | 1810| Array<DynamicSyncScene> | **DynamicSyncScene** object array.| 1811 1812**Example** 1813 1814<!--code_no_check--> 1815```ts 1816uiContext.DynamicSyncScene("dynamicSyncScene") 1817``` 1818 1819### openBindSheet<sup>12+</sup> 1820 1821openBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions?: SheetOptions, targetId?: number): Promise<void> 1822 1823Creates a sheet whose content is as defined in **bindSheetContent** and displays the sheet. This API uses a promise to return the result. 1824 1825> **NOTE** 1826> 1827> 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**. 1828> 1829> 2. Since [updateBindSheet](#updatebindsheet12) and [closeBindSheet](#closebindsheet12) depend on **bindSheetContent**, you need to maintain the passed **bindSheetContent** yourself. 1830> 1831> 3. Setting **SheetOptions.UIContext** is not supported. 1832> 1833 1834**Atomic service API**: This API can be used in atomic services since API version 12. 1835 1836**System capability**: SystemCapability.ArkUI.ArkUI.Full 1837 1838**Parameters** 1839 1840| Name | Type | Mandatory | Description | 1841| ------- | ---------------------------------------- | ---- | ------- | 1842| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content to display on the sheet.| 1843| 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).| 1844| targetId | number | No | ID of the component to be bound. If this parameter is not set, no component is bound.| 1845 1846**Return value** 1847 1848| Type | Description | 1849| ---------------------------------------- | ------- | 1850| Promise<void> | Promise used to return the result.| 1851 1852**Error codes** 1853 1854For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Sheet Error Codes](errorcode-bindSheet.md). 1855 1856| ID | Error Message | 1857| ------ | ---------------------------------- | 1858| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1859| 120001 | The bindSheetContent is incorrect. | 1860| 120002 | The bindSheetContent already exists. | 1861| 120004 | The targetId does not exist. | 1862| 120005 | The node of targetId is not in the component tree. | 1863| 120006 | The node of targetId is not a child of the page node or NavDestination node. | 1864 1865**Example** 1866 1867```ts 1868import { FrameNode, ComponentContent } from "@kit.ArkUI"; 1869import { BusinessError } from '@kit.BasicServicesKit'; 1870 1871class Params { 1872 text: string = "" 1873 1874 constructor(text: string) { 1875 this.text = text; 1876 } 1877} 1878 1879let contentNode: ComponentContent<Params>; 1880let gUIContext: UIContext; 1881 1882@Builder 1883function buildText(params: Params) { 1884 Column() { 1885 Text(params.text) 1886 Button('Update BindSheet') 1887 .fontSize(20) 1888 .onClick(() => { 1889 gUIContext.updateBindSheet(contentNode, { 1890 backgroundColor: Color.Pink, 1891 }, true) 1892 .then(() => { 1893 console.info('updateBindSheet success'); 1894 }) 1895 .catch((err: BusinessError) => { 1896 console.info('updateBindSheet error: ' + err.code + ' ' + err.message); 1897 }) 1898 }) 1899 1900 Button('Close BindSheet') 1901 .fontSize(20) 1902 .onClick(() => { 1903 gUIContext.closeBindSheet(contentNode) 1904 .then(() => { 1905 console.info('closeBindSheet success'); 1906 }) 1907 .catch((err: BusinessError) => { 1908 console.info('closeBindSheet error: ' + err.code + ' ' + err.message); 1909 }) 1910 }) 1911 } 1912} 1913 1914@Entry 1915@Component 1916struct UIContextBindSheet { 1917 @State message: string = 'BindSheet'; 1918 1919 aboutToAppear() { 1920 gUIContext = this.getUIContext(); 1921 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 1922 } 1923 1924 build() { 1925 RelativeContainer() { 1926 Column() { 1927 Button('Open BindSheet') 1928 .fontSize(20) 1929 .onClick(() => { 1930 let uiContext = this.getUIContext(); 1931 let uniqueId = this.getUniqueId(); 1932 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 1933 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 1934 uiContext.openBindSheet(contentNode, { 1935 height: SheetSize.MEDIUM, 1936 backgroundColor: Color.Green, 1937 title: { title: "Title", subtitle: "subtitle" } 1938 }, targetId) 1939 .then(() => { 1940 console.info('openBindSheet success'); 1941 }) 1942 .catch((err: BusinessError) => { 1943 console.info('openBindSheet error: ' + err.code + ' ' + err.message); 1944 }) 1945 }) 1946 } 1947 } 1948 .height('100%') 1949 .width('100%') 1950 } 1951} 1952``` 1953 1954### updateBindSheet<sup>12+</sup> 1955 1956updateBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions: SheetOptions, partialUpdate?: boolean ): Promise<void> 1957 1958Updates the style of the sheet corresponding to the provided **bindSheetContent**. This API uses a promise to return the result. 1959 1960> **NOTE** 1961> 1962> **SheetOptions.UIContext**, **SheetOptions.mode**, and callback functions cannot be updated. 1963> 1964 1965**Atomic service API**: This API can be used in atomic services since API version 12. 1966 1967**System capability**: SystemCapability.ArkUI.ArkUI.Full 1968 1969**Parameters** 1970 1971| Name | Type | Mandatory | Description | 1972| ------- | ---------------------------------------- | ---- | ------- | 1973| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content displayed on the sheet.| 1974| 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.| 1975| 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.| 1976 1977**Return value** 1978 1979| Type | Description | 1980| ---------------------------------------- | ------- | 1981| Promise<void> | Promise used to return the result.| 1982 1983**Error codes** 1984 1985For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Sheet Error Codes](errorcode-bindSheet.md). 1986 1987| ID | Error Message | 1988| ------ | ---------------------------------- | 1989| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1990| 120001 | The bindSheetContent is incorrect. | 1991| 120003 | The bindSheetContent cannot be found. | 1992 1993**Example** 1994 1995```ts 1996import { FrameNode, ComponentContent } from "@kit.ArkUI"; 1997import { BusinessError } from '@kit.BasicServicesKit'; 1998 1999class Params { 2000 text: string = "" 2001 2002 constructor(text: string) { 2003 this.text = text; 2004 } 2005} 2006 2007let contentNode: ComponentContent<Params>; 2008let gUIContext: UIContext; 2009 2010@Builder 2011function buildText(params: Params) { 2012 Column() { 2013 Text(params.text) 2014 Button('Update BindSheet') 2015 .fontSize(20) 2016 .onClick(() => { 2017 gUIContext.updateBindSheet(contentNode, { 2018 backgroundColor: Color.Pink, 2019 }, true) 2020 .then(() => { 2021 console.info('updateBindSheet success'); 2022 }) 2023 .catch((err: BusinessError) => { 2024 console.info('updateBindSheet error: ' + err.code + ' ' + err.message); 2025 }) 2026 }) 2027 2028 Button('Close BindSheet') 2029 .fontSize(20) 2030 .onClick(() => { 2031 gUIContext.closeBindSheet(contentNode) 2032 .then(() => { 2033 console.info('closeBindSheet success'); 2034 }) 2035 .catch((err: BusinessError) => { 2036 console.info('closeBindSheet error: ' + err.code + ' ' + err.message); 2037 }) 2038 }) 2039 } 2040} 2041 2042@Entry 2043@Component 2044struct UIContextBindSheet { 2045 @State message: string = 'BindSheet'; 2046 2047 aboutToAppear() { 2048 gUIContext = this.getUIContext(); 2049 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 2050 } 2051 2052 build() { 2053 RelativeContainer() { 2054 Column() { 2055 Button('Open BindSheet') 2056 .fontSize(20) 2057 .onClick(() => { 2058 let uiContext = this.getUIContext(); 2059 let uniqueId = this.getUniqueId(); 2060 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 2061 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 2062 uiContext.openBindSheet(contentNode, { 2063 height: SheetSize.MEDIUM, 2064 backgroundColor: Color.Green, 2065 title: { title: "Title", subtitle: "subtitle" } 2066 }, targetId) 2067 .then(() => { 2068 console.info('openBindSheet success'); 2069 }) 2070 .catch((err: BusinessError) => { 2071 console.info('openBindSheet error: ' + err.code + ' ' + err.message); 2072 }) 2073 }) 2074 } 2075 } 2076 .height('100%') 2077 .width('100%') 2078 } 2079} 2080``` 2081 2082### closeBindSheet<sup>12+</sup> 2083 2084closeBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>): Promise<void> 2085 2086Closes the sheet corresponding to **bindSheetContent**. This API uses a promise to return the result. 2087 2088> **NOTE** 2089> 2090> Closing a sheet using this API will not invoke the **shouldDismiss** callback. 2091> 2092 2093**Atomic service API**: This API can be used in atomic services since API version 12. 2094 2095**System capability**: SystemCapability.ArkUI.ArkUI.Full 2096 2097**Parameters** 2098 2099| Name | Type | Mandatory | Description | 2100| ------- | ---------------------------------------- | ---- | ------- | 2101| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content to display on the sheet.| 2102 2103**Return value** 2104 2105| Type | Description | 2106| ---------------------------------------- | ------- | 2107| Promise<void> | Promise used to return the result.| 2108 2109**Error codes** 2110 2111For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Sheet Error Codes](errorcode-bindSheet.md). 2112 2113| ID | Error Message | 2114| ------ | ---------------------------------- | 2115| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 2116| 120001 | The bindSheetContent is incorrect. | 2117| 120003 | The bindSheetContent cannot be found. | 2118 2119**Example** 2120 2121```ts 2122import { FrameNode, ComponentContent } from "@kit.ArkUI"; 2123import { BusinessError } from '@kit.BasicServicesKit'; 2124 2125class Params { 2126 text: string = "" 2127 2128 constructor(text: string) { 2129 this.text = text; 2130 } 2131} 2132 2133let contentNode: ComponentContent<Params>; 2134let gUIContext: UIContext; 2135 2136@Builder 2137function buildText(params: Params) { 2138 Column() { 2139 Text(params.text) 2140 Button('Update BindSheet') 2141 .fontSize(20) 2142 .onClick(() => { 2143 gUIContext.updateBindSheet(contentNode, { 2144 backgroundColor: Color.Pink, 2145 }, true) 2146 .then(() => { 2147 console.info('updateBindSheet success'); 2148 }) 2149 .catch((err: BusinessError) => { 2150 console.info('updateBindSheet error: ' + err.code + ' ' + err.message); 2151 }) 2152 }) 2153 2154 Button('Close BindSheet') 2155 .fontSize(20) 2156 .onClick(() => { 2157 gUIContext.closeBindSheet(contentNode) 2158 .then(() => { 2159 console.info('closeBindSheet success'); 2160 }) 2161 .catch((err: BusinessError) => { 2162 console.info('closeBindSheet error: ' + err.code + ' ' + err.message); 2163 }) 2164 }) 2165 } 2166} 2167 2168@Entry 2169@Component 2170struct UIContextBindSheet { 2171 @State message: string = 'BindSheet'; 2172 2173 aboutToAppear() { 2174 gUIContext = this.getUIContext(); 2175 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 2176 } 2177 2178 build() { 2179 RelativeContainer() { 2180 Column() { 2181 Button('Open BindSheet') 2182 .fontSize(20) 2183 .onClick(() => { 2184 let uiContext = this.getUIContext(); 2185 let uniqueId = this.getUniqueId(); 2186 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 2187 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 2188 uiContext.openBindSheet(contentNode, { 2189 height: SheetSize.MEDIUM, 2190 backgroundColor: Color.Green, 2191 title: { title: "Title", subtitle: "subtitle" } 2192 }, targetId) 2193 .then(() => { 2194 console.info('openBindSheet success'); 2195 }) 2196 .catch((err: BusinessError) => { 2197 console.info('openBindSheet error: ' + err.code + ' ' + err.message); 2198 }) 2199 }) 2200 } 2201 } 2202 .height('100%') 2203 .width('100%') 2204 } 2205} 2206``` 2207 2208### isFollowingSystemFontScale<sup>13+</sup> 2209 2210isFollowingSystemFontScale(): boolean 2211 2212Checks whether this UI context follows the system font scale settings. 2213 2214**Atomic service API**: This API can be used in atomic services since API version 13. 2215 2216**System capability**: SystemCapability.ArkUI.ArkUI.Full 2217 2218**Return value** 2219 2220| Type | Description | 2221|---------|---------------| 2222| boolean | Whether the current UI context follows the system font scale settings.| 2223 2224**Example** 2225 2226<!--code_no_check--> 2227```ts 2228uiContext.isFollowingSystemFontScale() 2229``` 2230 2231### getMaxFontScale<sup>13+</sup> 2232 2233getMaxFontScale(): number 2234 2235Obtains the maximum font scale of this UI context. 2236 2237**Atomic service API**: This API can be used in atomic services since API version 13. 2238 2239**System capability**: SystemCapability.ArkUI.ArkUI.Full 2240 2241**Return value** 2242 2243| Type | Description | 2244|---------|-----------| 2245| number | Maximum font scale of the current UI context.| 2246 2247**Example** 2248 2249<!--code_no_check--> 2250```ts 2251uiContext.getMaxFontScale() 2252``` 2253 2254### bindTabsToScrollable<sup>13+</sup> 2255 2256bindTabsToScrollable(tabsController: TabsController, scroller: Scroller): void; 2257 2258Binds 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 appearance and disappearance animations of the tab bar for all **Tabs** components that are bound to it. Specifically, the tab bar appears when scrolling up and disappears when scrolling down. A **TabsController** instance can be bound with multiple **Scroller** instances, and conversely, a **Scroller** instance can be bound with multiple **TabsController** instances. 2259 2260> **NOTE** 2261> 2262> 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. 2263 2264**Atomic service API**: This API can be used in atomic services since API version 13. 2265 2266**System capability**: SystemCapability.ArkUI.ArkUI.Full 2267 2268**Parameters** 2269 2270| Name | Type | Mandatory | Description | 2271| ------- | ---------------------------------------- | ---- | ------- | 2272| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | Yes| Controller of the target **Tabs** component.| 2273| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target scrollable container.| 2274 2275**Example** 2276 2277```ts 2278@Entry 2279@Component 2280struct TabsExample { 2281 private arr: string[] = [] 2282 private parentTabsController: TabsController = new TabsController() 2283 private childTabsController: TabsController = new TabsController() 2284 private listScroller: Scroller = new Scroller() 2285 private parentScroller: Scroller = new Scroller() 2286 private childScroller: Scroller = new Scroller() 2287 2288 aboutToAppear(): void { 2289 for (let i = 0; i < 20; i++) { 2290 this.arr.push(i.toString()) 2291 } 2292 let context = this.getUIContext() 2293 context.bindTabsToScrollable(this.parentTabsController, this.listScroller) 2294 context.bindTabsToScrollable(this.childTabsController, this.listScroller) 2295 context.bindTabsToNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller) 2296 } 2297 2298 aboutToDisappear(): void { 2299 let context = this.getUIContext() 2300 context.unbindTabsFromScrollable(this.parentTabsController, this.listScroller) 2301 context.unbindTabsFromScrollable(this.childTabsController, this.listScroller) 2302 context.unbindTabsFromNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller) 2303 } 2304 2305 build() { 2306 Tabs({ barPosition: BarPosition.End, controller: this.parentTabsController }) { 2307 TabContent() { 2308 Tabs({ controller: this.childTabsController }) { 2309 TabContent() { 2310 List({ space: 20, initialIndex: 0, scroller: this.listScroller }) { 2311 ForEach(this.arr, (item: string) => { 2312 ListItem() { 2313 Text(item) 2314 .width('100%') 2315 .height(100) 2316 .fontSize(16) 2317 .textAlign(TextAlign.Center) 2318 .borderRadius(10) 2319 .backgroundColor(Color.Gray) 2320 } 2321 }, (item: string) => item) 2322 } 2323 .scrollBar(BarState.Off) 2324 .width('90%') 2325 .height('100%') 2326 .contentStartOffset(56) 2327 .contentEndOffset(52) 2328 }.tabBar(SubTabBarStyle.of('Top tab')) 2329 } 2330 .width('100%') 2331 .height('100%') 2332 .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. 2333 .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. 2334 }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), 'Scroller')) 2335 2336 TabContent() { 2337 Scroll(this.parentScroller) { 2338 List({ space: 20, initialIndex: 0, scroller: this.childScroller }) { 2339 ForEach(this.arr, (item: string) => { 2340 ListItem() { 2341 Text(item) 2342 .width('100%') 2343 .height(100) 2344 .fontSize(16) 2345 .textAlign(TextAlign.Center) 2346 .borderRadius(10) 2347 .backgroundColor(Color.Gray) 2348 } 2349 }, (item: string) => item) 2350 } 2351 .scrollBar(BarState.Off) 2352 .width('90%') 2353 .height('100%') 2354 .contentEndOffset(52) 2355 .nestedScroll({ scrollForward: NestedScrollMode.SELF_FIRST, scrollBackward: NestedScrollMode.SELF_FIRST }) 2356 } 2357 .width('100%') 2358 .height('100%') 2359 .scrollBar(BarState.Off) 2360 .scrollable(ScrollDirection.Vertical) 2361 .edgeEffect(EdgeEffect.Spring) 2362 }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), 'Nested Scroller')) 2363 } 2364 .width('100%') 2365 .height('100%') 2366 .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. 2367 .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. 2368 } 2369} 2370``` 2371 2372 2373 2374### unbindTabsFromScrollable<sup>13+</sup> 2375 2376unbindTabsFromScrollable(tabsController: TabsController, scroller: Scroller): void; 2377 2378Unbinds a **Tabs** component from a scrollable container. 2379 2380**Atomic service API**: This API can be used in atomic services since API version 13. 2381 2382**System capability**: SystemCapability.ArkUI.ArkUI.Full 2383 2384**Parameters** 2385 2386| Name | Type | Mandatory | Description | 2387| ------- | ---------------------------------------- | ---- | ------- | 2388| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | Yes| Controller of the target **Tabs** component.| 2389| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target scrollable container.| 2390 2391**Example** 2392 2393See the example for [bindTabsToScrollable](#bindtabstoscrollable13). 2394 2395### bindTabsToNestedScrollable<sup>13+</sup> 2396 2397bindTabsToNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void; 2398 2399Binds 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 appearance and disappearance animations of the tab bar for all **Tabs** components that are bound to it. Specifically, the tab bar appears when scrolling up and disappears when scrolling down. A **TabsController** instance can be bound with multiple nested **Scroller** instances, and conversely, a nested **Scroller** instance can be bound with multiple **TabsController** instances. 2400 2401**Atomic service API**: This API can be used in atomic services since API version 13. 2402 2403**System capability**: SystemCapability.ArkUI.ArkUI.Full 2404 2405**Parameters** 2406 2407| Name | Type | Mandatory | Description | 2408| ------- | ---------------------------------------- | ---- | ------- | 2409| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | Yes| Controller of the target **Tabs** component.| 2410| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target parent scrollable container.| 2411| 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**.| 2412 2413**Example** 2414 2415See the example for [bindTabsToScrollable](#bindtabstoscrollable13). 2416 2417### unbindTabsFromNestedScrollable<sup>13+</sup> 2418 2419unbindTabsFromNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void; 2420 2421Unbinds a **Tabs** component from a nested scrollable container. 2422 2423**Atomic service API**: This API can be used in atomic services since API version 13. 2424 2425**System capability**: SystemCapability.ArkUI.ArkUI.Full 2426 2427**Parameters** 2428 2429| Name | Type | Mandatory | Description | 2430| ------- | ---------------------------------------- | ---- | ------- | 2431| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | Yes| Controller of the target **Tabs** component.| 2432| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target parent scrollable container.| 2433| 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**.| 2434 2435**Example** 2436 2437See the example for [bindTabsToScrollable](#bindtabstoscrollable13). 2438 2439## Font 2440 2441In 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. 2442 2443### registerFont 2444 2445registerFont(options: font.FontOptions): void 2446 2447Registers a custom font with the font manager. 2448 2449**Atomic service API**: This API can be used in atomic services since API version 11. 2450 2451**System capability**: SystemCapability.ArkUI.ArkUI.Full 2452 2453**Parameters** 2454 2455| Name | Type | Mandatory | Description | 2456| ------- | ---------------------------------------- | ---- | ----------- | 2457| options | [font.FontOptions](js-apis-font.md#fontoptions) | Yes | Information about the custom font to register.| 2458 2459**Example** 2460 2461<!--code_no_check--> 2462```ts 2463import { Font } from '@kit.ArkUI'; 2464 2465let font:Font = uiContext.getFont(); 2466font.registerFont({ 2467 familyName: 'medium', 2468 familySrc: '/font/medium.ttf' 2469}); 2470``` 2471### getSystemFontList 2472 2473getSystemFontList(): Array\<string> 2474 2475Obtains the list of supported fonts. 2476 2477**Atomic service API**: This API can be used in atomic services since API version 11. 2478 2479**System capability**: SystemCapability.ArkUI.ArkUI.Full 2480 2481**Return value** 2482 2483| Type | Description | 2484| -------------- | --------- | 2485| Array\<string> | List of supported fonts.| 2486 2487> **NOTE** 2488> 2489> This API takes effect only on 2-in-1 devices. 2490 2491**Example** 2492 2493<!--code_no_check--> 2494```ts 2495import { Font } from '@kit.ArkUI'; 2496 2497let font:Font|undefined = uiContext.getFont(); 2498if(font){ 2499 font.getSystemFontList() 2500} 2501``` 2502 2503### getFontByName 2504 2505getFontByName(fontName: string): font.FontInfo 2506 2507Obtains information about a system font based on the font name. 2508 2509**Atomic service API**: This API can be used in atomic services since API version 11. 2510 2511**System capability**: SystemCapability.ArkUI.ArkUI.Full 2512 2513**Parameters** 2514 2515| Name | Type | Mandatory | Description | 2516| -------- | ------ | ---- | ------- | 2517| fontName | string | Yes | System font name.| 2518 2519**Return value** 2520 2521| Type | Description | 2522| ----------------------------------------- | -------------- | 2523| [font.FontInfo](js-apis-font.md#fontinfo10) | Information about the system font.| 2524 2525**Example** 2526 2527<!--code_no_check--> 2528```ts 2529import { Font } from '@kit.ArkUI'; 2530 2531let font:Font|undefined = uiContext.getFont(); 2532if(font){ 2533 font.getFontByName('Sans Italic') 2534} 2535``` 2536 2537### dispatchKeyEvent<sup>15+</sup> 2538 2539Dispatches a key event to the specified component. To ensure predictable behavior, the target component must be within the subtree of the dispatching component. 2540 2541**Atomic service API**: This API can be used in atomic services since API version 15. 2542 2543**System capability**: SystemCapability.ArkUI.ArkUI.Full 2544 2545| Name| Type | Mandatory| Description | 2546| ------ | ----------------------------- | ---- | ------------------ | 2547| node | number \| string | Yes | ID or unique ID of the target component.| 2548| event |[KeyEvent](./arkui-ts/ts-universal-events-key.md#keyevent) | Yes | **KeyEvent** object.| 2549 2550**Example** 2551 2552```ts 2553@Entry 2554@Component 2555struct Index { 2556 build() { 2557 Row() { 2558 Row() { 2559 Button('Button1').id('Button1').onKeyEvent((event) => { 2560 console.log("Button1"); 2561 return true 2562 }) 2563 Button('Button2').id('Button2').onKeyEvent((event) => { 2564 console.log("Button2"); 2565 return true 2566 }) 2567 } 2568 .width('100%') 2569 .height('100%') 2570 .id('Row1') 2571 .onKeyEventDispatch((event) => { 2572 let context = this.getUIContext(); 2573 context.getFocusController().requestFocus('Button1'); 2574 return context.dispatchKeyEvent('Button1', event); 2575 }) 2576 2577 } 2578 .height('100%') 2579 .width('100%') 2580 .onKeyEventDispatch((event) => { 2581 if (event.type == KeyType.Down) { 2582 let context = this.getUIContext(); 2583 context.getFocusController().requestFocus('Row1'); 2584 return context.dispatchKeyEvent('Row1', event); 2585 } 2586 return true; 2587 }) 2588 } 2589} 2590``` 2591 2592## Context<sup>12+</sup> 2593 2594type Context = common.Context 2595 2596Defines the context of the current ability. 2597 2598**Atomic service API**: This API can be used in atomic services since API version 12. 2599 2600**System capability**: SystemCapability.Ability.AbilityRuntime.Core 2601 2602**Model restriction**: This API can be used only in the stage model. 2603 2604| Type|Description | 2605| ------ | ------------------- | 2606| [common.Context](../apis-ability-kit/js-apis-app-ability-common.md#context) |Context object associated with the current ability.| 2607 2608## ComponentUtils 2609 2610In 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. 2611 2612### getRectangleById 2613 2614getRectangleById(id: string): componentUtils.ComponentInfo 2615 2616Obtains the size, position, translation, scaling, rotation, and affine matrix information of the specified component. 2617 2618**Atomic service API**: This API can be used in atomic services since API version 11. 2619 2620**System capability**: SystemCapability.ArkUI.ArkUI.Full 2621 2622**Parameters** 2623 2624| Name | Type | Mandatory | Description | 2625| ---- | ------ | ---- | --------- | 2626| id | string | Yes | Unique component ID.| 2627 2628**Return value** 2629 2630| Type | Description | 2631| ------------------------------------------------------------ | ------------------------------------------------ | 2632| [componentUtils.ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | Size, position, translation, scaling, rotation, and affine matrix information of the component.| 2633 2634**Error codes** 2635 2636For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 2637 2638| ID | Error Message | 2639| ------ | ------------------- | 2640| 100001 | UI execution context not found. | 2641 2642**Example** 2643 2644<!--code_no_check--> 2645```ts 2646import { ComponentUtils } from '@kit.ArkUI'; 2647 2648let componentUtils:ComponentUtils = uiContext.getComponentUtils(); 2649let modePosition = componentUtils.getRectangleById("onClick"); 2650let localOffsetWidth = modePosition.size.width; 2651let localOffsetHeight = modePosition.size.height; 2652``` 2653 2654## UIInspector 2655 2656In 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. 2657 2658### createComponentObserver 2659 2660createComponentObserver(id: string): inspector.ComponentObserver 2661 2662Creates an observer for the specified component. 2663 2664**Atomic service API**: This API can be used in atomic services since API version 11. 2665 2666**System capability**: SystemCapability.ArkUI.ArkUI.Full 2667 2668**Parameters** 2669 2670| Name | Type | Mandatory | Description | 2671| ---- | ------ | ---- | ------- | 2672| id | string | Yes | Component ID.| 2673 2674**Return value** 2675 2676| Type | Description | 2677| ------------------------------------------------------------ | -------------------------------------------------- | 2678| [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.| 2679 2680**Example** 2681 2682<!--code_no_check--> 2683```ts 2684import { UIInspector } from '@kit.ArkUI'; 2685 2686let inspector: UIInspector = uiContext.getUIInspector(); 2687let listener = inspector.createComponentObserver('COMPONENT_ID'); 2688``` 2689 2690## PageInfo<sup>12+</sup> 2691Represents the page information of the router or navigation destination. If there is no related page information, **undefined** is returned. 2692 2693**Atomic service API**: This API can be used in atomic services since API version 12. 2694 2695**System capability**: SystemCapability.ArkUI.ArkUI.Full 2696 2697| Name| Type| Mandatory| Description| 2698| -------- | -------- | -------- | -------- | 2699| routerPageInfo | observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo) | No| Router information.| 2700| navDestinationInfo | observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo) | No| Navigation destination information.| 2701 2702## UIObserver<sup>11+</sup> 2703 2704In 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. 2705 2706### on('navDestinationUpdate')<sup>11+</sup> 2707 2708on(type: 'navDestinationUpdate', callback: Callback\<observer.NavDestinationInfo\>): void 2709 2710Subscribes to status changes of this **NavDestination** component. 2711 2712**Atomic service API**: This API can be used in atomic services since API version 12. 2713 2714**System capability**: SystemCapability.ArkUI.ArkUI.Full 2715 2716**Parameters** 2717 2718| Name | Type | Mandatory| Description | 2719| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 2720| type | string | Yes | Event type. The value is fixed at **'navDestinationUpdate'**, which indicates the state change event of the **NavDestination** component.| 2721| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | Yes | Callback used to return the current state of the **NavDestination** component. | 2722 2723**Example** 2724 2725<!--code_no_check--> 2726```ts 2727import { UIObserver } from '@kit.ArkUI'; 2728 2729let observer:UIObserver = uiContext.getUIObserver(); 2730observer.on('navDestinationUpdate', (info) => { 2731 console.info('NavDestination state update', JSON.stringify(info)); 2732}); 2733``` 2734 2735### off('navDestinationUpdate')<sup>11+</sup> 2736 2737off(type: 'navDestinationUpdate', callback?: Callback\<observer.NavDestinationInfo\>): void 2738 2739Unsubscribes from state changes of this **NavDestination** component. 2740 2741**Atomic service API**: This API can be used in atomic services since API version 12. 2742 2743**System capability**: SystemCapability.ArkUI.ArkUI.Full 2744 2745**Parameters** 2746 2747| Name | Type | Mandatory| Description | 2748| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 2749| type | string | Yes | Event type. The value is fixed at **'navDestinationUpdate'**, which indicates the state change event of the **NavDestination** component.| 2750| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | No | Callback used to return the current state of the **NavDestination** component. | 2751 2752**Example** 2753 2754<!--code_no_check--> 2755```ts 2756import { UIObserver } from '@kit.ArkUI'; 2757 2758let observer:UIObserver = uiContext.getUIObserver(); 2759observer.off('navDestinationUpdate'); 2760``` 2761 2762### on('navDestinationUpdate')<sup>11+</sup> 2763 2764on(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback: Callback\<observer.NavDestinationInfo\>): void 2765 2766Subscribes to state changes of this **NavDestination** component. 2767 2768**Atomic service API**: This API can be used in atomic services since API version 12. 2769 2770**System capability**: SystemCapability.ArkUI.ArkUI.Full 2771 2772**Parameters** 2773 2774| Name | Type | Mandatory| Description | 2775| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2776| type | string | Yes | Event type. The value is fixed at **'navDestinationUpdate'**, which indicates the state change event of the **NavDestination** component.| 2777| options | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | Yes | ID of the target **NavDestination** component. | 2778| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | Yes | Callback used to return the current state of the **NavDestination** component. | 2779 2780**Example** 2781 2782<!--code_no_check--> 2783```ts 2784import { UIObserver } from '@kit.ArkUI'; 2785 2786let observer:UIObserver = uiContext.getUIObserver(); 2787observer.on('navDestinationUpdate', { navigationId: "testId" }, (info) => { 2788 console.info('NavDestination state update', JSON.stringify(info)); 2789}); 2790``` 2791 2792### off('navDestinationUpdate')<sup>11+</sup> 2793 2794off(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback?: Callback\<observer.NavDestinationInfo\>): void 2795 2796Unsubscribes from state changes of the **NavDestination** component. 2797 2798**Atomic service API**: This API can be used in atomic services since API version 12. 2799 2800**System capability**: SystemCapability.ArkUI.ArkUI.Full 2801 2802**Parameters** 2803 2804| Name | Type | Mandatory| Description | 2805| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2806| type | string | Yes | Event type. The value is fixed at **'navDestinationUpdate'**, which indicates the state change event of the **NavDestination** component.| 2807| options | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | Yes | ID of the target **NavDestination** component. | 2808| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | No | Callback used to return the current state of the **NavDestination** component. | 2809 2810**Example** 2811 2812<!--code_no_check--> 2813```ts 2814import { UIObserver } from '@kit.ArkUI'; 2815 2816let observer:UIObserver = uiContext.getUIObserver(); 2817observer.off('navDestinationUpdate', { navigationId: "testId" }); 2818``` 2819 2820### on('scrollEvent')<sup>12+</sup> 2821 2822on(type: 'scrollEvent', callback: Callback\<observer.ScrollEventInfo\>): void 2823 2824Subscribes to the start and end of a scroll event. 2825 2826**Atomic service API**: This API can be used in atomic services since API version 12. 2827 2828**System capability**: SystemCapability.ArkUI.ArkUI.Full 2829 2830**Parameters** 2831 2832| Name | Type | Mandatory| Description | 2833| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 2834| type | string | Yes | Event type. The value **'scrollEvent'** indicates the start and end of a scroll event. | 2835| 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. | 2836 2837**Example** 2838 2839See [offscrollevent Example](#offscrollevent12-1). 2840 2841### off('scrollEvent')<sup>12+</sup> 2842 2843off(type: 'scrollEvent', callback?: Callback\<observer.ScrollEventInfo\>): void 2844 2845Unsubscribes from the start and end of a scroll event. 2846 2847**Atomic service API**: This API can be used in atomic services since API version 12. 2848 2849**System capability**: SystemCapability.ArkUI.ArkUI.Full 2850 2851**Parameters** 2852 2853| Name | Type | Mandatory| Description | 2854| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 2855| type | string | Yes | Event type. The value **'scrollEvent'** indicates the start and end of a scroll event. | 2856| 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. | 2857 2858**Example** 2859 2860See [offscrollevent Example](#offscrollevent12-1). 2861 2862### on('scrollEvent')<sup>12+</sup> 2863 2864on(type: 'scrollEvent', options: observer.ObserverOptions, callback: Callback\<observer.ScrollEventInfo\>): void 2865 2866Subscribes to the start and end of a scroll event. 2867 2868**Atomic service API**: This API can be used in atomic services since API version 12. 2869 2870**System capability**: SystemCapability.ArkUI.ArkUI.Full 2871 2872**Parameters** 2873 2874| Name | Type | Mandatory| Description | 2875| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2876| type | string | Yes | Event type. The value **'scrollEvent'** indicates the start and end of a scroll event.| 2877| options | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | Yes | Observer options, including the ID of the target scrollable component. | 2878| 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. | 2879 2880**Example** 2881 2882See [offscrollevent Example](#offscrollevent12-1). 2883 2884### off('scrollEvent')<sup>12+</sup> 2885 2886off(type: 'scrollEvent', options: observer.ObserverOptions, callback?: Callback\<observer.ScrollEventInfo\>): void 2887 2888Unsubscribes from the start and end of a scroll event. 2889 2890**Atomic service API**: This API can be used in atomic services since API version 12. 2891 2892**System capability**: SystemCapability.ArkUI.ArkUI.Full 2893 2894**Parameters** 2895 2896| Name | Type | Mandatory| Description | 2897| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2898| type | string | Yes | Event type. The value **'scrollEvent'** indicates the start and end of a scroll event.| 2899| options | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | Yes | Observer options, including the ID of the target scrollable component. | 2900| 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. | 2901 2902**Example** 2903 2904```ts 2905import { UIObserver } from '@kit.ArkUI' 2906 2907@Entry 2908@Component 2909struct Index { 2910 scroller: Scroller = new Scroller() 2911 observer: UIObserver = new UIObserver() 2912 private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7] 2913 2914 build() { 2915 Row() { 2916 Column() { 2917 Scroll(this.scroller) { 2918 Column() { 2919 ForEach(this.arr, (item: number) => { 2920 Text(item.toString()) 2921 .width('90%') 2922 .height(150) 2923 .backgroundColor(0xFFFFFF) 2924 .borderRadius(15) 2925 .fontSize(16) 2926 .textAlign(TextAlign.Center) 2927 .margin({ top: 10 }) 2928 }, (item: string) => item) 2929 }.width('100%') 2930 } 2931 .id("testId") 2932 .height('80%') 2933 } 2934 .width('100%') 2935 2936 Row() { 2937 Button('UIObserver on') 2938 .onClick(() => { 2939 this.observer.on('scrollEvent', (info) => { 2940 console.info('scrollEventInfo', JSON.stringify(info)); 2941 }); 2942 }) 2943 Button('UIObserver off') 2944 .onClick(() => { 2945 this.observer.off('scrollEvent'); 2946 }) 2947 } 2948 2949 Row() { 2950 Button('UIObserverWithId on') 2951 .onClick(() => { 2952 this.observer.on('scrollEvent', { id:"testId" }, (info) => { 2953 console.info('scrollEventInfo', JSON.stringify(info)); 2954 }); 2955 }) 2956 Button('UIObserverWithId off') 2957 .onClick(() => { 2958 this.observer.off('scrollEvent', { id:"testId" }); 2959 }) 2960 } 2961 } 2962 .height('100%') 2963 } 2964} 2965``` 2966 2967### on('routerPageUpdate')<sup>11+</sup> 2968 2969on(type: 'routerPageUpdate', callback: Callback\<observer.RouterPageInfo\>): void 2970 2971Subscribes to state changes of the page in the router. 2972 2973**Atomic service API**: This API can be used in atomic services since API version 12. 2974 2975**System capability**: SystemCapability.ArkUI.ArkUI.Full 2976 2977**Parameters** 2978 2979| Name | Type | Mandatory| Description | 2980| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2981| type | string | Yes | Event type. The value is fixed at **'routerPageUpdate'**, which indicates the state change event of the page in the router.| 2982| 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. | 2983 2984**Example** 2985 2986```ts 2987import { UIContext, UIObserver } from '@kit.ArkUI'; 2988 2989let observer:UIObserver = this.getUIContext().getUIObserver(); 2990observer.on('routerPageUpdate', (info) => { 2991 console.info('RouterPage state updated, called by ' + `${info.name}`); 2992}); 2993``` 2994 2995### off('routerPageUpdate')<sup>11+</sup> 2996 2997off(type: 'routerPageUpdate', callback?: Callback\<observer.RouterPageInfo\>): void 2998 2999Unsubscribes to state changes of the page in the router. 3000 3001**Atomic service API**: This API can be used in atomic services since API version 12. 3002 3003**System capability**: SystemCapability.ArkUI.ArkUI.Full 3004 3005**Parameters** 3006 3007| Name | Type | Mandatory| Description | 3008| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3009| type | string | Yes | Event type. The value is fixed at **'routerPageUpdate'**, which indicates the state change event of the page in the router.| 3010| callback | Callback\<observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo)\> | No | Callback to be unregistered. | 3011 3012**Example** 3013 3014```ts 3015import { UIContext, UIObserver } from '@kit.ArkUI'; 3016 3017let observer:UIObserver = this.getUIContext().getUIObserver(); 3018function callBackFunc(info:observer.RouterPageInfo) {}; 3019// callBackFunc is defined and used before 3020observer.off('routerPageUpdate', callBackFunc); 3021``` 3022 3023### on('densityUpdate')<sup>12+</sup> 3024 3025on(type: 'densityUpdate', callback: Callback\<observer.DensityInfo\>): void 3026 3027Subscribes to the pixel density changes of the screen. 3028 3029**Atomic service API**: This API can be used in atomic services since API version 12. 3030 3031**System capability**: SystemCapability.ArkUI.ArkUI.Full 3032 3033**Parameters** 3034 3035| Name | Type | Mandatory| Description | 3036| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3037| type | string | Yes | Event type. The value **'densityUpdate'** indicates the pixel density changes of the screen.| 3038| callback | Callback\<observer.[DensityInfo](./js-apis-arkui-observer.md#densityinfo12)\> | Yes | Callback used to return the screen pixel density after the change. | 3039 3040```ts 3041import { uiObserver } from '@kit.ArkUI'; 3042 3043@Entry 3044@Component 3045struct Index { 3046 @State density: number = 0; 3047 @State message: string = 'No listener registered' 3048 3049 densityUpdateCallback = (info: uiObserver.DensityInfo) => { 3050 this.density = info.density; 3051 this.message = 'DPI after change:' + this.density.toString(); 3052 } 3053 3054 build() { 3055 Column() { 3056 Text(this.message) 3057 .fontSize(24) 3058 .fontWeight(FontWeight.Bold) 3059 Button('Subscribe to Screen Pixel Density Changes') 3060 .onClick(() => { 3061 this.message = 'Listener registered' 3062 this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback); 3063 }) 3064 } 3065 } 3066} 3067``` 3068 3069### off('densityUpdate')<sup>12+</sup> 3070 3071off(type: 'densityUpdate', callback?: Callback\<observer.DensityInfo\>): void 3072 3073Unsubscribes from the pixel density changes of the screen. 3074 3075**Atomic service API**: This API can be used in atomic services since API version 12. 3076 3077**System capability**: SystemCapability.ArkUI.ArkUI.Full 3078 3079**Parameters** 3080 3081| Name | Type | Mandatory| Description | 3082| -------- | -------------------------------------------------------------------- | ---- | -------------------------------------------------------------------------------------------- | 3083| type | string | Yes | Event type. The value **'densityUpdate'** indicates the pixel density changes of the screen. | 3084| 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.| 3085 3086```ts 3087import { uiObserver } from '@kit.ArkUI'; 3088 3089@Entry 3090@Component 3091struct Index { 3092 @State density: number = 0; 3093 @State message: string = 'No listener registered' 3094 3095 densityUpdateCallback = (info: uiObserver.DensityInfo) => { 3096 this.density = info.density; 3097 this.message = 'DPI after change:' + this.density.toString(); 3098 } 3099 3100 build() { 3101 Column() { 3102 Text(this.message) 3103 .fontSize(24) 3104 .fontWeight(FontWeight.Bold) 3105 Button('Subscribe to Screen Pixel Density Changes') 3106 .margin({ bottom: 10 }) 3107 .onClick(() => { 3108 this.message = 'Listener registered' 3109 this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback); 3110 }) 3111 Button('Unsubscribe from Screen Pixel Density Changes') 3112 .onClick(() => { 3113 this.message = 'Listener not registered' 3114 this.getUIContext().getUIObserver().off('densityUpdate', this.densityUpdateCallback); 3115 }) 3116 } 3117 } 3118} 3119``` 3120 3121### on('willDraw')<sup>12+</sup> 3122 3123on(type: 'willDraw', callback: Callback\<void\>): void 3124 3125Subscribes to the dispatch of drawing instructions in each frame. 3126 3127**Atomic service API**: This API can be used in atomic services since API version 12. 3128 3129**System capability**: SystemCapability.ArkUI.ArkUI.Full 3130 3131**Parameters** 3132 3133| Name | Type | Mandatory| Description | 3134| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3135| type | string | Yes | Event event. The value **'willDraw'** indicates whether drawing is about to occur.| 3136| callback | Callback\<void\> | Yes | Callback used to return the result. | 3137 3138```ts 3139import { uiObserver } from '@kit.ArkUI'; 3140 3141@Entry 3142@Component 3143struct Index { 3144 willDrawCallback = () => { 3145 console.info("willDraw instruction dispatched.") 3146 } 3147 build() { 3148 Column() { 3149 Button('Subscribe to Drawing Instruction Dispatch') 3150 .onClick(() => { 3151 this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback); 3152 }) 3153 } 3154 } 3155} 3156``` 3157 3158### off('willDraw')<sup>12+</sup> 3159 3160off(type: 'willDraw', callback?: Callback\<void\>): void 3161 3162Unsubscribes from the dispatch of drawing instructions in each frame. 3163 3164**Atomic service API**: This API can be used in atomic services since API version 12. 3165 3166**System capability**: SystemCapability.ArkUI.ArkUI.Full 3167 3168**Parameters** 3169 3170| Name | Type | Mandatory| Description | 3171| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3172| type | string | Yes | Event event. The value **'willDraw'** indicates whether drawing is about to occur.| 3173| callback | Callback\<void\> | No | Callback to be unregistered. | 3174 3175```ts 3176import { uiObserver } from '@kit.ArkUI'; 3177 3178@Entry 3179@Component 3180struct Index { 3181 willDrawCallback = () => { 3182 console.info("willDraw instruction dispatched.") 3183 } 3184 3185 build() { 3186 Column() { 3187 Button('Subscribe to Drawing Instruction Dispatch') 3188 .margin({ bottom: 10 }) 3189 .onClick(() => { 3190 this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback); 3191 }) 3192 Button('Unsubscribe from Drawing Instruction Dispatch') 3193 .onClick(() => { 3194 this.getUIContext().getUIObserver().off('willDraw', this.willDrawCallback); 3195 }) 3196 } 3197 } 3198} 3199``` 3200 3201### on('didLayout')<sup>12+</sup> 3202 3203on(type: 'didLayout', callback: Callback\<void\>): void 3204 3205Subscribes to layout completion status in each frame. 3206 3207**Atomic service API**: This API can be used in atomic services since API version 12. 3208 3209**System capability**: SystemCapability.ArkUI.ArkUI.Full 3210 3211**Parameters** 3212 3213| Name | Type | Mandatory| Description | 3214| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3215| type | string | Yes | Event type. The value **'didLayout'** indicates whether the layout has been completed.| 3216| callback | Callback\<void\> | Yes | Callback used to return the result. | 3217 3218```ts 3219import { uiObserver } from '@kit.ArkUI'; 3220 3221@Entry 3222@Component 3223struct Index { 3224 didLayoutCallback = () => { 3225 console.info("Layout completed."); 3226 } 3227 build() { 3228 Column() { 3229 Button('Subscribe to Layout Completion') 3230 .onClick(() => { 3231 this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback); 3232 }) 3233 } 3234 } 3235} 3236``` 3237 3238### off('didLayout')<sup>12+</sup> 3239 3240off(type: 'didLayout', callback?: Callback\<void\>): void 3241 3242Unsubscribes from layout completion status in each frame. 3243 3244**Atomic service API**: This API can be used in atomic services since API version 12. 3245 3246**System capability**: SystemCapability.ArkUI.ArkUI.Full 3247 3248**Parameters** 3249 3250| Name | Type | Mandatory| Description | 3251| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3252| type | string | Yes | Event event. The value **'didLayout'** indicates whether the layout has been completed.| 3253| callback | Callback\<void\> | No | Callback to be unregistered. | 3254 3255```ts 3256import { uiObserver } from '@kit.ArkUI'; 3257 3258@Entry 3259@Component 3260struct Index { 3261 didLayoutCallback = () => { 3262 console.info("Layout completed.") 3263 } 3264 3265 build() { 3266 Column() { 3267 Button('Subscribe to Layout Completion') 3268 .margin({ bottom: 10 }) 3269 .onClick(() => { 3270 this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback); 3271 }) 3272 Button('Unsubscribe from Layout Completion') 3273 .onClick(() => { 3274 this.getUIContext().getUIObserver().off('didLayout', this.didLayoutCallback); 3275 }) 3276 } 3277 } 3278} 3279``` 3280 3281### on('navDestinationSwitch')<sup>12+</sup> 3282 3283on(type: 'navDestinationSwitch', callback: Callback\<observer.NavDestinationSwitchInfo\>): void 3284 3285Subscribes to the page switching event of the **Navigation** component. 3286 3287**Atomic service API**: This API can be used in atomic services since API version 12. 3288 3289**System capability**: SystemCapability.ArkUI.ArkUI.Full 3290 3291**Parameters** 3292 3293| Name | Type | Mandatory| Description | 3294| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3295| type | string | Yes | Event type. The value **'navDestinationSwitch'** indicates the page switching event of the **Navigation** component.| 3296| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\> | Yes | Callback used to return the information about the page switching event. | 3297 3298**Example** 3299 3300```ts 3301// Index.ets 3302// UIObserver.on('navDestinationSwitch', callback) demo 3303// UIObserver.off('navDestinationSwitch', callback) 3304import { uiObserver } from '@kit.ArkUI'; 3305 3306@Component 3307struct PageOne { 3308 build() { 3309 NavDestination() { 3310 Text("pageOne") 3311 }.title("pageOne") 3312 } 3313} 3314 3315function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) { 3316 console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`) 3317} 3318 3319@Entry 3320@Component 3321struct Index { 3322 private stack: NavPathStack = new NavPathStack(); 3323 3324 @Builder 3325 PageBuilder(name: string) { 3326 PageOne() 3327 } 3328 3329 aboutToAppear() { 3330 let obs = this.getUIContext().getUIObserver(); 3331 obs.on('navDestinationSwitch', callBackFunc); 3332 } 3333 3334 aboutToDisappear() { 3335 let obs = this.getUIContext().getUIObserver(); 3336 obs.off('navDestinationSwitch', callBackFunc); 3337 } 3338 3339 build() { 3340 Column() { 3341 Navigation(this.stack) { 3342 Button("push").onClick(() => { 3343 this.stack.pushPath({name: "pageOne"}); 3344 }) 3345 } 3346 .title("Navigation") 3347 .navDestination(this.PageBuilder) 3348 } 3349 .width('100%') 3350 .height('100%') 3351 } 3352} 3353``` 3354 3355### off('navDestinationSwitch')<sup>12+</sup> 3356 3357off(type: 'navDestinationSwitch', callback?: Callback\<observer.NavDestinationSwitchInfo\>): void 3358 3359Unsubscribes from the page switching event of the **Navigation** component. 3360 3361**Atomic service API**: This API can be used in atomic services since API version 12. 3362 3363**System capability**: SystemCapability.ArkUI.ArkUI.Full 3364 3365**Parameters** 3366 3367| Name | Type | Mandatory| Description | 3368| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3369| type | string | Yes | Event type. The value **'navDestinationSwitch'** indicates the page switching event of the **Navigation** component.| 3370| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\> | No | Callback to be unregistered. | 3371 3372For the sample code, see the sample code of the **UIObserver.on('navDestinationSwitch')** API. 3373 3374### on('navDestinationSwitch')<sup>12+</sup> 3375 3376on(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback: Callback\<observer.NavDestinationSwitchInfo\>): void 3377 3378Subscribes to the page switching event of the **Navigation** component. 3379 3380**Atomic service API**: This API can be used in atomic services since API version 12. 3381 3382**System capability**: SystemCapability.ArkUI.ArkUI.Full 3383 3384**Parameters** 3385 3386| Name | Type | Mandatory| Description | 3387| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3388| type | string | Yes | Event type. The value **'navDestinationSwitch'** indicates the page switching event of the **Navigation** component.| 3389| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12) | Yes | Observer options. | 3390| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\> | Yes | Callback used to return the information about the page switching event. | 3391 3392**Example** 3393 3394```ts 3395// Index.ets 3396// Demo UIObserver.on('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback) 3397// UIObserver.off('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback) 3398import { uiObserver } from '@kit.ArkUI'; 3399 3400@Component 3401struct PageOne { 3402 build() { 3403 NavDestination() { 3404 Text("pageOne") 3405 }.title("pageOne") 3406 } 3407} 3408 3409function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) { 3410 console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`) 3411} 3412 3413@Entry 3414@Component 3415struct Index { 3416 private stack: NavPathStack = new NavPathStack(); 3417 3418 @Builder 3419 PageBuilder(name: string) { 3420 PageOne() 3421 } 3422 3423 aboutToAppear() { 3424 let obs = this.getUIContext().getUIObserver(); 3425 obs.on('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc) 3426 } 3427 3428 aboutToDisappear() { 3429 let obs = this.getUIContext().getUIObserver(); 3430 obs.off('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc) 3431 } 3432 3433 build() { 3434 Column() { 3435 Navigation(this.stack) { 3436 Button("push").onClick(() => { 3437 this.stack.pushPath({name: "pageOne"}); 3438 }) 3439 } 3440 .id("myNavId") 3441 .title("Navigation") 3442 .navDestination(this.PageBuilder) 3443 } 3444 .width('100%') 3445 .height('100%') 3446 } 3447} 3448``` 3449 3450### off('navDestinationSwitch')<sup>12+</sup> 3451 3452off(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback?: Callback\<observer.NavDestinationSwitchInfo\>): void 3453 3454Unsubscribes from the page switching event of the **Navigation** component. 3455 3456**Atomic service API**: This API can be used in atomic services since API version 12. 3457 3458**System capability**: SystemCapability.ArkUI.ArkUI.Full 3459 3460**Parameters** 3461 3462| Name | Type | Mandatory| Description | 3463| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3464| type | string | Yes | Event type. The value **'navDestinationSwitch'** indicates the page switching event of the **Navigation** component.| 3465| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12) | Yes | Observer options. | 3466| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\> | No | Callback to be unregistered. | 3467 3468For the sample code, see the sample code of the **UIObserver.on('navDestinationSwitch')** API. 3469 3470### on('willClick')<sup>12+</sup> 3471 3472on(type: 'willClick', callback: GestureEventListenerCallback): void 3473 3474Subscribes to the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported. 3475 3476**Atomic service API**: This API can be used in atomic services since API version 12. 3477 3478**System capability**: SystemCapability.ArkUI.ArkUI.Full 3479 3480**Parameters** 3481 3482| Name | Type | Mandatory| Description | 3483| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3484| 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.| 3485| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | Yes | Callback used to return the **GestureEvent** object of the click event and the FrameNode of the component. | 3486 3487**Example** 3488 3489```ts 3490// Used in page components. 3491import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3492 3493// callback is a callback defined by you. 3494let callback = (event: GestureEvent, frameNode?: FrameNode) => {}; 3495let observer: UIObserver = this.getUIContext().getUIObserver(); 3496observer.on('willClick', callback); 3497``` 3498 3499### off('willClick')<sup>12+</sup> 3500 3501off(type: 'willClick', callback?: GestureEventListenerCallback): void 3502 3503Unsubscribes from the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported. 3504 3505**Atomic service API**: This API can be used in atomic services since API version 12. 3506 3507**System capability**: SystemCapability.ArkUI.ArkUI.Full 3508 3509**Parameters** 3510 3511| Name | Type | Mandatory| Description | 3512| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | 3513| type | string | Yes | Event type. The value **'willClick'** indicates the dispatch of click event instructions.| 3514| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | No | Callback to be unregistered. | 3515 3516**Example** 3517 3518```ts 3519// Used in page components. 3520import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3521 3522// callback is a callback defined by you. 3523let callback = (event: GestureEvent, frameNode?: FrameNode) => {}; 3524let observer: UIObserver = this.getUIContext().getUIObserver(); 3525observer.off('willClick', callback); 3526``` 3527 3528### on('didClick')<sup>12+</sup> 3529 3530on(type: 'didClick', callback: GestureEventListenerCallback): void 3531 3532Subscribes to the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported. 3533 3534**Atomic service API**: This API can be used in atomic services since API version 12. 3535 3536**System capability**: SystemCapability.ArkUI.ArkUI.Full 3537 3538**Parameters** 3539 3540| Name | Type | Mandatory| Description | 3541| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3542| 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.| 3543| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | Yes | Callback used to return the **GestureEvent** object of the click event and the FrameNode of the component. | 3544 3545**Example** 3546 3547```ts 3548// Used in page components. 3549import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3550 3551// callback is a callback defined by you. 3552let callback = (event: GestureEvent, frameNode?: FrameNode) => {}; 3553let observer: UIObserver = this.getUIContext().getUIObserver(); 3554observer.on('didClick', callback); 3555``` 3556 3557### off('didClick')<sup>12+</sup> 3558 3559off(type: 'didClick', callback?: GestureEventListenerCallback): void 3560 3561Unsubscribes from the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported. 3562 3563**Atomic service API**: This API can be used in atomic services since API version 12. 3564 3565**System capability**: SystemCapability.ArkUI.ArkUI.Full 3566 3567**Parameters** 3568 3569| Name | Type | Mandatory| Description | 3570| -------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------- | 3571| type | string | Yes | Event type. The value **'didClick'** indicates the dispatch of click event instructions.| 3572| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | No | Callback to be unregistered. | 3573 3574**Example** 3575 3576```ts 3577// Used in page components. 3578import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3579 3580// callback is a callback defined by you. 3581let callback = (event: GestureEvent, frameNode?: FrameNode) => {}; 3582let observer: UIObserver = this.getUIContext().getUIObserver(); 3583observer.off('didClick', callback); 3584``` 3585 3586### on('willClick')<sup>12+</sup> 3587 3588on(type: 'willClick', callback: ClickEventListenerCallback): void 3589 3590Subscribes to the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported. 3591 3592**Atomic service API**: This API can be used in atomic services since API version 12. 3593 3594**System capability**: SystemCapability.ArkUI.ArkUI.Full 3595 3596**Parameters** 3597 3598| Name | Type | Mandatory| Description | 3599| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | 3600| 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.| 3601| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | Yes | Callback used to return the **ClickEvent** object and the FrameNode of the component. | 3602 3603**Example** 3604 3605```ts 3606// Used in page components. 3607import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3608 3609// callback is a callback defined by you. 3610let callback = (event: ClickEvent, frameNode?: FrameNode) => {}; 3611let observer: UIObserver = this.getUIContext().getUIObserver(); 3612observer.on('willClick', callback); 3613``` 3614 3615### off('willClick')<sup>12+</sup> 3616 3617off(type: 'willClick', callback?: ClickEventListenerCallback): void 3618 3619Unsubscribes from the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported. 3620 3621**Atomic service API**: This API can be used in atomic services since API version 12. 3622 3623**System capability**: SystemCapability.ArkUI.ArkUI.Full 3624 3625**Parameters** 3626 3627| Name | Type | Mandatory| Description | 3628| -------- | ----------------------------------------------------------- | ---- | ----------------------------------------------------- | 3629| type | string | Yes | Event type. The value **'willClick'** indicates the dispatch of click event instructions.| 3630| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | No | Callback to be unregistered. | 3631 3632**Example** 3633 3634```ts 3635// Used in page components. 3636import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3637 3638// callback is a callback defined by you. 3639let callback = (event: ClickEvent, frameNode?: FrameNode) => {}; 3640let observer: UIObserver = this.getUIContext().getUIObserver(); 3641observer.off('willClick', callback); 3642``` 3643 3644### on('didClick')<sup>12+</sup> 3645 3646on(type: 'didClick', callback: ClickEventListenerCallback): void 3647 3648Subscribes to the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported. 3649 3650**Atomic service API**: This API can be used in atomic services since API version 12. 3651 3652**System capability**: SystemCapability.ArkUI.ArkUI.Full 3653 3654**Parameters** 3655 3656| Name | Type | Mandatory| Description | 3657| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | 3658| 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.| 3659| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | Yes | Callback used to return the **ClickEvent** object and the FrameNode of the component. | 3660 3661**Example** 3662 3663```ts 3664// Used in page components. 3665import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3666 3667// callback is a callback defined by you. 3668let callback = (event: ClickEvent, frameNode?: FrameNode) => {}; 3669let observer: UIObserver = this.getUIContext().getUIObserver(); 3670observer.on('didClick', callback); 3671``` 3672 3673### off('didClick')<sup>12+</sup> 3674 3675off(type: 'didClick', callback?: ClickEventListenerCallback): void 3676 3677Unsubscribes from the dispatch of click event instructions. Currently, the screen reader touch exploration mode is not supported. 3678 3679**Atomic service API**: This API can be used in atomic services since API version 12. 3680 3681**System capability**: SystemCapability.ArkUI.ArkUI.Full 3682 3683**Parameters** 3684 3685| Name | Type | Mandatory| Description | 3686| -------- | ----------------------------------------------------------- | ---- | ---------------------------------------------------- | 3687| type | string | Yes | Event type. The value **'didClick'** indicates the dispatch of click event instructions.| 3688| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | No | Callback to be unregistered. | 3689 3690**Example** 3691 3692```ts 3693// Used in page components. 3694import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3695 3696// callback is a callback defined by you. 3697let callback = (event: ClickEvent, frameNode?: FrameNode) => {}; 3698let observer: UIObserver = this.getUIContext().getUIObserver(); 3699observer.off('didClick', callback); 3700``` 3701 3702### on('tabContentUpdate')<sup>12+</sup> 3703 3704on(type: 'tabContentUpdate', callback: Callback\<observer.TabContentInfo\>): void 3705 3706Subscribes to the **TabContent** switching event. 3707 3708**Atomic service API**: This API can be used in atomic services since API version 12. 3709 3710**System capability**: SystemCapability.ArkUI.ArkUI.Full 3711 3712**Parameters** 3713 3714| Name | Type | Mandatory| Description | 3715| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3716| type | string | Yes | Event type. The value **'tabContentUpdate'** indicates the **TabContent** switching event.| 3717| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | Yes | Callback used to return the information about the **TabContent** switching event.| 3718 3719**Example** 3720 3721```ts 3722import { uiObserver } from '@kit.ArkUI'; 3723 3724function callbackFunc(info: uiObserver.TabContentInfo) { 3725 console.info('tabContentUpdate', JSON.stringify(info)); 3726} 3727 3728@Entry 3729@Component 3730struct TabsExample { 3731 3732 aboutToAppear(): void { 3733 let observer = this.getUIContext().getUIObserver(); 3734 observer.on('tabContentUpdate', callbackFunc); 3735 } 3736 3737 aboutToDisappear(): void { 3738 let observer = this.getUIContext().getUIObserver(); 3739 observer.off('tabContentUpdate', callbackFunc); 3740 } 3741 3742 build() { 3743 Column() { 3744 Tabs() { 3745 TabContent() { 3746 Column().width('100%').height('100%').backgroundColor('#00CB87') 3747 }.tabBar('green').id('tabContentId0') 3748 3749 TabContent() { 3750 Column().width('100%').height('100%').backgroundColor('#007DFF') 3751 }.tabBar('blue').id('tabContentId1') 3752 3753 TabContent() { 3754 Column().width('100%').height('100%').backgroundColor('#FFBF00') 3755 }.tabBar('yellow').id('tabContentId2') 3756 3757 TabContent() { 3758 Column().width('100%').height('100%').backgroundColor('#E67C92') 3759 }.tabBar('pink').id('tabContentId3') 3760 } 3761 .width(360) 3762 .height(296) 3763 .backgroundColor('#F1F3F5') 3764 .id('tabsId') 3765 }.width('100%') 3766 } 3767} 3768``` 3769 3770### off('tabContentUpdate')<sup>12+</sup> 3771 3772off(type: 'tabContentUpdate', callback?: Callback\<observer.TabContentInfo\>): void 3773 3774Unsubscribes from the **TabContent** switching event. 3775 3776**Atomic service API**: This API can be used in atomic services since API version 12. 3777 3778**System capability**: SystemCapability.ArkUI.ArkUI.Full 3779 3780**Parameters** 3781 3782| Name | Type | Mandatory| Description | 3783| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3784| type | string | Yes | Event type. The value **'tabContentUpdate'** indicates the **TabContent** switching event.| 3785| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | No | Callback to be unregistered.| 3786 3787**Example** 3788 3789See the example of [on('tabContentUpdate')](#ontabcontentupdate12). 3790 3791### on('tabContentUpdate')<sup>12+</sup> 3792 3793on(type: 'tabContentUpdate', options: observer.ObserverOptions, callback: Callback\<observer.TabContentInfo\>): void 3794 3795Subscribes to the **TabContent** switching event. 3796 3797**Atomic service API**: This API can be used in atomic services since API version 12. 3798 3799**System capability**: SystemCapability.ArkUI.ArkUI.Full 3800 3801**Parameters** 3802 3803| Name | Type | Mandatory| Description | 3804| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3805| type | string | Yes | Event type. The value **'tabContentUpdate'** indicates the **TabContent** switching event.| 3806| options | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | Yes | ID of the target **Tabs** component.| 3807| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | Yes | Callback used to return the information about the **TabContent** switching event.| 3808 3809**Example** 3810 3811```ts 3812import { uiObserver } from '@kit.ArkUI'; 3813 3814function callbackFunc(info: uiObserver.TabContentInfo) { 3815 console.info('tabContentUpdate', JSON.stringify(info)); 3816} 3817 3818@Entry 3819@Component 3820struct TabsExample { 3821 3822 aboutToAppear(): void { 3823 let observer = this.getUIContext().getUIObserver(); 3824 observer.on('tabContentUpdate', { id: 'tabsId' }, callbackFunc); 3825 } 3826 3827 aboutToDisappear(): void { 3828 let observer = this.getUIContext().getUIObserver(); 3829 observer.off('tabContentUpdate', { id: 'tabsId' }, callbackFunc); 3830 } 3831 3832 build() { 3833 Column() { 3834 Tabs() { 3835 TabContent() { 3836 Column().width('100%').height('100%').backgroundColor('#00CB87') 3837 }.tabBar('green').id('tabContentId0') 3838 3839 TabContent() { 3840 Column().width('100%').height('100%').backgroundColor('#007DFF') 3841 }.tabBar('blue').id('tabContentId1') 3842 3843 TabContent() { 3844 Column().width('100%').height('100%').backgroundColor('#FFBF00') 3845 }.tabBar('yellow').id('tabContentId2') 3846 3847 TabContent() { 3848 Column().width('100%').height('100%').backgroundColor('#E67C92') 3849 }.tabBar('pink').id('tabContentId3') 3850 } 3851 .width(360) 3852 .height(296) 3853 .backgroundColor('#F1F3F5') 3854 .id('tabsId') 3855 }.width('100%') 3856 } 3857} 3858``` 3859 3860### off('tabContentUpdate')<sup>12+</sup> 3861 3862off(type: 'tabContentUpdate', options: observer.ObserverOptions, callback?: Callback\<observer.TabContentInfo\>): void 3863 3864Unsubscribes from the **TabContent** switching event. 3865 3866**Atomic service API**: This API can be used in atomic services since API version 12. 3867 3868**System capability**: SystemCapability.ArkUI.ArkUI.Full 3869 3870**Parameters** 3871 3872| Name | Type | Mandatory| Description | 3873| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3874| type | string | Yes | Event type. The value **'tabContentUpdate'** indicates the **TabContent** switching event.| 3875| options | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | Yes | ID of the target **Tabs** component.| 3876| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | No | Callback to be unregistered.| 3877 3878**Example** 3879 3880See the example of [on('tabContentUpdate')](#ontabcontentupdate12-1). 3881 3882## GestureEventListenerCallback<sup>12+</sup> 3883type GestureEventListenerCallback = (event: GestureEvent, node?: FrameNode) => void 3884 3885Implements a callback for the ArkTS gesture event. 3886 3887**Atomic service API**: This API can be used in atomic services since API version 12. 3888 3889**System capability**: SystemCapability.ArkUI.ArkUI.Full 3890 3891**Parameters** 3892 3893| Name | Type | Mandatory| Description | 3894| ------- | ------ | ---- | --------------------------- | 3895| event | [GestureEvent](../apis-arkui/arkui-ts/ts-gesture-settings.md#gestureevent)| Yes| Information about the subscribed-to gesture event.| 3896| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | No| Component bound to the subscribed-to gesture event.| 3897 3898## ClickEventListenerCallback<sup>12+</sup> 3899type ClickEventListenerCallback = (event: ClickEvent, node?: FrameNode) => void 3900 3901Implements a callback for the ArkTS gesture event. 3902 3903**Atomic service API**: This API can be used in atomic services since API version 12. 3904 3905**System capability**: SystemCapability.ArkUI.ArkUI.Full 3906 3907**Parameters** 3908 3909| Name | Type | Mandatory| Description | 3910| ------- | ------ | ---- | --------------------------- | 3911| event | [ClickEvent](../apis-arkui/arkui-ts/ts-universal-events-click.md#clickevent)| Yes| Information about the subscribed-to click event.| 3912| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | No| Component bound to the subscribed-to click event.| 3913 3914## MediaQuery 3915 3916In 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. 3917 3918### matchMediaSync 3919 3920matchMediaSync(condition: string): mediaQuery.MediaQueryListener 3921 3922Sets the media query criteria and returns the corresponding listening handle. 3923 3924**Atomic service API**: This API can be used in atomic services since API version 11. 3925 3926**System capability**: SystemCapability.ArkUI.ArkUI.Full 3927 3928**Parameters** 3929 3930| Name | Type | Mandatory | Description | 3931| --------- | ------ | ---- | ---------------------------------------- | 3932| condition | string | Yes | Media query condition. For details, see [Syntax](../../ui/arkts-layout-development-media-query.md#syntax).| 3933 3934**Return value** 3935 3936| Type | Description | 3937| ------------------------------------------------------------ | -------------------------------------------- | 3938| [mediaQuery.MediaQueryListener](js-apis-mediaquery.md#mediaquerylistener) | Listening handle to a media event, which is used to register or unregister the listening callback.| 3939 3940**Example** 3941 3942```ts 3943import { MediaQuery } from '@kit.ArkUI'; 3944 3945let mediaquery: MediaQuery = uiContext.getMediaQuery(); 3946let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. 3947``` 3948 3949## Router 3950 3951In 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. 3952 3953### pushUrl 3954 3955pushUrl(options: router.RouterOptions): Promise<void> 3956 3957Navigates to a specified page in the application. This API uses a promise to return the result. 3958 3959**Atomic service API**: This API can be used in atomic services since API version 11. 3960 3961**System capability**: SystemCapability.ArkUI.ArkUI.Full 3962 3963**Parameters** 3964 3965| Name | Type | Mandatory | Description | 3966| ------- | ---------------------------------------- | ---- | --------- | 3967| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters.| 3968 3969**Return value** 3970 3971| Type | Description | 3972| ------------------- | ------- | 3973| Promise<void> | Promise used to return the result.| 3974 3975**Error codes** 3976 3977For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 3978 3979| ID | Error Message | 3980| ------ | ---------------------------------- | 3981| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 3982| 100001 | Internal error. | 3983| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. | 3984| 100003 | Page stack error. Too many pages are pushed. | 3985 3986**Example** 3987 3988```ts 3989import { BusinessError } from '@kit.BasicServicesKit' 3990 3991@Entry 3992@Component 3993struct Index { 3994 async routePage() { 3995 this.getUIContext().getRouter().pushUrl({ 3996 url: 'pages/routerpage2', 3997 params: { 3998 data1: 'message', 3999 data2: { 4000 data3: [123, 456, 789] 4001 } 4002 } 4003 }) 4004 .then(() => { 4005 console.info('succeeded') 4006 }) 4007 .catch((error: BusinessError) => { 4008 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4009 }) 4010 } 4011 4012 build() { 4013 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4014 Button() { 4015 Text('next page') 4016 .fontSize(25) 4017 .fontWeight(FontWeight.Bold) 4018 }.type(ButtonType.Capsule) 4019 .margin({ top: 20 }) 4020 .backgroundColor('#ccc') 4021 .onClick(() => { 4022 this.routePage() 4023 }) 4024 } 4025 .width('100%') 4026 .height('100%') 4027 } 4028} 4029``` 4030 4031### pushUrl 4032 4033pushUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void 4034 4035Navigates to a specified page in the application. 4036 4037**Atomic service API**: This API can be used in atomic services since API version 11. 4038 4039**System capability**: SystemCapability.ArkUI.ArkUI.Full 4040 4041**Parameters** 4042 4043| Name | Type | Mandatory | Description | 4044| -------- | ---------------------------------------- | ---- | --------- | 4045| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters.| 4046| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 4047 4048**Error codes** 4049 4050For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4051 4052| ID | Error Message | 4053| ------ | ---------------------------------- | 4054| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4055| 100001 | Internal error. | 4056| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. | 4057| 100003 | Page stack error. Too many pages are pushed. | 4058 4059**Example** 4060 4061```ts 4062import { BusinessError } from '@kit.BasicServicesKit' 4063 4064@Entry 4065@Component 4066struct Index { 4067 async routePage() { 4068 this.getUIContext().getRouter().pushUrl({ 4069 url: 'pages/routerpage2', 4070 params: { 4071 data1: 'message', 4072 data2: { 4073 data3: [123, 456, 789] 4074 } 4075 } 4076 }, (err: Error) => { 4077 if (err) { 4078 let message = (err as BusinessError).message; 4079 let code = (err as BusinessError).code; 4080 console.error(`pushUrl failed, code is ${code}, message is ${message}`); 4081 return; 4082 } 4083 console.info('pushUrl success'); 4084 }) 4085 } 4086 4087 build() { 4088 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4089 Button() { 4090 Text('next page') 4091 .fontSize(25) 4092 .fontWeight(FontWeight.Bold) 4093 }.type(ButtonType.Capsule) 4094 .margin({ top: 20 }) 4095 .backgroundColor('#ccc') 4096 .onClick(() => { 4097 this.routePage() 4098 }) 4099 } 4100 .width('100%') 4101 .height('100%') 4102 } 4103} 4104``` 4105 4106### pushUrl 4107 4108pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void> 4109 4110Navigates to a specified page in the application. This API uses a promise to return the result. 4111 4112**Atomic service API**: This API can be used in atomic services since API version 11. 4113 4114**System capability**: SystemCapability.ArkUI.ArkUI.Full 4115 4116**Parameters** 4117 4118| Name | Type | Mandatory | Description | 4119| ------- | ---------------------------------------- | ---- | ---------- | 4120| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters. | 4121| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| 4122 4123**Return value** 4124 4125| Type | Description | 4126| ------------------- | ------- | 4127| Promise<void> | Promise used to return the result.| 4128 4129**Error codes** 4130 4131For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4132 4133| ID | Error Message | 4134| ------ | ---------------------------------- | 4135| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4136| 100001 | Internal error. | 4137| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. | 4138| 100003 | Page stack error. Too many pages are pushed. | 4139 4140**Example** 4141 4142```ts 4143import { router } from '@kit.ArkUI'; 4144import { BusinessError } from '@kit.BasicServicesKit' 4145 4146class RouterTmp { 4147 Standard: router.RouterMode = router.RouterMode.Standard 4148} 4149 4150let rtm: RouterTmp = new RouterTmp() 4151 4152@Entry 4153@Component 4154struct Index { 4155 async routePage() { 4156 this.getUIContext().getRouter().pushUrl({ 4157 url: 'pages/routerpage2', 4158 params: { 4159 data1: 'message', 4160 data2: { 4161 data3: [123, 456, 789] 4162 } 4163 } 4164 }, rtm.Standard) 4165 .then(() => { 4166 console.info('succeeded') 4167 }) 4168 .catch((error: BusinessError) => { 4169 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4170 }) 4171 } 4172 4173 build() { 4174 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4175 Button() { 4176 Text('next page') 4177 .fontSize(25) 4178 .fontWeight(FontWeight.Bold) 4179 }.type(ButtonType.Capsule) 4180 .margin({ top: 20 }) 4181 .backgroundColor('#ccc') 4182 .onClick(() => { 4183 this.routePage() 4184 }) 4185 } 4186 .width('100%') 4187 .height('100%') 4188 } 4189} 4190``` 4191 4192### pushUrl 4193 4194pushUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 4195 4196Navigates to a specified page in the application. 4197 4198**Atomic service API**: This API can be used in atomic services since API version 11. 4199 4200**System capability**: SystemCapability.ArkUI.ArkUI.Full 4201 4202**Parameters** 4203 4204| Name | Type | Mandatory | Description | 4205| -------- | ---------------------------------------- | ---- | ---------- | 4206| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Page routing parameters. | 4207| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| 4208| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 4209 4210**Error codes** 4211 4212For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4213 4214| ID | Error Message | 4215| ------ | ---------------------------------- | 4216| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4217| 100001 | Internal error. | 4218| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. | 4219| 100003 | Page stack error. Too many pages are pushed. | 4220 4221**Example** 4222 4223```ts 4224import { router } from '@kit.ArkUI'; 4225import { BusinessError } from '@kit.BasicServicesKit' 4226 4227class RouterTmp { 4228 Standard: router.RouterMode = router.RouterMode.Standard 4229} 4230 4231let rtm: RouterTmp = new RouterTmp() 4232 4233@Entry 4234@Component 4235struct Index { 4236 async routePage() { 4237 this.getUIContext().getRouter().pushUrl({ 4238 url: 'pages/routerpage2', 4239 params: { 4240 data1: 'message', 4241 data2: { 4242 data3: [123, 456, 789] 4243 } 4244 } 4245 }, rtm.Standard, (err) => { 4246 if (err) { 4247 let message = (err as BusinessError).message; 4248 let code = (err as BusinessError).code; 4249 console.error(`pushUrl failed, code is ${code}, message is ${message}`); 4250 return; 4251 } 4252 console.info('pushUrl success'); 4253 }) 4254 } 4255 4256 build() { 4257 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4258 Button() { 4259 Text('next page') 4260 .fontSize(25) 4261 .fontWeight(FontWeight.Bold) 4262 }.type(ButtonType.Capsule) 4263 .margin({ top: 20 }) 4264 .backgroundColor('#ccc') 4265 .onClick(() => { 4266 this.routePage() 4267 }) 4268 } 4269 .width('100%') 4270 .height('100%') 4271 } 4272} 4273``` 4274 4275### replaceUrl 4276 4277replaceUrl(options: router.RouterOptions): Promise<void> 4278 4279Replaces the current page with another one in the application and destroys the current page. This API uses a promise to return the result. 4280 4281**Atomic service API**: This API can be used in atomic services since API version 11. 4282 4283**System capability**: SystemCapability.ArkUI.ArkUI.Full 4284 4285**Parameters** 4286 4287| Name | Type | Mandatory | Description | 4288| ------- | ---------------------------------------- | ---- | --------- | 4289| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page.| 4290 4291**Return value** 4292 4293| Type | Description | 4294| ------------------- | ------- | 4295| Promise<void> | Promise used to return the result.| 4296 4297**Error codes** 4298 4299For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4300 4301| ID | Error Message | 4302| ------ | ---------------------------------------- | 4303| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4304| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 4305| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. | 4306 4307**Example** 4308 4309```ts 4310import { BusinessError } from '@kit.BasicServicesKit' 4311 4312@Entry 4313@Component 4314struct Index { 4315 async routePage() { 4316 this.getUIContext().getRouter().replaceUrl({ 4317 url: 'pages/detail', 4318 params: { 4319 data1: 'message' 4320 } 4321 }) 4322 .then(() => { 4323 console.info('succeeded') 4324 }) 4325 .catch((error: BusinessError) => { 4326 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4327 }) 4328 } 4329 4330 build() { 4331 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4332 Button() { 4333 Text('next page') 4334 .fontSize(25) 4335 .fontWeight(FontWeight.Bold) 4336 }.type(ButtonType.Capsule) 4337 .margin({ top: 20 }) 4338 .backgroundColor('#ccc') 4339 .onClick(() => { 4340 this.routePage() 4341 }) 4342 } 4343 .width('100%') 4344 .height('100%') 4345 } 4346} 4347``` 4348 4349### replaceUrl 4350 4351replaceUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void 4352 4353Replaces the current page with another one in the application and destroys the current page. 4354 4355**Atomic service API**: This API can be used in atomic services since API version 11. 4356 4357**System capability**: SystemCapability.ArkUI.ArkUI.Full 4358 4359**Parameters** 4360 4361| Name | Type | Mandatory | Description | 4362| -------- | ---------------------------------------- | ---- | --------- | 4363| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page.| 4364| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 4365 4366**Error codes** 4367 4368For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4369 4370| ID | Error Message | 4371| ------ | ---------------------------------------- | 4372| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4373| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 4374| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. | 4375 4376**Example** 4377 4378```ts 4379import { BusinessError } from '@kit.BasicServicesKit' 4380 4381@Entry 4382@Component 4383struct Index { 4384 async routePage() { 4385 this.getUIContext().getRouter().replaceUrl({ 4386 url: 'pages/detail', 4387 params: { 4388 data1: 'message' 4389 } 4390 }, (err: Error) => { 4391 if (err) { 4392 let message = (err as BusinessError).message; 4393 let code = (err as BusinessError).code; 4394 console.error(`replaceUrl failed, code is ${code}, message is ${message}`); 4395 return; 4396 } 4397 console.info('replaceUrl success'); 4398 }) 4399 } 4400 4401 build() { 4402 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4403 Button() { 4404 Text('next page') 4405 .fontSize(25) 4406 .fontWeight(FontWeight.Bold) 4407 }.type(ButtonType.Capsule) 4408 .margin({ top: 20 }) 4409 .backgroundColor('#ccc') 4410 .onClick(() => { 4411 this.routePage() 4412 }) 4413 } 4414 .width('100%') 4415 .height('100%') 4416 } 4417} 4418``` 4419 4420### replaceUrl 4421 4422replaceUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void> 4423 4424Replaces the current page with another one in the application and destroys the current page. This API uses a promise to return the result. 4425 4426**Atomic service API**: This API can be used in atomic services since API version 11. 4427 4428**System capability**: SystemCapability.ArkUI.ArkUI.Full 4429 4430**Parameters** 4431 4432| Name | Type | Mandatory | Description | 4433| ------- | ---------------------------------------- | ---- | ---------- | 4434| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page. | 4435| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| 4436 4437**Return value** 4438 4439| Type | Description | 4440| ------------------- | ------- | 4441| Promise<void> | Promise used to return the result.| 4442 4443**Error codes** 4444 4445For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4446 4447| ID | Error Message | 4448| ------ | ---------------------------------------- | 4449| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4450| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. | 4451| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. | 4452 4453**Example** 4454 4455```ts 4456import { router } from '@kit.ArkUI'; 4457import { BusinessError } from '@kit.BasicServicesKit' 4458 4459class RouterTmp { 4460 Standard: router.RouterMode = router.RouterMode.Standard 4461} 4462 4463let rtm: RouterTmp = new RouterTmp() 4464 4465@Entry 4466@Component 4467struct Index { 4468 async routePage() { 4469 this.getUIContext().getRouter().replaceUrl({ 4470 url: 'pages/detail', 4471 params: { 4472 data1: 'message' 4473 } 4474 }, rtm.Standard) 4475 .then(() => { 4476 console.info('succeeded') 4477 }) 4478 .catch((error: BusinessError) => { 4479 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4480 }) 4481 } 4482 4483 build() { 4484 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4485 Button() { 4486 Text('next page') 4487 .fontSize(25) 4488 .fontWeight(FontWeight.Bold) 4489 }.type(ButtonType.Capsule) 4490 .margin({ top: 20 }) 4491 .backgroundColor('#ccc') 4492 .onClick(() => { 4493 this.routePage() 4494 }) 4495 } 4496 .width('100%') 4497 .height('100%') 4498 } 4499} 4500``` 4501 4502### replaceUrl 4503 4504replaceUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 4505 4506Replaces the current page with another one in the application and destroys the current page. 4507 4508**Atomic service API**: This API can be used in atomic services since API version 11. 4509 4510**System capability**: SystemCapability.ArkUI.ArkUI.Full 4511 4512**Parameters** 4513 4514| Name | Type | Mandatory | Description | 4515| -------- | ---------------------------------------- | ---- | ---------- | 4516| options | [router.RouterOptions](js-apis-router.md#routeroptions) | Yes | Description of the new page. | 4517| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| 4518| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 4519 4520**Error codes** 4521 4522For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4523 4524| ID | Error Message | 4525| ------ | ---------------------------------------- | 4526| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4527| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 4528| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. | 4529 4530**Example** 4531 4532```ts 4533import { router } from '@kit.ArkUI'; 4534import { BusinessError } from '@kit.BasicServicesKit'; 4535 4536class RouterTmp { 4537 Standard: router.RouterMode = router.RouterMode.Standard 4538} 4539 4540let rtm: RouterTmp = new RouterTmp() 4541 4542@Entry 4543@Component 4544struct Index { 4545 async routePage() { 4546 this.getUIContext().getRouter().replaceUrl({ 4547 url: 'pages/detail', 4548 params: { 4549 data1: 'message' 4550 } 4551 }, rtm.Standard, (err: Error) => { 4552 if (err) { 4553 let message = (err as BusinessError).message; 4554 let code = (err as BusinessError).code; 4555 console.error(`replaceUrl failed, code is ${code}, message is ${message}`); 4556 return; 4557 } 4558 console.info('replaceUrl success'); 4559 }); 4560 } 4561 4562 build() { 4563 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4564 Button() { 4565 Text('next page') 4566 .fontSize(25) 4567 .fontWeight(FontWeight.Bold) 4568 }.type(ButtonType.Capsule) 4569 .margin({ top: 20 }) 4570 .backgroundColor('#ccc') 4571 .onClick(() => { 4572 this.routePage() 4573 }) 4574 } 4575 .width('100%') 4576 .height('100%') 4577 } 4578} 4579``` 4580 4581### pushNamedRoute 4582 4583pushNamedRoute(options: router.NamedRouterOptions): Promise<void> 4584 4585Navigates to a page using the named route. This API uses a promise to return the result. 4586 4587**Atomic service API**: This API can be used in atomic services since API version 11. 4588 4589**System capability**: SystemCapability.ArkUI.ArkUI.Full 4590 4591**Parameters** 4592 4593| Name | Type | Mandatory | Description | 4594| ------- | ---------------------------------------- | ---- | --------- | 4595| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters.| 4596 4597**Return value** 4598 4599| Type | Description | 4600| ------------------- | ------- | 4601| Promise<void> | Promise used to return the result.| 4602 4603**Error codes** 4604 4605For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4606 4607| ID | Error Message | 4608| ------ | ---------------------------------- | 4609| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4610| 100001 | Internal error. | 4611| 100003 | Page stack error. Too many pages are pushed. | 4612| 100004 | Named route error. The named route does not exist. | 4613 4614**Example** 4615 4616```ts 4617import { BusinessError } from '@kit.BasicServicesKit' 4618 4619@Entry 4620@Component 4621struct Index { 4622 async routePage() { 4623 this.getUIContext().getRouter().pushNamedRoute({ 4624 name: 'myPage', 4625 params: { 4626 data1: 'message', 4627 data2: { 4628 data3: [123, 456, 789] 4629 } 4630 } 4631 }) 4632 .then(() => { 4633 console.info('succeeded') 4634 }) 4635 .catch((error: BusinessError) => { 4636 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4637 }) 4638 } 4639 4640 build() { 4641 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4642 Button() { 4643 Text('next page') 4644 .fontSize(25) 4645 .fontWeight(FontWeight.Bold) 4646 }.type(ButtonType.Capsule) 4647 .margin({ top: 20 }) 4648 .backgroundColor('#ccc') 4649 .onClick(() => { 4650 this.routePage() 4651 }) 4652 } 4653 .width('100%') 4654 .height('100%') 4655 } 4656} 4657``` 4658 4659### pushNamedRoute 4660 4661pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void 4662 4663Navigates to a page using the named route. This API uses a promise to return the result. 4664 4665**Atomic service API**: This API can be used in atomic services since API version 11. 4666 4667**System capability**: SystemCapability.ArkUI.ArkUI.Full 4668 4669**Parameters** 4670 4671| Name | Type | Mandatory | Description | 4672| -------- | ---------------------------------------- | ---- | --------- | 4673| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters.| 4674| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 4675 4676**Error codes** 4677 4678For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4679 4680| ID | Error Message | 4681| ------ | ---------------------------------- | 4682| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4683| 100001 | Internal error. | 4684| 100003 | Page stack error. Too many pages are pushed. | 4685| 100004 | Named route error. The named route does not exist. | 4686 4687**Example** 4688 4689```ts 4690import { BusinessError } from '@kit.BasicServicesKit'; 4691 4692@Entry 4693@Component 4694struct Index { 4695 async routePage() { 4696 this.getUIContext().getRouter().pushNamedRoute({ 4697 name: 'myPage', 4698 params: { 4699 data1: 'message', 4700 data2: { 4701 data3: [123, 456, 789] 4702 } 4703 } 4704 }, (err: Error) => { 4705 if (err) { 4706 let message = (err as BusinessError).message; 4707 let code = (err as BusinessError).code; 4708 console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); 4709 return; 4710 } 4711 console.info('pushNamedRoute success'); 4712 }) 4713 } 4714 4715 build() { 4716 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4717 Button() { 4718 Text('next page') 4719 .fontSize(25) 4720 .fontWeight(FontWeight.Bold) 4721 }.type(ButtonType.Capsule) 4722 .margin({ top: 20 }) 4723 .backgroundColor('#ccc') 4724 .onClick(() => { 4725 this.routePage() 4726 }) 4727 } 4728 .width('100%') 4729 .height('100%') 4730 } 4731} 4732``` 4733### pushNamedRoute 4734 4735pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void> 4736 4737Navigates to a page using the named route. This API uses a promise to return the result. 4738 4739**Atomic service API**: This API can be used in atomic services since API version 11. 4740 4741**System capability**: SystemCapability.ArkUI.ArkUI.Full 4742 4743**Parameters** 4744 4745| Name | Type | Mandatory | Description | 4746| ------- | ---------------------------------------- | ---- | ---------- | 4747| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters. | 4748| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| 4749 4750**Return value** 4751 4752| Type | Description | 4753| ------------------- | ------- | 4754| Promise<void> | Promise used to return the result.| 4755 4756**Error codes** 4757 4758For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4759 4760| ID | Error Message | 4761| ------ | ---------------------------------- | 4762| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4763| 100001 | Internal error. | 4764| 100003 | Page stack error. Too many pages are pushed. | 4765| 100004 | Named route error. The named route does not exist. | 4766 4767**Example** 4768 4769```ts 4770import { router } from '@kit.ArkUI'; 4771import { BusinessError } from '@kit.BasicServicesKit'; 4772 4773class RouterTmp{ 4774 Standard:router.RouterMode = router.RouterMode.Standard 4775} 4776let rtm:RouterTmp = new RouterTmp() 4777 4778@Entry 4779@Component 4780struct Index { 4781 async routePage() { 4782 this.getUIContext().getRouter().pushNamedRoute({ 4783 name: 'myPage', 4784 params: { 4785 data1: 'message', 4786 data2: { 4787 data3: [123, 456, 789] 4788 } 4789 } 4790 }, rtm.Standard) 4791 .then(() => { 4792 console.info('succeeded') 4793 }) 4794 .catch((error: BusinessError) => { 4795 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4796 }) 4797 } 4798 4799 build() { 4800 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4801 Button() { 4802 Text('next page') 4803 .fontSize(25) 4804 .fontWeight(FontWeight.Bold) 4805 }.type(ButtonType.Capsule) 4806 .margin({ top: 20 }) 4807 .backgroundColor('#ccc') 4808 .onClick(() => { 4809 this.routePage() 4810 }) 4811 } 4812 .width('100%') 4813 .height('100%') 4814 } 4815} 4816``` 4817 4818### pushNamedRoute 4819 4820pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 4821 4822Navigates to a page using the named route. This API uses a promise to return the result. 4823 4824**Atomic service API**: This API can be used in atomic services since API version 11. 4825 4826**System capability**: SystemCapability.ArkUI.ArkUI.Full 4827 4828**Parameters** 4829 4830| Name | Type | Mandatory | Description | 4831| -------- | ---------------------------------------- | ---- | ---------- | 4832| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Page routing parameters. | 4833| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| 4834| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 4835 4836**Error codes** 4837 4838For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4839 4840| ID | Error Message | 4841| ------ | ---------------------------------- | 4842| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4843| 100001 | Internal error. | 4844| 100003 | Page stack error. Too many pages are pushed. | 4845| 100004 | Named route error. The named route does not exist. | 4846 4847**Example** 4848 4849```ts 4850import { router } from '@kit.ArkUI'; 4851import { BusinessError } from '@kit.BasicServicesKit'; 4852 4853class RouterTmp { 4854 Standard: router.RouterMode = router.RouterMode.Standard 4855} 4856 4857let rtm: RouterTmp = new RouterTmp() 4858 4859@Entry 4860@Component 4861struct Index { 4862 async routePage() { 4863 this.getUIContext().getRouter().pushNamedRoute({ 4864 name: 'myPage', 4865 params: { 4866 data1: 'message', 4867 data2: { 4868 data3: [123, 456, 789] 4869 } 4870 } 4871 }, rtm.Standard, (err: Error) => { 4872 if (err) { 4873 let message = (err as BusinessError).message; 4874 let code = (err as BusinessError).code; 4875 console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); 4876 return; 4877 } 4878 console.info('pushNamedRoute success'); 4879 }) 4880 } 4881 4882 build() { 4883 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4884 Button() { 4885 Text('next page') 4886 .fontSize(25) 4887 .fontWeight(FontWeight.Bold) 4888 }.type(ButtonType.Capsule) 4889 .margin({ top: 20 }) 4890 .backgroundColor('#ccc') 4891 .onClick(() => { 4892 this.routePage() 4893 }) 4894 } 4895 .width('100%') 4896 .height('100%') 4897 } 4898} 4899``` 4900 4901### replaceNamedRoute 4902 4903replaceNamedRoute(options: router.NamedRouterOptions): Promise<void> 4904 4905Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result. 4906 4907**Atomic service API**: This API can be used in atomic services since API version 11. 4908 4909**System capability**: SystemCapability.ArkUI.ArkUI.Full 4910 4911**Parameters** 4912 4913| Name | Type | Mandatory | Description | 4914| ------- | ---------------------------------------- | ---- | --------- | 4915| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page.| 4916 4917**Return value** 4918 4919| Type | Description | 4920| ------------------- | ------- | 4921| Promise<void> | Promise used to return the result.| 4922 4923**Error codes** 4924 4925For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4926 4927| ID | Error Message | 4928| ------ | ---------------------------------------- | 4929| 401 | if the number of parameters is less than 1 or the type of the url parameter is not string. | 4930| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 4931| 100004 | Named route error. The named route does not exist. | 4932 4933**Example** 4934 4935```ts 4936import { BusinessError } from '@kit.BasicServicesKit'; 4937 4938@Entry 4939@Component 4940struct Index { 4941 async routePage() { 4942 this.getUIContext().getRouter().replaceNamedRoute({ 4943 name: 'myPage', 4944 params: { 4945 data1: 'message' 4946 } 4947 }) 4948 .then(() => { 4949 console.info('succeeded') 4950 }) 4951 .catch((error: BusinessError) => { 4952 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4953 }) 4954 } 4955 4956 build() { 4957 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4958 Button() { 4959 Text('next page') 4960 .fontSize(25) 4961 .fontWeight(FontWeight.Bold) 4962 }.type(ButtonType.Capsule) 4963 .margin({ top: 20 }) 4964 .backgroundColor('#ccc') 4965 .onClick(() => { 4966 this.routePage() 4967 }) 4968 } 4969 .width('100%') 4970 .height('100%') 4971 } 4972} 4973``` 4974 4975### replaceNamedRoute 4976 4977replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void 4978 4979Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result. 4980 4981**Atomic service API**: This API can be used in atomic services since API version 11. 4982 4983**System capability**: SystemCapability.ArkUI.ArkUI.Full 4984 4985**Parameters** 4986 4987| Name | Type | Mandatory | Description | 4988| -------- | ---------------------------------------- | ---- | --------- | 4989| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page.| 4990| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 4991 4992**Error codes** 4993 4994For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 4995 4996| ID | Error Message | 4997| ------ | ---------------------------------------- | 4998| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4999| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 5000| 100004 | Named route error. The named route does not exist. | 5001 5002**Example** 5003 5004```ts 5005import { BusinessError } from '@kit.BasicServicesKit'; 5006 5007@Entry 5008@Component 5009struct Index { 5010 async routePage() { 5011 this.getUIContext().getRouter().replaceNamedRoute({ 5012 name: 'myPage', 5013 params: { 5014 data1: 'message' 5015 } 5016 }, (err: Error) => { 5017 if (err) { 5018 let message = (err as BusinessError).message; 5019 let code = (err as BusinessError).code; 5020 console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`); 5021 return; 5022 } 5023 console.info('replaceNamedRoute success'); 5024 }) 5025 } 5026 5027 build() { 5028 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5029 Button() { 5030 Text('next page') 5031 .fontSize(25) 5032 .fontWeight(FontWeight.Bold) 5033 }.type(ButtonType.Capsule) 5034 .margin({ top: 20 }) 5035 .backgroundColor('#ccc') 5036 .onClick(() => { 5037 this.routePage() 5038 }) 5039 } 5040 .width('100%') 5041 .height('100%') 5042 } 5043} 5044``` 5045 5046### replaceNamedRoute 5047 5048replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void> 5049 5050Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result. 5051 5052**Atomic service API**: This API can be used in atomic services since API version 11. 5053 5054**System capability**: SystemCapability.ArkUI.ArkUI.Full 5055 5056**Parameters** 5057 5058| Name | Type | Mandatory | Description | 5059| ------- | ---------------------------------------- | ---- | ---------- | 5060| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page. | 5061| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| 5062 5063 5064**Return value** 5065 5066| Type | Description | 5067| ------------------- | ------- | 5068| Promise<void> | Promise used to return the result.| 5069 5070**Error codes** 5071 5072For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 5073 5074| ID | Error Message | 5075| ------ | ---------------------------------------- | 5076| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5077| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. | 5078| 100004 | Named route error. The named route does not exist. | 5079 5080**Example** 5081 5082```ts 5083import { router } from '@kit.ArkUI'; 5084import { BusinessError } from '@kit.BasicServicesKit'; 5085 5086class RouterTmp { 5087 Standard: router.RouterMode = router.RouterMode.Standard 5088} 5089 5090let rtm: RouterTmp = new RouterTmp() 5091 5092@Entry 5093@Component 5094struct Index { 5095 async routePage() { 5096 this.getUIContext().getRouter().replaceNamedRoute({ 5097 name: 'myPage', 5098 params: { 5099 data1: 'message' 5100 } 5101 }, rtm.Standard) 5102 .then(() => { 5103 console.info('succeeded') 5104 }) 5105 .catch((error: BusinessError) => { 5106 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 5107 }) 5108 } 5109 5110 build() { 5111 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5112 Button() { 5113 Text('next page') 5114 .fontSize(25) 5115 .fontWeight(FontWeight.Bold) 5116 }.type(ButtonType.Capsule) 5117 .margin({ top: 20 }) 5118 .backgroundColor('#ccc') 5119 .onClick(() => { 5120 this.routePage() 5121 }) 5122 } 5123 .width('100%') 5124 .height('100%') 5125 } 5126} 5127``` 5128 5129### replaceNamedRoute 5130 5131replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 5132 5133Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result. 5134 5135**Atomic service API**: This API can be used in atomic services since API version 11. 5136 5137**System capability**: SystemCapability.ArkUI.ArkUI.Full 5138 5139**Parameters** 5140 5141| Name | Type | Mandatory | Description | 5142| -------- | ---------------------------------------- | ---- | ---------- | 5143| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | Yes | Description of the new page. | 5144| mode | [router.RouterMode](js-apis-router.md#routermode9) | Yes | Routing mode.| 5145| callback | AsyncCallback<void> | Yes | Callback used to return the result. | 5146 5147**Error codes** 5148 5149For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 5150 5151| ID | Error Message | 5152| ------ | ---------------------------------------- | 5153| 401 | if the number of parameters is less than 1 or the type of the url parameter is not string. | 5154| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 5155| 100004 | Named route error. The named route does not exist. | 5156 5157**Example** 5158 5159```ts 5160import { router } from '@kit.ArkUI'; 5161import { BusinessError } from '@kit.BasicServicesKit'; 5162 5163class RouterTmp { 5164 Standard: router.RouterMode = router.RouterMode.Standard 5165} 5166 5167let rtm: RouterTmp = new RouterTmp() 5168 5169@Entry 5170@Component 5171struct Index { 5172 async routePage() { 5173 this.getUIContext().getRouter().replaceNamedRoute({ 5174 name: 'myPage', 5175 params: { 5176 data1: 'message' 5177 } 5178 }, rtm.Standard, (err: Error) => { 5179 if (err) { 5180 let message = (err as BusinessError).message; 5181 let code = (err as BusinessError).code; 5182 console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`); 5183 return; 5184 } 5185 console.info('replaceNamedRoute success'); 5186 }) 5187 } 5188 5189 build() { 5190 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5191 Button() { 5192 Text('next page') 5193 .fontSize(25) 5194 .fontWeight(FontWeight.Bold) 5195 }.type(ButtonType.Capsule) 5196 .margin({ top: 20 }) 5197 .backgroundColor('#ccc') 5198 .onClick(() => { 5199 this.routePage() 5200 }) 5201 } 5202 .width('100%') 5203 .height('100%') 5204 } 5205} 5206``` 5207 5208### back 5209 5210back(options?: router.RouterOptions ): void 5211 5212Returns to the previous page or a specified page. 5213 5214**Atomic service API**: This API can be used in atomic services since API version 11. 5215 5216**System capability**: SystemCapability.ArkUI.ArkUI.Full 5217 5218**Parameters** 5219 5220| Name | Type | Mandatory | Description | 5221| ------- | ---------------------------------------- | ---- | ---------------------------------------- | 5222| 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.| 5223 5224**Example** 5225 5226```ts 5227import { Router } from '@kit.ArkUI'; 5228let router: Router = uiContext.getRouter(); 5229router.back({url:'pages/detail'}); 5230``` 5231 5232### back<sup>12+</sup> 5233 5234back(index: number, params?: Object): void; 5235 5236Returns to the specified page. 5237 5238**Atomic service API**: This API can be used in atomic services since API version 12. 5239 5240**System capability**: SystemCapability.ArkUI.ArkUI.Full 5241 5242**Parameters** 5243 5244| Name | Type | Mandatory | Description | 5245| ------- | ------------------------------- | ---- | ---------- | 5246| index | number | Yes | Index of the target page to navigate to. | 5247| params | Object | No | Parameters carried when returning to the page.| 5248 5249**Example** 5250 5251```ts 5252import { Router } from '@kit.ArkUI'; 5253 5254let router: Router = uiContext.getRouter(); 5255router.back(1); 5256``` 5257 5258```ts 5259import { Router } from '@kit.ArkUI'; 5260 5261let router: Router = uiContext.getRouter(); 5262router.back(1, {info:'From Home'}); // Returning with parameters. 5263``` 5264 5265### clear 5266 5267clear(): void 5268 5269Clears all historical pages in the stack and retains only the current page at the top of the stack. 5270 5271**Atomic service API**: This API can be used in atomic services since API version 11. 5272 5273**System capability**: SystemCapability.ArkUI.ArkUI.Full 5274 5275**Example** 5276 5277```ts 5278import { Router } from '@kit.ArkUI'; 5279 5280let router: Router = uiContext.getRouter(); 5281router.clear(); 5282``` 5283 5284### getLength 5285 5286getLength(): string 5287 5288Obtains the number of pages in the current stack. 5289 5290**Atomic service API**: This API can be used in atomic services since API version 11. 5291 5292**System capability**: SystemCapability.ArkUI.ArkUI.Full 5293 5294**Return value** 5295 5296| Type | Description | 5297| ------ | ------------------ | 5298| string | Number of pages in the stack. The maximum value is **32**.| 5299 5300**Example** 5301 5302```ts 5303import { Router } from '@kit.ArkUI'; 5304 5305let router: Router = uiContext.getRouter(); 5306let size = router.getLength(); 5307console.info('pages stack size = ' + size); 5308``` 5309 5310### getState 5311 5312getState(): router.RouterState 5313 5314Obtains state information about the current page. 5315 5316**Atomic service API**: This API can be used in atomic services since API version 11. 5317 5318**System capability**: SystemCapability.ArkUI.ArkUI.Full 5319 5320**Return value** 5321 5322| Type | Description | 5323| ---------------------------------------- | ------- | 5324| router.[RouterState](js-apis-router.md#routerstate) | Page routing state.| 5325 5326**Example** 5327 5328<!--code_no_check--> 5329```ts 5330import { Router } from '@kit.ArkUI'; 5331 5332let router: Router = uiContext.getRouter(); 5333let page = router.getState(); 5334console.info('current index = ' + page.index); 5335console.info('current name = ' + page.name); 5336console.info('current path = ' + page.path); 5337``` 5338 5339### getStateByIndex<sup>12+</sup> 5340 5341getStateByIndex(index: number): router.RouterState | undefined 5342 5343Obtains the status information about a page by its index. 5344 5345**Atomic service API**: This API can be used in atomic services since API version 12. 5346 5347**System capability**: SystemCapability.ArkUI.ArkUI.Full 5348 5349**Parameters** 5350 5351| Name | Type | Mandatory | Description | 5352| ------- | ------------------------------- | ---- | ---------- | 5353| index | number | Yes | Index of the target page. | 5354 5355**Return value** 5356 5357| Type | Description | 5358| --------------------------- | ------- | 5359| router.[RouterState](js-apis-router.md#routerstate) \| undefined | State information about the target page. **undefined** if the specified index does not exist.| 5360 5361**Example** 5362 5363<!--code_no_check--> 5364```ts 5365import { Router } from '@kit.ArkUI'; 5366 5367let router: Router = uiContext.getRouter(); 5368let options: router.RouterState | undefined = router.getStateByIndex(1); 5369if (options != undefined) { 5370 console.info('index = ' + options.index); 5371 console.info('name = ' + options.name); 5372 console.info('path = ' + options.path); 5373 console.info('params = ' + options.params); 5374} 5375``` 5376### getStateByUrl<sup>12+</sup> 5377 5378getStateByUrl(url: string): Array<router.[RouterState](js-apis-router.md#routerstate)> 5379 5380Obtains the status information about a page by its URL. 5381 5382**Atomic service API**: This API can be used in atomic services since API version 12. 5383 5384**System capability**: SystemCapability.ArkUI.ArkUI.Full 5385 5386**Parameters** 5387 5388| Name | Type | Mandatory | Description | 5389| ------- | ------------------------------- | ---- | ---------- | 5390| url | string | Yes | URL of the target page. | 5391 5392**Return value** 5393 5394| Type | Description | 5395| --------------------------- | ------- | 5396| Array<router.[RouterState](js-apis-router.md#routerstate)> | Page routing state.| 5397 5398**Example** 5399 5400<!--code_no_check--> 5401```ts 5402import { Router } from '@kit.ArkUI'; 5403let router: Router = uiContext.getRouter(); 5404let options:Array<router.RouterState> = router.getStateByUrl('pages/index'); 5405for (let i: number = 0; i < options.length; i++) { 5406 console.info('index = ' + options[i].index); 5407 console.info('name = ' + options[i].name); 5408 console.info('path = ' + options[i].path); 5409 console.info('params = ' + options[i].params); 5410} 5411``` 5412 5413### showAlertBeforeBackPage 5414 5415showAlertBeforeBackPage(options: router.EnableAlertOptions): void 5416 5417Enables the display of a confirm dialog box before returning to the previous page. 5418 5419**Atomic service API**: This API can be used in atomic services since API version 11. 5420 5421**System capability**: SystemCapability.ArkUI.ArkUI.Full 5422 5423**Parameters** 5424 5425| Name | Type | Mandatory | Description | 5426| ------- | ---------------------------------------- | ---- | --------- | 5427| options | [router.EnableAlertOptions](js-apis-router.md#enablealertoptions) | Yes | Description of the dialog box.| 5428 5429**Error codes** 5430 5431For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Router Error Codes](errorcode-router.md). 5432 5433| ID | Error Message | 5434| ------ | ---------------------------------- | 5435| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5436| 100001 | Internal error. | 5437 5438**Example** 5439 5440<!--code_no_check--> 5441```ts 5442import { Router } from '@kit.ArkUI'; 5443import { BusinessError } from '@kit.BasicServicesKit'; 5444 5445let router: Router = uiContext.getRouter(); 5446try { 5447 router.showAlertBeforeBackPage({ 5448 message: 'Message Info' 5449 }); 5450} catch(error) { 5451 let message = (error as BusinessError).message; 5452 let code = (error as BusinessError).code; 5453 console.error(`showAlertBeforeBackPage failed, code is ${code}, message is ${message}`); 5454} 5455``` 5456 5457### hideAlertBeforeBackPage 5458 5459hideAlertBeforeBackPage(): void 5460 5461Disables the display of a confirm dialog box before returning to the previous page. 5462 5463**Atomic service API**: This API can be used in atomic services since API version 11. 5464 5465**System capability**: SystemCapability.ArkUI.ArkUI.Full 5466 5467**Example** 5468 5469```ts 5470import { Router } from '@kit.ArkUI'; 5471 5472let router: Router = uiContext.getRouter(); 5473router.hideAlertBeforeBackPage(); 5474``` 5475 5476### getParams 5477 5478getParams(): Object 5479 5480Obtains the parameters passed from the page that initiates redirection to the current page. 5481 5482**Atomic service API**: This API can be used in atomic services since API version 11. 5483 5484**System capability**: SystemCapability.ArkUI.ArkUI.Full 5485 5486**Return value** 5487 5488| Type | Description | 5489| ------ | ----------------- | 5490| object | Parameters passed from the page that initiates redirection to the current page.| 5491 5492**Example** 5493 5494<!--code_no_check--> 5495 5496```ts 5497import { Router } from '@kit.ArkUI'; 5498 5499let router: Router = uiContext.getRouter(); 5500router.getParams(); 5501``` 5502 5503## PromptAction 5504 5505In 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. 5506 5507### showToast 5508 5509showToast(options: promptAction.ShowToastOptions): void 5510 5511Shows a toast in the given settings. 5512 5513**Atomic service API**: This API can be used in atomic services since API version 11. 5514 5515**System capability**: SystemCapability.ArkUI.ArkUI.Full 5516 5517**Parameters** 5518 5519| Name | Type | Mandatory | Description | 5520| ------- | ---------------------------------------- | ---- | ------- | 5521| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | Yes | Toast options.| 5522 5523**Error codes** 5524 5525For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md). 5526 5527| ID | Error Message | 5528| ------ | ---------------------------------- | 5529| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5530| 100001 | Internal error. | 5531 5532**Example** 5533 5534<!--code_no_check--> 5535```ts 5536import { PromptAction } from '@kit.ArkUI'; 5537import { BusinessError } from '@kit.BasicServicesKit'; 5538 5539let promptAction: PromptAction = uiContext.getPromptAction(); 5540try { 5541 promptAction.showToast({ 5542 message: 'Message Info', 5543 duration: 2000 5544 }); 5545} catch (error) { 5546 let message = (error as BusinessError).message; 5547 let code = (error as BusinessError).code; 5548 console.error(`showToast args error code is ${code}, message is ${message}`); 5549}; 5550``` 5551 5552### showDialog 5553 5554showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse>): void 5555 5556Shows a dialog box in the given settings. This API uses an asynchronous callback to return the result. 5557 5558**Atomic service API**: This API can be used in atomic services since API version 11. 5559 5560**System capability**: SystemCapability.ArkUI.ArkUI.Full 5561 5562**Parameters** 5563 5564| Name | Type | Mandatory | Description | 5565| -------- | ---------------------------------------- | ---- | ------------ | 5566| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes | Dialog box options.| 5567| callback | AsyncCallback<[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | 5568 5569**Error codes** 5570 5571For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md). 5572 5573| ID | Error Message | 5574| ------ | ---------------------------------- | 5575| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5576| 100001 | Internal error. | 5577 5578**Example** 5579 5580<!--code_no_check--> 5581 5582```ts 5583import { PromptAction } from '@kit.ArkUI'; 5584import { BusinessError } from '@kit.BasicServicesKit'; 5585 5586let promptAction: PromptAction = uiContext.getPromptAction(); 5587try { 5588 promptAction.showDialog({ 5589 title: 'showDialog Title Info', 5590 message: 'Message Info', 5591 buttons: [ 5592 { 5593 text: 'button1', 5594 color: '#000000' 5595 }, 5596 { 5597 text: 'button2', 5598 color: '#000000' 5599 } 5600 ] 5601 }, (err, data) => { 5602 if (err) { 5603 console.error('showDialog err: ' + err); 5604 return; 5605 } 5606 console.info('showDialog success callback, click button: ' + data.index); 5607 }); 5608} catch (error) { 5609 let message = (error as BusinessError).message; 5610 let code = (error as BusinessError).code; 5611 console.error(`showDialog args error code is ${code}, message is ${message}`); 5612}; 5613``` 5614 5615### showDialog 5616 5617showDialog(options: promptAction.ShowDialogOptions): Promise<promptAction.ShowDialogSuccessResponse> 5618 5619Shows a dialog box. This API uses a promise to return the result. 5620 5621**Atomic service API**: This API can be used in atomic services since API version 11. 5622 5623**System capability**: SystemCapability.ArkUI.ArkUI.Full 5624 5625**Parameters** 5626 5627| Name | Type | Mandatory | Description | 5628| ------- | ---------------------------------------- | ---- | ------ | 5629| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | Yes | Dialog box options.| 5630 5631**Return value** 5632 5633| Type | Description | 5634| ---------------------------------------- | -------- | 5635| Promise<[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | Promise used to return the dialog box response result.| 5636 5637**Error codes** 5638 5639For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md). 5640 5641| ID | Error Message | 5642| ------ | ---------------------------------- | 5643| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5644| 100001 | Internal error. | 5645 5646**Example** 5647 5648<!--code_no_check--> 5649```ts 5650import { PromptAction } from '@kit.ArkUI'; 5651 5652let promptAction: PromptAction = uiContext.getPromptAction(); 5653promptAction.showDialog({ 5654 title: 'Title Info', 5655 message: 'Message Info', 5656 buttons: [ 5657 { 5658 text: 'button1', 5659 color: '#000000' 5660 }, 5661 { 5662 text: 'button2', 5663 color: '#000000' 5664 } 5665 ], 5666}) 5667 .then(data => { 5668 console.info('showDialog success, click button: ' + data.index); 5669 }) 5670 .catch((err: Error) => { 5671 console.error('showDialog error: ' + err); 5672 }) 5673``` 5674 5675### showActionMenu<sup>11+</sup> 5676 5677showActionMenu(options: promptAction.ActionMenuOptions, callback: AsyncCallback<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)>):void 5678 5679Shows an action menu in the given settings. This API uses an asynchronous callback to return the result. 5680 5681**Atomic service API**: This API can be used in atomic services since API version 11. 5682 5683**System capability**: SystemCapability.ArkUI.ArkUI.Full 5684 5685**Parameters** 5686 5687| Name | Type | Mandatory| Description | 5688| -------- | ------------------------------------------------------------ | ---- | ------------------ | 5689| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes | Action menu options. | 5690| callback | AsyncCallback<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.| 5691 5692**Error codes** 5693 5694For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md). 5695 5696| ID| Error Message | 5697| -------- | ---------------------------------- | 5698| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5699| 100001 | Internal error. | 5700 5701**Example** 5702 5703<!--code_no_check--> 5704```ts 5705import { PromptAction, promptAction } from '@kit.ArkUI'; 5706import { BusinessError } from '@kit.BasicServicesKit'; 5707 5708let promptActionF: PromptAction = uiContext.getPromptAction(); 5709try { 5710 promptActionF.showActionMenu({ 5711 title: 'Title Info', 5712 buttons: [ 5713 { 5714 text: 'item1', 5715 color: '#666666' 5716 }, 5717 { 5718 text: 'item2', 5719 color: '#000000' 5720 } 5721 ] 5722 }, (err:BusinessError, data:promptAction.ActionMenuSuccessResponse) => { 5723 if (err) { 5724 console.error('showDialog err: ' + err); 5725 return; 5726 } 5727 console.info('showDialog success callback, click button: ' + data.index); 5728 }); 5729} catch (error) { 5730 let message = (error as BusinessError).message; 5731 let code = (error as BusinessError).code; 5732 console.error(`showActionMenu args error code is ${code}, message is ${message}`); 5733}; 5734``` 5735 5736### showActionMenu<sup>(deprecated)</sup> 5737 5738showActionMenu(options: promptAction.ActionMenuOptions, callback: [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)):void 5739 5740Shows an action menu in the given settings. This API uses an asynchronous callback to return the result. 5741 5742This API is deprecated since API version 11. You are advised to use [showActionMenu](#showactionmenu11) instead. 5743 5744**System capability**: SystemCapability.ArkUI.ArkUI.Full 5745 5746**Parameters** 5747 5748| Name | Type | Mandatory| Description | 5749| -------- | ------------------------------------------------------------ | ---- | ------------------ | 5750| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes | Action menu options. | 5751| callback | [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse) | Yes | Callback used to return the action menu response result.| 5752 5753**Error codes** 5754 5755For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md). 5756 5757| ID | Error Message | 5758| ------ | ---------------------------------- | 5759| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5760| 100001 | Internal error. | 5761 5762**Example** 5763 5764<!--code_no_check--> 5765```ts 5766import { PromptAction,promptAction } from '@kit.ArkUI'; 5767import { BusinessError } from '@kit.BasicServicesKit'; 5768 5769let promptActionF: PromptAction = uiContext.getPromptAction(); 5770try { 5771 promptActionF.showActionMenu({ 5772 title: 'Title Info', 5773 buttons: [ 5774 { 5775 text: 'item1', 5776 color: '#666666' 5777 }, 5778 { 5779 text: 'item2', 5780 color: '#000000' 5781 } 5782 ] 5783 }, { index:0 }); 5784} catch (error) { 5785 let message = (error as BusinessError).message; 5786 let code = (error as BusinessError).code; 5787 console.error(`showActionMenu args error code is ${code}, message is ${message}`); 5788}; 5789``` 5790 5791### showActionMenu 5792 5793showActionMenu(options: promptAction.ActionMenuOptions): Promise<promptAction.ActionMenuSuccessResponse> 5794 5795Shows an action menu. This API uses a promise to return the result. 5796 5797**Atomic service API**: This API can be used in atomic services since API version 11. 5798 5799**System capability**: SystemCapability.ArkUI.ArkUI.Full 5800 5801**Parameters** 5802 5803| Name | Type | Mandatory | Description | 5804| ------- | ---------------------------------------- | ---- | ------- | 5805| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | Yes | Action menu options.| 5806 5807**Return value** 5808 5809| Type | Description | 5810| ---------------------------------------- | ------- | 5811| Promise<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | Promise used to return the action menu response result.| 5812 5813**Error codes** 5814 5815For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md). 5816 5817| ID | Error Message | 5818| ------ | ---------------------------------- | 5819| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5820| 100001 | Internal error. | 5821 5822**Example** 5823 5824<!--code_no_check--> 5825```ts 5826import { PromptAction } from '@kit.ArkUI'; 5827 5828let promptAction: PromptAction = uiContext.getPromptAction(); 5829promptAction.showActionMenu({ 5830 title: 'showActionMenu Title Info', 5831 buttons: [ 5832 { 5833 text: 'item1', 5834 color: '#666666' 5835 }, 5836 { 5837 text: 'item2', 5838 color: '#000000' 5839 }, 5840 ] 5841}) 5842 .then(data => { 5843 console.info('showActionMenu success, click button: ' + data.index); 5844 }) 5845 .catch((err: Error) => { 5846 console.error('showActionMenu error: ' + err); 5847 }) 5848``` 5849 5850### openCustomDialog<sup>12+</sup> 5851 5852openCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>, options?: promptAction.BaseDialogOptions): Promise<void> 5853 5854Opens 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**. **isModal = true** and **showInSubWindow = true** cannot be used at the same time. 5855 5856**Atomic service API**: This API can be used in atomic services since API version 12. 5857 5858**System capability**: SystemCapability.ArkUI.ArkUI.Full 5859 5860**Parameters** 5861 5862| Name | Type | Mandatory | Description | 5863| ------- | ---------------------------------------- | ---- | ------- | 5864| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content of the custom dialog box.| 5865| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | No | Dialog box style.| 5866 5867**Return value** 5868 5869| Type | Description | 5870| ---------------------------------------- | ------- | 5871| Promise<void> | Promise used to return the result.| 5872 5873**Error codes** 5874 5875For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md). 5876 5877| ID | Error Message | 5878| ------ | ---------------------------------- | 5879| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5880| 103301 | the ComponentContent is incorrect. | 5881| 103302 | Dialog content already exists.| 5882 5883**Example** 5884 5885```ts 5886import { BusinessError } from '@kit.BasicServicesKit'; 5887import { ComponentContent } from '@kit.ArkUI'; 5888 5889class Params { 5890 text: string = "" 5891 5892 constructor(text: string) { 5893 this.text = text; 5894 } 5895} 5896 5897@Builder 5898function buildText(params: Params) { 5899 Column() { 5900 Text(params.text) 5901 .fontSize(50) 5902 .fontWeight(FontWeight.Bold) 5903 .margin({ bottom: 36 }) 5904 }.backgroundColor('#FFF0F0F0') 5905} 5906 5907@Entry 5908@Component 5909struct Index { 5910 @State message: string = "hello" 5911 5912 build() { 5913 Row() { 5914 Column() { 5915 Button("click me") 5916 .onClick(() => { 5917 let uiContext = this.getUIContext(); 5918 let promptAction = uiContext.getPromptAction(); 5919 let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); 5920 promptAction.openCustomDialog(contentNode) 5921 .then(() => { 5922 console.info('succeeded') 5923 }) 5924 .catch((error: BusinessError) => { 5925 console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`); 5926 }) 5927 }) 5928 } 5929 .width('100%') 5930 .height('100%') 5931 } 5932 .height('100%') 5933 } 5934} 5935``` 5936 5937### closeCustomDialog<sup>12+</sup> 5938 5939closeCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>): Promise<void> 5940 5941Closes a custom dialog box corresponding to **dialogContent**. This API uses a promise to return the result. 5942 5943**Atomic service API**: This API can be used in atomic services since API version 12. 5944 5945**System capability**: SystemCapability.ArkUI.ArkUI.Full 5946 5947**Parameters** 5948 5949| Name | Type | Mandatory | Description | 5950| ------- | ---------------------------------------- | ---- | ------- | 5951| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content of the custom dialog box.| 5952 5953**Return value** 5954 5955| Type | Description | 5956| ---------------------------------------- | ------- | 5957| Promise<void> | Promise used to return the result.| 5958 5959**Error codes** 5960 5961For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md). 5962 5963| ID | Error Message | 5964| ------ | ---------------------------------- | 5965| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5966| 103301 | the ComponentContent is incorrect. | 5967| 103303 | the ComponentContent cannot be found. | 5968 5969**Example** 5970 5971```ts 5972import { BusinessError } from '@kit.BasicServicesKit'; 5973import { ComponentContent } from '@kit.ArkUI'; 5974 5975class Params { 5976 text: string = "" 5977 5978 constructor(text: string) { 5979 this.text = text; 5980 } 5981} 5982 5983@Builder 5984function buildText(params: Params) { 5985 Column() { 5986 Text(params.text) 5987 .fontSize(50) 5988 .fontWeight(FontWeight.Bold) 5989 .margin({ bottom: 36 }) 5990 }.backgroundColor('#FFF0F0F0') 5991} 5992 5993@Entry 5994@Component 5995struct Index { 5996 @State message: string = "hello" 5997 5998 build() { 5999 Row() { 6000 Column() { 6001 Button("click me") 6002 .onClick(() => { 6003 let uiContext = this.getUIContext(); 6004 let promptAction = uiContext.getPromptAction(); 6005 let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); 6006 promptAction.openCustomDialog(contentNode) 6007 .then(() => { 6008 console.info('succeeded') 6009 }) 6010 .catch((error: BusinessError) => { 6011 console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`); 6012 }) 6013 setTimeout(() => { 6014 promptAction.closeCustomDialog(contentNode) 6015 .then(() => { 6016 console.info('succeeded') 6017 }) 6018 .catch((error: BusinessError) => { 6019 console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`); 6020 }) 6021 }, 2000); // Automatically close the dialog box after 2 seconds. 6022 }) 6023 } 6024 .width('100%') 6025 .height('100%') 6026 } 6027 .height('100%') 6028 } 6029} 6030``` 6031 6032### updateCustomDialog<sup>12+</sup> 6033 6034updateCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>, options: promptAction.BaseDialogOptions): Promise<void> 6035 6036Updates a custom dialog box corresponding to **dialogContent**. This API uses a promise to return the result. 6037 6038**Atomic service API**: This API can be used in atomic services since API version 12. 6039 6040**System capability**: SystemCapability.ArkUI.ArkUI.Full 6041 6042**Parameters** 6043 6044| Name | Type | Mandatory | Description | 6045| ------- | ---------------------------------------- | ---- | ------- | 6046| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | Yes| Content of the custom dialog box.| 6047| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | Yes | Dialog box style. Currently, only **alignment**, **offset**, **autoCancel**, and **maskColor** can be updated.| 6048 6049**Return value** 6050 6051| Type | Description | 6052| ---------------------------------------- | ------- | 6053| Promise<void> | Promise used to return the result.| 6054 6055**Error codes** 6056 6057For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md). 6058 6059| ID | Error Message | 6060| ------ | ---------------------------------- | 6061| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6062| 103301 | the ComponentContent is incorrect. | 6063| 103303 | the ComponentContent cannot be found. | 6064 6065**Example** 6066 6067```ts 6068import { BusinessError } from '@kit.BasicServicesKit'; 6069import { ComponentContent } from '@kit.ArkUI'; 6070 6071class Params { 6072 text: string = "" 6073 6074 constructor(text: string) { 6075 this.text = text; 6076 } 6077} 6078 6079@Builder 6080function buildText(params: Params) { 6081 Column() { 6082 Text(params.text) 6083 .fontSize(50) 6084 .fontWeight(FontWeight.Bold) 6085 .margin({ bottom: 36 }) 6086 }.backgroundColor('#FFF0F0F0') 6087} 6088 6089@Entry 6090@Component 6091struct Index { 6092 @State message: string = "hello" 6093 6094 build() { 6095 Row() { 6096 Column() { 6097 Button("click me") 6098 .onClick(() => { 6099 let uiContext = this.getUIContext(); 6100 let promptAction = uiContext.getPromptAction(); 6101 let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)) 6102 promptAction.openCustomDialog(contentNode) 6103 .then(() => { 6104 console.info('succeeded') 6105 }) 6106 .catch((error: BusinessError) => { 6107 console.error(`updateCustomDialog args error code is ${error.code}, message is ${error.message}`) 6108 }) 6109 6110 setTimeout(() => { 6111 promptAction.updateCustomDialog(contentNode, { alignment: DialogAlignment.CenterEnd }) 6112 .then(() => { 6113 console.info('succeeded') 6114 }) 6115 .catch((error: BusinessError) => { 6116 console.error(`updateCustomDialog args error code is ${error.code}, message is ${error.message}`) 6117 }) 6118 }, 2000); // Automatically update the dialog box position after 2 seconds. 6119 }) 6120 } 6121 .width('100%') 6122 .height('100%') 6123 } 6124 .height('100%') 6125 } 6126} 6127``` 6128 6129### openCustomDialog<sup>12+</sup> 6130 6131openCustomDialog(options: promptAction.CustomDialogOptions): Promise\<number> 6132 6133Creates 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. 6134 6135**Atomic service API**: This API can be used in atomic services since API version 12. 6136 6137**System capability**: SystemCapability.ArkUI.ArkUI.Full 6138 6139**Parameters** 6140 6141| Name | Type | Mandatory| Description | 6142| ------- | ------------------------------------------------------------ | ---- | ------------------ | 6143| options | [promptAction.CustomDialogOptions](js-apis-promptAction.md#customdialogoptions11) | No| Style of the custom dialog box.| 6144 6145**Return value** 6146 6147| Type | Description | 6148| ------------------- | --------------------------------------- | 6149| Promise<number> | Promise used to return the custom dialog box ID.| 6150 6151**Error codes** 6152 6153For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md). 6154 6155| ID| Error Message | 6156| -------- | ------------------------------------------------------------ | 6157| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6158| 100001 | Internal error. | 6159 6160### closeCustomDialog<sup>12+</sup> 6161 6162closeCustomDialog(dialogId: number): void 6163 6164Closes the specified custom dialog box. 6165 6166**Atomic service API**: This API can be used in atomic services since API version 12. 6167 6168**System capability**: SystemCapability.ArkUI.ArkUI.Full 6169 6170**Parameters** 6171 6172| Name | Type | Mandatory| Description | 6173| -------- | ------ | ---- | -------------------------------- | 6174| dialogId | number | Yes | ID of the custom dialog box to close. It is returned from **openCustomDialog**.| 6175 6176**Error codes** 6177 6178For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [promptAction Error Codes](errorcode-promptAction.md). 6179 6180| ID| Error Message | 6181| -------- | ------------------------------------------------------------ | 6182| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6183| 100001 | Internal error. | 6184 6185**Example** 6186 6187```ts 6188import { PromptAction } from '@kit.ArkUI'; 6189 6190@Entry 6191@Component 6192struct Index { 6193 promptAction: PromptAction = this.getUIContext().getPromptAction() 6194 private customDialogComponentId: number = 0 6195 6196 @Builder 6197 customDialogComponent() { 6198 Column() { 6199 Text('Dialog box').fontSize(30) 6200 Row({ space: 50 }) { 6201 Button("OK").onClick(() => { 6202 this.promptAction.closeCustomDialog(this.customDialogComponentId) 6203 }) 6204 Button("Cancel").onClick(() => { 6205 this.promptAction.closeCustomDialog(this.customDialogComponentId) 6206 }) 6207 } 6208 }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween) 6209 } 6210 6211 build() { 6212 Row() { 6213 Column() { 6214 Button("click me") 6215 .onClick(() => { 6216 this.promptAction.openCustomDialog({ 6217 builder: () => { 6218 this.customDialogComponent() 6219 }, 6220 onWillDismiss: (dismissDialogAction: DismissDialogAction) => { 6221 console.info("reason" + JSON.stringify(dismissDialogAction.reason)) 6222 console.log("dialog onWillDismiss") 6223 if (dismissDialogAction.reason == DismissReason.PRESS_BACK) { 6224 dismissDialogAction.dismiss() 6225 } 6226 if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) { 6227 dismissDialogAction.dismiss() 6228 } 6229 } 6230 }).then((dialogId: number) => { 6231 this.customDialogComponentId = dialogId 6232 }) 6233 }) 6234 } 6235 .width('100%') 6236 .height('100%') 6237 } 6238 .height('100%') 6239 } 6240} 6241``` 6242 6243## DragController<sup>11+</sup> 6244In 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. 6245 6246### executeDrag<sup>11+</sup> 6247 6248executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo, callback: AsyncCallback<dragController.DragEventParam>): void 6249 6250Executes dragging, by passing in the object to be dragged and the dragging information. This API uses a callback to return the drag event result. 6251 6252**Atomic service API**: This API can be used in atomic services since API version 12. 6253 6254**System capability**: SystemCapability.ArkUI.ArkUI.Full 6255 6256**Parameters** 6257 6258| Name | Type | Mandatory| Description | 6259| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 6260| 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.| 6261| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | Yes | Dragging information. | 6262| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<[dragController.DragEventParam](js-apis-arkui-dragController.md#drageventparam12)> | 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.| 6263 6264**Error codes** 6265For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 6266 6267| ID| Error Message | 6268| -------- | ------------- | 6269| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6270| 100001 | Internal handling failed. | 6271 6272**Example** 6273 6274```ts 6275import { dragController } from "@kit.ArkUI" 6276import { unifiedDataChannel } from '@kit.ArkData'; 6277 6278@Entry 6279@Component 6280struct DragControllerPage { 6281 @Builder DraggingBuilder() { 6282 Column() { 6283 Text("DraggingBuilder") 6284 } 6285 .width(100) 6286 .height(100) 6287 .backgroundColor(Color.Blue) 6288 } 6289 6290 build() { 6291 Column() { 6292 Button('touch to execute drag') 6293 .onTouch((event?:TouchEvent) => { 6294 if(event){ 6295 if (event.type == TouchType.Down) { 6296 let text = new unifiedDataChannel.Text() 6297 let unifiedData = new unifiedDataChannel.UnifiedData(text) 6298 6299 let dragInfo: dragController.DragInfo = { 6300 pointerId: 0, 6301 data: unifiedData, 6302 extraParams: '' 6303 } 6304 class tmp{ 6305 event:DragEvent|undefined = undefined 6306 extraParams:string = '' 6307 } 6308 let eve:tmp = new tmp() 6309 dragController.executeDrag(()=>{this.DraggingBuilder()}, dragInfo, (err, eve) => { 6310 if(eve.event){ 6311 if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) { 6312 // ... 6313 } else if (eve.event.getResult() == DragResult.DRAG_FAILED) { 6314 // ... 6315 } 6316 } 6317 }) 6318 } 6319 } 6320 }) 6321 } 6322 } 6323} 6324``` 6325 6326### executeDrag<sup>11+</sup> 6327 6328executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo): Promise<dragController.DragEventParam> 6329 6330Executes dragging, by passing in the object to be dragged and the dragging information. This API uses a promise to return the drag event result. 6331 6332**Atomic service API**: This API can be used in atomic services since API version 12. 6333 6334**System capability**: SystemCapability.ArkUI.ArkUI.Full 6335 6336**Parameters** 6337 6338| Name | Type | Mandatory| Description | 6339| -------- | ------------------------------------------------------------ | ---- | -------------------------------- | 6340| custom | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo) | Yes | Object to be dragged.| 6341| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | Yes | Dragging information. | 6342 6343**Return value** 6344 6345| Type | Description | 6346| ------------------------------------------------------------ | ------------------------------------------------------------ | 6347| Promise<[dragController.DragEventParam](js-apis-arkui-dragController.md#drageventparam12)> | 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.| 6348 6349**Error codes** 6350For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 6351 6352| ID| Error Message | 6353| -------- | ------------- | 6354| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6355| 100001 | Internal handling failed. | 6356 6357**Example** 6358 6359```ts 6360import { dragController, componentSnapshot } from "@kit.ArkUI" 6361import { image } from '@kit.ImageKit'; 6362import { unifiedDataChannel } from '@kit.ArkData'; 6363 6364@Entry 6365@Component 6366struct DragControllerPage { 6367 @State pixmap: image.PixelMap|null = null 6368 6369 @Builder DraggingBuilder() { 6370 Column() { 6371 Text("DraggingBuilder") 6372 } 6373 .width(100) 6374 .height(100) 6375 .backgroundColor(Color.Blue) 6376 } 6377 6378 @Builder PixmapBuilder() { 6379 Column() { 6380 Text("PixmapBuilder") 6381 } 6382 .width(100) 6383 .height(100) 6384 .backgroundColor(Color.Blue) 6385 } 6386 6387 build() { 6388 Column() { 6389 Button('touch to execute drag') 6390 .onTouch((event?:TouchEvent) => { 6391 if(event){ 6392 if (event.type == TouchType.Down) { 6393 let text = new unifiedDataChannel.Text() 6394 let unifiedData = new unifiedDataChannel.UnifiedData(text) 6395 6396 let dragInfo: dragController.DragInfo = { 6397 pointerId: 0, 6398 data: unifiedData, 6399 extraParams: '' 6400 } 6401 let pb:CustomBuilder = ():void=>{this.PixmapBuilder()} 6402 componentSnapshot.createFromBuilder(pb).then((pix: image.PixelMap) => { 6403 this.pixmap = pix; 6404 let dragItemInfo: DragItemInfo = { 6405 pixelMap: this.pixmap, 6406 builder: ()=>{this.DraggingBuilder()}, 6407 extraInfo: "DragItemInfoTest" 6408 } 6409 6410 class tmp{ 6411 event:DragResult|undefined = undefined 6412 extraParams:string = '' 6413 } 6414 let eve:tmp = new tmp() 6415 dragController.executeDrag(dragItemInfo, dragInfo) 6416 .then((eve) => { 6417 if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) { 6418 // ... 6419 } else if (eve.event.getResult() == DragResult.DRAG_FAILED) { 6420 // ... 6421 } 6422 }) 6423 .catch((err:Error) => { 6424 }) 6425 }) 6426 } 6427 } 6428 }) 6429 } 6430 .width('100%') 6431 .height('100%') 6432 } 6433} 6434``` 6435 6436### createDragAction<sup>11+</sup> 6437 6438createDragAction(customArray: Array<CustomBuilder \| DragItemInfo>, dragInfo: dragController.DragInfo): dragController.DragAction 6439 6440Creates 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. 6441 6442**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. 6443 6444**Atomic service API**: This API can be used in atomic services since API version 12. 6445 6446**System capability**: SystemCapability.ArkUI.ArkUI.Full 6447 6448**Parameters** 6449 6450| Name | Type | Mandatory| Description | 6451| -------- | ------------------------------------------------------------ | ---- | -------------------------------- | 6452| customArray | Array<[CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo)> | Yes | Object to be dragged.| 6453| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | Yes | Dragging information. | 6454 6455**Return value** 6456 6457| Type | Description | 6458| ------------------------------------------------------ | ------------------ | 6459| [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.| 6460 6461**Error codes** 6462For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 6463 6464| ID| Error Message | 6465| -------- | ------------- | 6466| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6467| 100001 | Internal handling failed. | 6468 6469**Example** 64701. In the **EntryAbility.ets** file, obtain the UI context and save it to LocalStorage. 6471```ts 6472import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 6473import { hilog } from '@kit.PerformanceAnalysisKit'; 6474import { window, UIContext } from '@kit.ArkUI'; 6475 6476let uiContext: UIContext; 6477let localStorage: LocalStorage = new LocalStorage('uiContext'); 6478 6479export default class EntryAbility extends UIAbility { 6480 storage: LocalStorage = localStorage; 6481 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 6482 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 6483 } 6484 6485 onDestroy(): void { 6486 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); 6487 } 6488 6489 onWindowStageCreate(windowStage: window.WindowStage): void { 6490 // Main window is created, set main page for this ability 6491 let storage: LocalStorage = new LocalStorage(); 6492 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 6493 6494 windowStage.loadContent('pages/Index', storage, (err, data) => { 6495 if (err.code) { 6496 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 6497 return; 6498 } 6499 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 6500 windowStage.getMainWindow((err, data) => 6501 { 6502 if (err.code) { 6503 console.error('Failed to abtain the main window. Cause:' + err.message); 6504 return; 6505 } 6506 let windowClass: window.Window = data; 6507 uiContext = windowClass.getUIContext(); 6508 this.storage.setOrCreate<UIContext>('uiContext', uiContext); 6509 // Obtain a UIContext instance. 6510 }) 6511 }); 6512 } 6513 6514 onWindowStageDestroy(): void { 6515 // Main window is destroyed, release UI related resources 6516 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); 6517 } 6518 6519 onForeground(): void { 6520 // Ability has brought to foreground 6521 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); 6522 } 6523 6524 onBackground(): void { 6525 // Ability has back to background 6526 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); 6527 } 6528} 6529``` 65302. Call **LocalStorage.getShared()** to obtain the UI context and then use the **DragController** object obtained to perform subsequent operations. 6531```ts 6532import { dragController, componentSnapshot, UIContext, DragController } from "@kit.ArkUI" 6533import { image } from '@kit.ImageKit'; 6534import { unifiedDataChannel } from '@kit.ArkData'; 6535 6536let storages = LocalStorage.getShared(); 6537 6538@Entry(storages) 6539@Component 6540struct DragControllerPage { 6541 @State pixmap: image.PixelMap|null = null 6542 private dragAction: dragController.DragAction|null = null; 6543 customBuilders:Array<CustomBuilder | DragItemInfo> = new Array<CustomBuilder | DragItemInfo>(); 6544 @Builder DraggingBuilder() { 6545 Column() { 6546 Text("DraggingBuilder") 6547 } 6548 .width(100) 6549 .height(100) 6550 .backgroundColor(Color.Blue) 6551 } 6552 6553 build() { 6554 Column() { 6555 6556 Column() { 6557 Text("Test") 6558 } 6559 .width(100) 6560 .height(100) 6561 .backgroundColor(Color.Red) 6562 6563 Button('Drag Multiple Objects').onTouch((event?:TouchEvent) => { 6564 if(event){ 6565 if (event.type == TouchType.Down) { 6566 console.info("muti drag Down by listener"); 6567 this.customBuilders.push(()=>{this.DraggingBuilder()}); 6568 this.customBuilders.push(()=>{this.DraggingBuilder()}); 6569 this.customBuilders.push(()=>{this.DraggingBuilder()}); 6570 let text = new unifiedDataChannel.Text() 6571 let unifiedData = new unifiedDataChannel.UnifiedData(text) 6572 let dragInfo: dragController.DragInfo = { 6573 pointerId: 0, 6574 data: unifiedData, 6575 extraParams: '' 6576 } 6577 try{ 6578 let uiContext: UIContext = storages.get<UIContext>('uiContext') as UIContext; 6579 this.dragAction = uiContext.getDragController().createDragAction(this.customBuilders, dragInfo) 6580 if(!this.dragAction){ 6581 console.info("listener dragAction is null"); 6582 return 6583 } 6584 this.dragAction.on('statusChange', (dragAndDropInfo)=>{ 6585 if (dragAndDropInfo.status == dragController.DragStatus.STARTED) { 6586 console.info("drag has start"); 6587 } else if (dragAndDropInfo.status == dragController.DragStatus.ENDED){ 6588 console.info("drag has end"); 6589 if (!this.dragAction) { 6590 return 6591 } 6592 this.customBuilders.splice(0, this.customBuilders.length) 6593 this.dragAction.off('statusChange') 6594 } 6595 }) 6596 this.dragAction.startDrag().then(()=>{}).catch((err:Error)=>{ 6597 console.error("start drag Error:" + err.message); 6598 }) 6599 } catch(err) { 6600 console.error("create dragAction Error:" + err.message); 6601 } 6602 } 6603 } 6604 }).margin({top:20}) 6605 } 6606 } 6607} 6608``` 6609 6610### getDragPreview<sup>11+</sup> 6611 6612getDragPreview(): dragController.DragPreview 6613 6614Obtains the **DragPreview** object, which represents the preview displayed during a drag. 6615 6616**Atomic service API**: This API can be used in atomic services since API version 12. 6617 6618**System capability**: SystemCapability.ArkUI.ArkUI.Full 6619 6620**Return value** 6621 6622| Type | Description | 6623| ------------------------------------------------------------ | ------------------------------------------------------------ | 6624| [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.| 6625 6626**Error codes**: For details about universal error codes, see [Universal Error Codes](../errorcode-universal.md). 6627 6628**Example** 6629 6630For details, see [animate](js-apis-arkui-dragController.md#animate11). 6631 6632### setDragEventStrictReportingEnabled<sup>12+</sup> 6633 6634setDragEventStrictReportingEnabled(enable: boolean): void 6635 6636Sets whether the **onDragLeave** callback of the parent component is triggered when an item is dragged from the parent to the child component. 6637 6638**Atomic service API**: This API can be used in atomic services since API version 12. 6639 6640**System capability**: SystemCapability.ArkUI.ArkUI.Full 6641 6642**Parameters** 6643 6644| Name| Type | Mandatory| Description | 6645| ------ | ------- | ---- | ------------------------------------------------------------ | 6646| 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.| 6647 6648**Example** 6649 6650```ts 6651import { UIAbility } from '@kit.AbilityKit'; 6652import { window, UIContext } from '@kit.ArkUI'; 6653 6654 export default class EntryAbility extends UIAbility { 6655 onWindowStageCreate(windowStage: window.WindowStage): void { 6656 windowStage.loadContent('pages/Index', (err, data) => { 6657 if (err.code) { 6658 return; 6659 } 6660 windowStage.getMainWindow((err, data) => { 6661 if (err.code) { 6662 return; 6663 } 6664 let windowClass: window.Window = data; 6665 let uiContext: UIContext = windowClass.getUIContext(); 6666 uiContext.getDragController().setDragEventStrictReportingEnabled(true); 6667 }); 6668 }); 6669 } 6670} 6671``` 6672### cancelDataLoading<sup>15+</sup> 6673 6674cancelDataLoading(key: string): void 6675 6676Cancels the data loading initiated by the [startDataLoading](arkui-ts/ts-universal-events-drag-drop.md#dragevent7) API. 6677 6678**Atomic service API**: This API can be used in atomic services since API version 16. 6679 6680**System capability**: SystemCapability.ArkUI.ArkUI.Full 6681 6682**Parameters** 6683 6684| Name| Type | Mandatory| Description | 6685| ------ | ------- | ---- | ------------------------------------------------------------ | 6686| 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.| 6687 6688**Error codes** 6689 6690For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 6691 6692| ID| Error Message| 6693| -------- | ------------------------------------------------------------ | 6694| 401 | Parameter error. | 6695 6696## OverlayManager<sup>12+</sup> 6697 6698In 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. 6699> **NOTE** 6700> 6701> The nodes on **OverlayManager** are above the page level, but below such components as created through **Dialog**, **Popup**, **Menu**, **BindSheet**, **BindContentCover**, and **Toast**. 6702> 6703> 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. 6704> 6705> 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. 6706 6707### addComponentContent<sup>12+</sup> 6708 6709addComponentContent(content: ComponentContent, index?: number): void 6710 6711Adds a specified **ComponentContent** node to the **OverlayManager**. 6712 6713**Atomic service API**: This API can be used in atomic services since API version 12. 6714 6715**System capability**: SystemCapability.ArkUI.ArkUI.Full 6716 6717**Parameters** 6718 6719| Name | Type | Mandatory | Description | 6720| ------- | ---------------------------------------- | ---- | ----------- | 6721| 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.| 6722| 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> 6723 6724**Example** 6725 6726```ts 6727import { ComponentContent, OverlayManager, router } from '@kit.ArkUI'; 6728 6729class Params { 6730 text: string = "" 6731 offset: Position 6732 constructor(text: string, offset: Position) { 6733 this.text = text 6734 this.offset = offset 6735 } 6736} 6737@Builder 6738function builderText(params: Params) { 6739 Column() { 6740 Text(params.text) 6741 .fontSize(30) 6742 .fontWeight(FontWeight.Bold) 6743 }.offset(params.offset) 6744} 6745 6746@Entry 6747@Component 6748struct OverlayExample { 6749 @State message: string = 'ComponentContent'; 6750 private uiContext: UIContext = this.getUIContext() 6751 private overlayNode: OverlayManager = this.uiContext.getOverlayManager() 6752 @StorageLink('contentArray') contentArray: ComponentContent<Params>[] = [] 6753 @StorageLink('componentContentIndex') componentContentIndex: number = 0 6754 @StorageLink('arrayIndex') arrayIndex: number = 0 6755 @StorageLink("componentOffset") componentOffset: Position = {x: 0, y: 80} 6756 6757 build() { 6758 Column() { 6759 Button("++componentContentIndex: " + this.componentContentIndex).onClick(()=>{ 6760 ++this.componentContentIndex 6761 }) 6762 Button("--componentContentIndex: " + this.componentContentIndex).onClick(()=>{ 6763 --this.componentContentIndex 6764 }) 6765 Button("Add ComponentContent" + this.contentArray.length).onClick(()=>{ 6766 let componentContent = new ComponentContent( 6767 this.uiContext, wrapBuilder<[Params]>(builderText), 6768 new Params(this.message + (this.contentArray.length), this.componentOffset) 6769 ) 6770 this.contentArray.push(componentContent) 6771 this.overlayNode.addComponentContent(componentContent, this.componentContentIndex) 6772 }) 6773 Button("++arrayIndex: " + this.arrayIndex).onClick(()=>{ 6774 ++this.arrayIndex 6775 }) 6776 Button("--arrayIndex: " + this.arrayIndex).onClick(()=>{ 6777 --this.arrayIndex 6778 }) 6779 Button("Delete ComponentContent" + this.arrayIndex).onClick(()=>{ 6780 if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) { 6781 let componentContent = this.contentArray.splice(this.arrayIndex, 1) 6782 this.overlayNode.removeComponentContent(componentContent.pop()) 6783 } else { 6784 console.info("Invalid arrayIndex.") 6785 } 6786 }) 6787 Button("Show ComponentContent" + this.arrayIndex).onClick(()=>{ 6788 if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) { 6789 let componentContent = this.contentArray[this.arrayIndex] 6790 this.overlayNode.showComponentContent(componentContent) 6791 } else { 6792 console.info("Invalid arrayIndex.") 6793 } 6794 }) 6795 Button("Hide ComponentContent" + this.arrayIndex).onClick(()=>{ 6796 if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) { 6797 let componentContent = this.contentArray[this.arrayIndex] 6798 this.overlayNode.hideComponentContent(componentContent) 6799 } else { 6800 console.info("Invalid arrayIndex.") 6801 } 6802 }) 6803 Button("Show All ComponentContent").onClick(()=>{ 6804 this.overlayNode.showAllComponentContents() 6805 }) 6806 Button("Hide All ComponentContent").onClick(()=>{ 6807 this.overlayNode.hideAllComponentContents() 6808 }) 6809 6810 Button("Go").onClick(()=>{ 6811 router.pushUrl({ 6812 url: 'pages/Second' 6813 }) 6814 }) 6815 } 6816 .width('100%') 6817 .height('100%') 6818 } 6819} 6820``` 6821 6822### removeComponentContent<sup>12+</sup> 6823 6824removeComponentContent(content: ComponentContent): void 6825 6826Removes a specified **ComponentContent** node from the **OverlayManager** 6827 6828**Atomic service API**: This API can be used in atomic services since API version 12. 6829 6830**System capability**: SystemCapability.ArkUI.ArkUI.Full 6831 6832**Parameters** 6833 6834| Name | Type | Mandatory | Description | 6835| ------- | ---------------------------------------- | ---- | ----------- | 6836| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | Yes | Content to remove from the **OverlayManager**.| 6837 6838**Example** 6839 6840See [addComponentContent Example](#addcomponentcontent12). 6841 6842### showComponentContent<sup>12+</sup> 6843 6844showComponentContent(content: ComponentContent): void 6845 6846Shows a specified **ComponentContent** node on the **OverlayManager**. 6847 6848**Atomic service API**: This API can be used in atomic services since API version 12. 6849 6850**System capability**: SystemCapability.ArkUI.ArkUI.Full 6851 6852**Parameters** 6853 6854| Name | Type | Mandatory | Description | 6855| ------- | ---------------------------------------- | ---- | ----------- | 6856| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | Yes | Content to show on the **OverlayManager**.| 6857 6858**Example** 6859 6860See [addComponentContent Example](#addcomponentcontent12). 6861 6862### hideComponentContent<sup>12+</sup> 6863 6864hideComponentContent(content: ComponentContent): void 6865 6866Hides a specified **ComponentContent** node on the **OverlayManager**. 6867 6868**Atomic service API**: This API can be used in atomic services since API version 12. 6869 6870**System capability**: SystemCapability.ArkUI.ArkUI.Full 6871 6872**Parameters** 6873 6874| Name | Type | Mandatory | Description | 6875| ------- | ---------------------------------------- | ---- | ----------- | 6876| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | Yes | Content to hide on the **OverlayManager**.| 6877 6878**Example** 6879 6880See [addComponentContent Example](#addcomponentcontent12). 6881 6882### showAllComponentContents<sup>12+</sup> 6883 6884showAllComponentContents(): void 6885 6886Shows all **ComponentContent** nodes on the **OverlayManager**. 6887 6888**Atomic service API**: This API can be used in atomic services since API version 12. 6889 6890**System capability**: SystemCapability.ArkUI.ArkUI.Full 6891 6892**Example** 6893 6894See [addComponentContent Example](#addcomponentcontent12). 6895 6896### hideAllComponentContents<sup>12+</sup> 6897 6898hideAllComponentContents(): void 6899 6900Hides all **ComponentContent** nodes on the **OverlayManager**. 6901 6902**Atomic service API**: This API can be used in atomic services since API version 12. 6903 6904**System capability**: SystemCapability.ArkUI.ArkUI.Full 6905 6906**Example** 6907 6908See [addComponentContent Example](#addcomponentcontent12). 6909 6910## OverlayManagerOptions<sup>15+</sup> 6911 6912Defines the options used to initialize the [OverlayManager](#overlaymanager12). 6913 6914**Atomic service API**: This API can be used in atomic services since API version 15. 6915 6916**System capability**: SystemCapability.ArkUI.ArkUI.Full 6917 6918| Name | Type | Mandatory | Description | 6919| --------------- | ---------------------- | ------------ | --------------------- | 6920| renderRootOverlay | boolean | No| Whether to render the root overlay node.<br>Default value: **true**| 6921 6922## AtomicServiceBar<sup>11+</sup> 6923 6924In 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. 6925> **NOTE** 6926> 6927> Since API version 12, the atomic service menu bar style is changed, and the following APIs are obsolete: 6928 6929### setVisible<sup>11+</sup> 6930 6931setVisible(visible: boolean): void 6932 6933Sets whether the atomic service menu bar is visible. 6934> **NOTE** 6935> 6936> 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. 6937 6938**Atomic service API**: This API can be used in atomic services since API version 11. 6939 6940**System capability**: SystemCapability.ArkUI.ArkUI.Full 6941 6942**Parameters** 6943 6944| Name| Type| Mandatory| Description| 6945| ------- | ------- | ------- | ------- | 6946| visible | boolean | Yes| Whether the atomic service menu bar is visible.| 6947 6948 6949**Example** 6950 6951```ts 6952import {UIContext, AtomicServiceBar, window } from '@kit.ArkUI'; 6953import { hilog } from '@kit.PerformanceAnalysisKit'; 6954 6955onWindowStageCreate(windowStage: window.WindowStage) { 6956 // Main window is created, set main page for this ability 6957 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 6958 windowStage.loadContent('pages/Index', (err, data) => { 6959 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 6960 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 6961 if (atomicServiceBar != undefined) { 6962 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 6963 atomicServiceBar.setVisible(false); 6964 } else { 6965 hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 6966 } 6967 }); 6968} 6969``` 6970 6971### setBackgroundColor<sup>11+</sup> 6972 6973setBackgroundColor(color:Nullable<Color | number | string>): void 6974 6975Sets the background color of the atomic service menu bar. 6976> **NOTE** 6977> 6978> The background of the atomic service menu bar is hidden by default since API version 12; its color cannot be set using this API. 6979 6980**Atomic service API**: This API can be used in atomic services since API version 12. 6981 6982**System capability**: SystemCapability.ArkUI.ArkUI.Full 6983 6984**Parameters** 6985 6986| Name| Type| Mandatory| Description| 6987| ------ | ------ | ------ | ------ | 6988| 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.| 6989 6990**Example** 6991 6992```ts 6993import {UIContext, AtomicServiceBar,window } from '@kit.ArkUI'; 6994import { hilog } from '@kit.PerformanceAnalysisKit'; 6995onWindowStageCreate(windowStage: window.WindowStage) { 6996 // Main window is created, set main page for this ability 6997 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 6998 windowStage.loadContent('pages/Index', (err, data) => { 6999 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 7000 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 7001 if (atomicServiceBar != undefined) { 7002 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 7003 atomicServiceBar.setBackgroundColor(0x88888888); 7004 } else { 7005 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 7006 } 7007 }); 7008} 7009``` 7010 7011### setTitleContent<sup>11+</sup> 7012 7013setTitleContent(content:string): void 7014 7015Sets the title content of the atomic service menu bar. 7016> **NOTE** 7017> 7018> The title of the atomic service menu bar is hidden by default since API version 12; its content cannot be set using this API. 7019 7020**Atomic service API**: This API can be used in atomic services since API version 12. 7021 7022**System capability**: SystemCapability.ArkUI.ArkUI.Full 7023 7024**Parameters** 7025 7026|Name|Type|Mandatory|Description| 7027| ------- | ------- | ------- | ------- | 7028| content | string | Yes| Title content of the atomic service menu bar.| 7029 7030**Example** 7031 7032```ts 7033import {UIContext, AtomicServiceBar,window } from '@kit.ArkUI'; 7034import { hilog } from '@kit.PerformanceAnalysisKit'; 7035 7036onWindowStageCreate(windowStage: window.WindowStage) { 7037 // Main window is created, set main page for this ability 7038 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 7039 windowStage.loadContent('pages/Index', (err, data) => { 7040 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 7041 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 7042 if (atomicServiceBar != undefined) { 7043 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 7044 atomicServiceBar.setTitleContent('text2'); 7045 } else { 7046 hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 7047 } 7048 }); 7049} 7050``` 7051 7052### setTitleFontStyle<sup>11+</sup> 7053 7054setTitleFontStyle(font:FontStyle):void 7055 7056Sets the font style of the atomic service menu bar. 7057> **NOTE** 7058> 7059> 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. 7060 7061**Atomic service API**: This API can be used in atomic services since API version 12. 7062 7063**System capability**: SystemCapability.ArkUI.ArkUI.Full 7064 7065**Parameters** 7066 7067| Name| Type| Mandatory| Description| 7068| ------ | ------ | ------ | ------ | 7069| font | [FontStyle](arkui-ts/ts-appendix-enums.md#fontstyle) | Yes| Font style of the atomic service menu bar.| 7070 7071**Example** 7072 7073```ts 7074import {UIContext, Font, AtomicServiceBar } from '@kit.ArkUI'; 7075import { hilog } from '@kit.PerformanceAnalysisKit'; 7076 7077onWindowStageCreate(windowStage: window.WindowStage) { 7078 // Main window is created, set main page for this ability 7079 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 7080 windowStage.loadContent('pages/Index', (err, data) => { 7081 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 7082 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 7083 if (atomicServiceBar != undefined) { 7084 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 7085 atomicServiceBar.setTitleFontStyle(FontStyle.Normal); 7086 } else { 7087 hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 7088 } 7089 }); 7090} 7091``` 7092 7093### setIconColor<sup>11+</sup> 7094 7095setIconColor(color:Nullable<Color | number | string>): void 7096 7097Sets the color of the atomic service icon. 7098> **NOTE** 7099> 7100> 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. 7101 7102**Atomic service API**: This API can be used in atomic services since API version 12. 7103 7104**System capability**: SystemCapability.ArkUI.ArkUI.Full 7105 7106**Parameters** 7107 7108| Name| Type| Mandatory| Description| 7109| ------- | ------- | ------- | ------- | 7110| 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.| 7111 7112 7113**Example** 7114 7115```ts 7116import {UIContext, Font, window } from '@kit.ArkUI'; 7117import { hilog } from '@kit.PerformanceAnalysisKit'; 7118 7119onWindowStageCreate(windowStage: window.WindowStage) { 7120 // Main window is created, set main page for this ability 7121 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 7122 windowStage.loadContent('pages/Index', (err, data) => { 7123 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 7124 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 7125 if (atomicServiceBar != undefined) { 7126 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 7127 atomicServiceBar.setIconColor(0x12345678); 7128 } else { 7129 hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 7130 } 7131 }); 7132} 7133``` 7134 7135### getBarRect<sup>15+</sup> 7136 7137getBarRect(): Frame 7138 7139Obtains the layout information of the atomic service menu bar relative to the window. 7140> **NOTE** 7141> 7142> The layout information includes the left and right margins of the atomic service menu bar. 7143 7144**Atomic service API**: This API can be used in atomic services since API version 15. 7145 7146**System capability**: SystemCapability.ArkUI.ArkUI.Full 7147 7148**Return value** 7149 7150| Type | Description | 7151| ----------------- | ------------- | 7152| [Frame](./js-apis-arkui-graphics.md#frame) | Size and position of the atomic service menu bar.| 7153 7154**Example** 7155 7156```ts 7157import { AtomicServiceBar } from '@kit.ArkUI'; 7158import { hilog } from '@kit.PerformanceAnalysisKit'; 7159@Entry 7160@Component 7161struct Index { 7162 build() { 7163 Button("getBarRect") 7164 .onClick(() => { 7165 let uiContext: UIContext = this.getUIContext(); 7166 let currentBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 7167 if (currentBar != undefined) { 7168 let rect = currentBar.getBarRect(); 7169 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully. x:' + 7170 rect.x + ' y:' + rect.y + ' width:' + rect.width + ' height:' + rect.height); 7171 } else { 7172 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar failed.'); 7173 } 7174 }) 7175 } 7176} 7177``` 7178 7179## KeyboardAvoidMode<sup>11+</sup> 7180 7181Enumerates the modes in which the layout responds when the keyboard is displayed. 7182 7183**System capability**: SystemCapability.ArkUI.ArkUI.Full 7184 7185| Name | Value | Description | 7186| ------ | ---- | ---------- | 7187| OFFSET | 0 | The layout moves up.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 7188| RESIZE | 1 | The layout is resized.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 7189| 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.| 7190| 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.| 7191| 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.| 7192 7193 7194## FocusController<sup>12+</sup> 7195In 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. 7196 7197### clearFocus<sup>12+</sup> 7198 7199clearFocus(): void 7200 7201Clears 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. 7202 7203**Atomic service API**: This API can be used in atomic services since API version 12. 7204 7205**System capability**: SystemCapability.ArkUI.ArkUI.Full 7206 7207**Example** 7208 7209```ts 7210@Entry 7211@Component 7212struct ClearFocusExample { 7213 @State inputValue: string = '' 7214 @State btColor: Color = Color.Blue 7215 7216 build() { 7217 Column({ space: 20 }) { 7218 Column({ space: 5 }) { 7219 Button('button1') 7220 .width(200) 7221 .height(70) 7222 .fontColor(Color.White) 7223 .focusOnTouch(true) 7224 .backgroundColor(Color.Blue) 7225 Button('button2') 7226 .width(200) 7227 .height(70) 7228 .fontColor(Color.White) 7229 .focusOnTouch(true) 7230 .backgroundColor(this.btColor) 7231 .defaultFocus(true) 7232 .onFocus(() => { 7233 this.btColor = Color.Red 7234 }) 7235 .onBlur(() => { 7236 this.btColor = Color.Blue 7237 }) 7238 Button('clearFocus') 7239 .width(200) 7240 .height(70) 7241 .fontColor(Color.White) 7242 .backgroundColor(Color.Blue) 7243 .onClick(() => { 7244 this.getUIContext().getFocusController().clearFocus() 7245 }) 7246 } 7247 } 7248 .width('100%') 7249 .height('100%') 7250 } 7251} 7252``` 7253 7254### requestFocus<sup>12+</sup> 7255 7256requestFocus(key: string): void 7257 7258Sets focus on the specified entity node in the component tree based on the component ID. This API takes effect in the current frame. 7259 7260**Atomic service API**: This API can be used in atomic services since API version 12. 7261 7262**System capability**: SystemCapability.ArkUI.ArkUI.Full 7263 7264**Parameters** 7265 7266| Name| Type| Mandatory| Description| 7267| ------- | ------- | ------- | ------- | 7268| key | string | Yes| [Component ID](arkui-ts/ts-universal-attributes-component-id.md) of the target node.| 7269 7270**Error codes** 7271 7272For details about the error codes, see [Focus Error Codes](errorcode-focus.md). 7273 7274| ID| Error Message | 7275| -------- | ----------------------------------------------- | 7276| 150001 | the component cannot be focused. | 7277| 150002 | This component has an unfocusable ancestor. | 7278| 150003 | the component is not on tree or does not exist. | 7279 7280**Example** 7281 7282```ts 7283@Entry 7284@Component 7285struct RequestExample { 7286 @State btColor: Color = Color.Blue 7287 7288 build() { 7289 Column({ space: 20 }) { 7290 Column({ space: 5 }) { 7291 Button('Button') 7292 .width(200) 7293 .height(70) 7294 .fontColor(Color.White) 7295 .focusOnTouch(true) 7296 .backgroundColor(this.btColor) 7297 .onFocus(() => { 7298 this.btColor = Color.Red 7299 }) 7300 .onBlur(() => { 7301 this.btColor = Color.Blue 7302 }) 7303 .id("testButton") 7304 7305 Divider() 7306 .vertical(false) 7307 .width("80%") 7308 .backgroundColor(Color.Black) 7309 .height(10) 7310 7311 Button('requestFocus') 7312 .width(200) 7313 .height(70) 7314 .onClick(() => { 7315 this.getUIContext().getFocusController().requestFocus("testButton") 7316 }) 7317 7318 Button('requestFocus fail') 7319 .width(200) 7320 .height(70) 7321 .onClick(() => { 7322 try { 7323 this.getUIContext().getFocusController().requestFocus("eee") 7324 } catch (error) { 7325 console.error('requestFocus failed code is ' + error.code + ' message is ' + error.message) 7326 } 7327 }) 7328 } 7329 } 7330 .width('100%') 7331 .height('100%') 7332 } 7333} 7334``` 7335 7336### activate<sup>14+</sup> 7337 7338activate(isActive: boolean, autoInactive?: boolean): void 7339 7340Sets the [focus activation state](../../ui/arkts-common-events-focus-event.md) of this page. 7341 7342**Atomic service API**: This API can be used in atomic services since API version 14. 7343 7344**System capability**: SystemCapability.ArkUI.ArkUI.Full 7345 7346**Parameters** 7347 7348| Name| Type| Mandatory| Description| 7349| ------- | ------- | ------- | ------- | 7350| isActive| boolean| Yes| Whether to enter or exit the focus activation state.| 7351| autoInactive | boolean | No| Logic for exiting the focus activation state. 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.| 7352 7353```ts 7354// 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. 7355@Entry 7356@Component 7357struct ActivateExample { 7358 aboutToAppear() { 7359 this.getUIContext().getFocusController().activate(true, false) 7360 } 7361 7362 aboutToDisappear() { 7363 this.getUIContext().getFocusController().activate(false) 7364 } 7365 7366 build() { 7367 Row() { 7368 Button('Button1') 7369 .width(200) 7370 .height(70) 7371 .defaultFocus(true) 7372 7373 Button('Button2') 7374 .width(200) 7375 .height(70) 7376 7377 Button('Button3') 7378 .width(200) 7379 .height(70) 7380 } 7381 .padding(10) 7382 .justifyContent(FlexAlign.SpaceBetween) 7383 .width(800) 7384 } 7385} 7386``` 7387 7388### setAutoFocusTransfer<sup>14+</sup> 7389 7390setAutoFocusTransfer(isAutoFocusTransfer: boolean): void; 7391 7392Sets whether the new page should automatically acquire focus during page switching. 7393 7394**Atomic service API**: This API can be used in atomic services since API version 14. 7395 7396**System capability**: SystemCapability.ArkUI.ArkUI.Full 7397 7398**Parameters** 7399 7400| Name| Type| Mandatory| Description| 7401| ------- | ------- | ------- | ------- | 7402| isAutoFocusTransfer | boolean| Yes| Whether the new page should automatically acquire focus during page switching using navigation components, 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> Default value: **true**| 7403 7404```ts 7405@CustomDialog 7406struct CustomDialogExample { 7407 controller?: CustomDialogController 7408 build() { 7409 Column() { 7410 Text('This is a custom dialog box') 7411 .fontSize(30) 7412 .height(100) 7413 Text('The dialog box should not automatically acquire focus') 7414 .fontSize(20) 7415 .height(100) 7416 Button('Close Dialog Box') 7417 .onClick(() => { 7418 if (this.controller != undefined) { 7419 this.getUIContext().getFocusController().setAutoFocusTransfer(true) 7420 this.controller.close() 7421 } 7422 }) 7423 .margin(20) 7424 } 7425 } 7426} 7427@Entry 7428@Component 7429struct CustomDialogUser { 7430 dialogController: CustomDialogController | null = new CustomDialogController({ 7431 builder: CustomDialogExample({ 7432 }), 7433 }) 7434 aboutToDisappear() { 7435 this.dialogController = null 7436 } 7437 7438 build() { 7439 Column() { 7440 Button('click me') 7441 .onClick(() => { 7442 if (this.dialogController != null) { 7443 this.getUIContext().getFocusController().setAutoFocusTransfer(false) 7444 this.dialogController.open() 7445 } 7446 }).backgroundColor(0x317aff) 7447 }.width('100%').margin({ top: 5 }) 7448 } 7449} 7450``` 7451 7452### setKeyProcessingMode<sup>15+</sup> 7453 7454setKeyProcessingMode(mode: KeyProcessingMode): void 7455 7456Sets the mode for processing key events. 7457 7458**Atomic service API**: This API can be used in atomic services since API version 15. 7459 7460**System capability**: SystemCapability.ArkUI.ArkUI.Full 7461 7462**Parameters** 7463 7464| Name| Type| Mandatory| Description| 7465| ------- | ------- | ------- | ------- | 7466| mode | [KeyProcessingMode](./arkui-ts/ts-universal-attributes-focus.md#keyprocessingmode15)| Yes| Mode for processing key events.| 7467 7468```ts 7469 7470// This example demonstrates how to set the focus behavior after the page is loaded. 7471@Entry 7472@Component 7473struct Index { 7474 7475 aboutToAppear() { 7476 this.getUIContext().getFocusController().setKeyProcessingMode(KeyProcessingMode.ANCESTOR_EVENT) 7477 } 7478 7479 build() { 7480 Row() { 7481 Row() { 7482 Button('Button1').id('Button1').onKeyEvent((event) => { 7483 console.log("Button1"); 7484 return true 7485 }) 7486 Button('Button2').id('Button2').onKeyEvent((event) => { 7487 console.log("Button2"); 7488 return true 7489 }) 7490 } 7491 .width('100%') 7492 .height('100%') 7493 .id('Row1') 7494 .onKeyEventDispatch((event) => { 7495 let context = this.getUIContext(); 7496 context.getFocusController().requestFocus('Button1'); 7497 return context.dispatchKeyEvent('Button1', event); 7498 }) 7499 } 7500 .height('100%') 7501 .width('100%') 7502 .onKeyEventDispatch((event) => { 7503 if (event.type == KeyType.Down) { 7504 let context = this.getUIContext(); 7505 context.getFocusController().requestFocus('Row1'); 7506 return context.dispatchKeyEvent('Row1', event); 7507 } 7508 return true; 7509 }) 7510 } 7511} 7512``` 7513 7514## PointerStyle<sup>12+</sup> 7515 7516type PointerStyle = pointer.PointerStyle 7517 7518Defines the pointer style. 7519 7520**Atomic service API**: This API can be used in atomic services since API version 12. 7521 7522**System capability**: SystemCapability.MultimodalInput.Input.Pointer 7523 7524|Type|Description| 7525| -- | -- | 7526|[pointer.PointerStyle](../apis-input-kit/js-apis-pointer.md#pointerstyle) |Pointer style.| 7527 7528## CursorController<sup>12+</sup> 7529In 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. 7530 7531### restoreDefault<sup>12+</sup> 7532 7533restoreDefault(): void 7534 7535Restores the default cursor style. 7536 7537**Atomic service API**: This API can be used in atomic services since API version 12. 7538 7539**System capability**: SystemCapability.ArkUI.ArkUI.Full 7540 7541**Example** 7542In this example, the **restoreDefault** API of **CursorController** is used to restore the cursor style when the cursor moves out of the green frame. 7543 7544```ts 7545import { pointer } from '@kit.InputKit'; 7546import { UIContext, CursorController } from '@kit.ArkUI'; 7547 7548@Entry 7549@Component 7550struct CursorControlExample { 7551 @State text: string = '' 7552 cursorCustom: CursorController = this.getUIContext().getCursorController(); 7553 7554 build() { 7555 Column() { 7556 Row().height(200).width(200).backgroundColor(Color.Green).position({x: 150 ,y:70}) 7557 .onHover((flag) => { 7558 if (flag) { 7559 this.cursorCustom.setCursor(pointer.PointerStyle.EAST) 7560 } else { 7561 console.info("restoreDefault"); 7562 this.cursorCustom.restoreDefault(); 7563 } 7564 }) 7565 }.width('100%') 7566 } 7567} 7568``` 7569 7570 7571### setCursor<sup>12+</sup> 7572 7573setCursor(value: PointerStyle): void 7574 7575Sets the cursor style. 7576 7577**Atomic service API**: This API can be used in atomic services since API version 12. 7578 7579**System capability**: SystemCapability.ArkUI.ArkUI.Full 7580 7581**Parameters** 7582 7583| Name | Type | Mandatory | Description | 7584| ------- | ---------------------------------------- | ---- | ------- | 7585| value | [PointerStyle](#pointerstyle12) | Yes | Cursor style.| 7586 7587**Example** 7588In 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. 7589 7590```ts 7591import { pointer } from '@kit.InputKit'; 7592import { UIContext, CursorController } from '@kit.ArkUI'; 7593 7594@Entry 7595@Component 7596struct CursorControlExample { 7597 @State text: string = '' 7598 cursorCustom: CursorController = this.getUIContext().getCursorController(); 7599 7600 build() { 7601 Column() { 7602 Row().height(200).width(200).backgroundColor(Color.Blue).position({x: 100 ,y:70}) 7603 .onHover((flag) => { 7604 if (flag) { 7605 this.cursorCustom.setCursor(pointer.PointerStyle.WEST) 7606 } else { 7607 this.cursorCustom.restoreDefault(); 7608 } 7609 }) 7610 }.width('100%') 7611 } 7612} 7613``` 7614 7615 7616## ContextMenuController<sup>12+</sup> 7617In 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. 7618 7619### close<sup>12+</sup> 7620 7621close(): void 7622 7623Closes this menu. 7624 7625**Atomic service API**: This API can be used in atomic services since API version 12. 7626 7627**System capability**: SystemCapability.ArkUI.ArkUI.Full 7628 7629**Example** 7630This example triggers the **close** API of **ContextMenuController** by a time to close the menu. 7631 7632```ts 7633import { ContextMenuController } from '@kit.ArkUI'; 7634 7635@Entry 7636@Component 7637struct Index { 7638 menu: ContextMenuController = this.getUIContext().getContextMenuController(); 7639 7640 @Builder MenuBuilder() { 7641 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 7642 Button('Test ContextMenu1 Close') 7643 Divider().strokeWidth(2).margin(5).color(Color.Black) 7644 Button('Test ContextMenu2') 7645 Divider().strokeWidth(2).margin(5).color(Color.Black) 7646 Button('Test ContextMenu3') 7647 } 7648 .width(200) 7649 .height(160) 7650 } 7651 7652 build() { 7653 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 7654 Button("Start Timer").onClick(()=> 7655 { 7656 setTimeout(() => { 7657 this.menu.close(); 7658 }, 10000); 7659 }) 7660 7661 Column() { 7662 Text("Test ContextMenu close") 7663 .fontSize(20) 7664 .width('100%') 7665 .height(500) 7666 .backgroundColor(0xAFEEEE) 7667 .textAlign(TextAlign.Center) 7668 } 7669 .bindContextMenu(this.MenuBuilder, ResponseType.LongPress) 7670 } 7671 .width('100%') 7672 .height('100%') 7673 } 7674} 7675``` 7676 7677 7678 7679## MeasureUtils<sup>12+</sup> 7680 7681In 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. 7682 7683### measureText<sup>12+</sup> 7684 7685measureText(options: MeasureOptions): number 7686 7687Measures the width of the given single-line text. 7688 7689**Atomic service API**: This API can be used in atomic services since API version 12. 7690 7691**System capability**: SystemCapability.ArkUI.ArkUI.Full 7692 7693**Parameters** 7694 7695| Name | Type | Mandatory | Description | 7696| ------- | ------------------------------- | ---- | --------- | 7697| options | [MeasureOptions](js-apis-measure.md#measureoptions) | Yes | Options of the target text.| 7698 7699**Return value** 7700 7701| Type | Description | 7702| ------------ | --------- | 7703| number | Text width.<br>**NOTE**<br>Unit: px| 7704 7705 7706**Example** 7707This example uses the **measureText** API of **MeasureUtils** to obtain the width of the **"Hello World"** text. 7708 7709```ts 7710import { MeasureUtils } from '@kit.ArkUI'; 7711 7712@Entry 7713@Component 7714struct Index { 7715 @State uiContext: UIContext = this.getUIContext(); 7716 @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils(); 7717 @State textWidth: number = this.uiContextMeasure.measureText({ 7718 textContent: "Hello World", 7719 fontSize: '50px' 7720 }) 7721 7722 build() { 7723 Row() { 7724 Column() { 7725 Text(`The width of 'Hello World': ${this.textWidth}`) 7726 } 7727 .width('100%') 7728 } 7729 .height('100%') 7730 } 7731} 7732``` 7733 7734### measureTextSize<sup>12+</sup> 7735 7736measureTextSize(options: MeasureOptions): SizeOptions 7737 7738Measures the width and height of the given single-line text. 7739 7740**Atomic service API**: This API can be used in atomic services since API version 12. 7741 7742**System capability**: SystemCapability.ArkUI.ArkUI.Full 7743 7744**Parameters** 7745 7746| Name | Type | Mandatory | Description | 7747| ------- | ------------------------------- | ---- | --------- | 7748| options | [MeasureOptions](js-apis-measure.md#measureoptions) | Yes | Options of the target text.| 7749 7750**Return value** 7751 7752| Type | Description | 7753| ------------ | --------- | 7754| [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.| 7755 7756 7757**Example** 7758This example uses the **measureTextSize** API of **MeasureUtils** to obtain the width and height of the **"Hello World"** text. 7759 7760```ts 7761import { MeasureUtils } from '@kit.ArkUI'; 7762 7763@Entry 7764@Component 7765struct Index { 7766 @State uiContext: UIContext = this.getUIContext(); 7767 @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils(); 7768 textSize : SizeOptions = this.uiContextMeasure.measureTextSize({ 7769 textContent: "Hello World", 7770 fontSize: '50px' 7771 }) 7772 build() { 7773 Row() { 7774 Column() { 7775 Text(`The width of 'Hello World': ${this.textSize.width}`) 7776 Text(`The height of 'Hello World': ${this.textSize.height}`) 7777 } 7778 .width('100%') 7779 } 7780 .height('100%') 7781 } 7782} 7783``` 7784 7785## ComponentSnapshot<sup>12+</sup> 7786 7787In 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. 7788 7789### get<sup>12+</sup> 7790 7791get(id: string, callback: AsyncCallback<image.PixelMap>, options?: componentSnapshot.SnapshotOptions): void 7792 7793Obtains the snapshot of a component that has been loaded. This API uses an asynchronous callback to return the result. 7794 7795> **NOTE** 7796> 7797> 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. 7798 7799**Atomic service API**: This API can be used in atomic services since API version 12. 7800 7801**System capability**: SystemCapability.ArkUI.ArkUI.Full 7802 7803**Parameters** 7804 7805| Name | Type | Mandatory| Description | 7806| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 7807| id | string | Yes | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.| 7808| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. | 7809| options<sup>12+</sup> | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | No | Custom settings of the snapshot.| 7810 7811**Error codes** 7812 7813For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 7814 7815| ID| Error Message | 7816| -------- | ------------------------------------------------------------ | 7817| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7818| 100001 | Invalid ID. | 7819 7820**Example** 7821 7822```ts 7823import { image } from '@kit.ImageKit'; 7824import { UIContext } from '@kit.ArkUI'; 7825 7826@Entry 7827@Component 7828struct SnapshotExample { 7829 @State pixmap: image.PixelMap | undefined = undefined 7830 uiContext: UIContext = this.getUIContext(); 7831 build() { 7832 Column() { 7833 Row() { 7834 Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5) 7835 Image($r('app.media.img')).autoResize(true).width(150).height(150).margin(5).id("root") 7836 } 7837 Button("click to generate UI snapshot") 7838 .onClick(() => { 7839 this.uiContext.getComponentSnapshot().get("root", (error: Error, pixmap: image.PixelMap) => { 7840 if (error) { 7841 console.error("error: " + JSON.stringify(error)) 7842 return; 7843 } 7844 this.pixmap = pixmap 7845 }, {scale : 2, waitUntilRenderFinished : true}) 7846 }).margin(10) 7847 } 7848 .width('100%') 7849 .height('100%') 7850 .alignItems(HorizontalAlign.Center) 7851 } 7852} 7853``` 7854 7855### get<sup>12+</sup> 7856 7857get(id: string, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap> 7858 7859Obtains the snapshot of a component that has been loaded. This API uses a promise to return the result. 7860 7861> **NOTE** 7862> 7863> 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. 7864 7865**Atomic service API**: This API can be used in atomic services since API version 12. 7866 7867**System capability**: SystemCapability.ArkUI.ArkUI.Full 7868 7869**Parameters** 7870 7871| Name| Type | Mandatory| Description | 7872| ------ | ------ | ---- | ------------------------------------------------------------ | 7873| id | string | Yes | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.| 7874| options<sup>12+</sup> | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | No | Custom settings of the snapshot.| 7875 7876**Return value** 7877 7878| Type | Description | 7879| ------------------------------------------------------------ | ---------------- | 7880| Promise<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Promise used to return the result.| 7881 7882**Error codes** 7883 7884For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 7885 7886| ID| Error Message | 7887| -------- | ------------------------------------------------------------ | 7888| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7889| 100001 | Invalid ID. | 7890 7891**Example** 7892 7893```ts 7894import { image } from '@kit.ImageKit'; 7895import { UIContext } from '@kit.ArkUI'; 7896 7897@Entry 7898@Component 7899struct SnapshotExample { 7900 @State pixmap: image.PixelMap | undefined = undefined 7901 uiContext: UIContext = this.getUIContext(); 7902 7903 build() { 7904 Column() { 7905 Row() { 7906 Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5) 7907 Image($r('app.media.icon')).autoResize(true).width(150).height(150).margin(5).id("root") 7908 } 7909 Button("click to generate UI snapshot") 7910 .onClick(() => { 7911 this.uiContext.getComponentSnapshot() 7912 .get("root", {scale : 2, waitUntilRenderFinished : true}) 7913 .then((pixmap: image.PixelMap) => { 7914 this.pixmap = pixmap 7915 }) 7916 .catch((err: Error) => { 7917 console.error("error: " + err) 7918 }) 7919 }).margin(10) 7920 } 7921 .width('100%') 7922 .height('100%') 7923 .alignItems(HorizontalAlign.Center) 7924 } 7925} 7926``` 7927 7928### createFromBuilder<sup>12+</sup> 7929 7930createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): void 7931 7932Renders 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. 7933> **NOTE** 7934> 7935> 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. 7936> 7937> 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. 7938 7939**Atomic service API**: This API can be used in atomic services since API version 12. 7940 7941**System capability**: SystemCapability.ArkUI.ArkUI.Full 7942 7943**Parameters** 7944 7945| Name | Type | Mandatory| Description | 7946| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 7947| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | Yes | Builder for the custom component.<br>**NOTE**<br>The global builder is not supported. | 7948| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. The coordinates and size of the offscreen component's drawing area can be obtained through the callback.| 7949| 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| 7950| 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**| 7951| options<sup>12+</sup> | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | No | Custom settings of the snapshot.| 7952 7953**Error codes** 7954 7955For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 7956 7957| ID| Error Message | 7958| -------- | ------------------------------------------------------------ | 7959| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7960| 100001 | The builder is not a valid build function. | 7961| 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. | 7962 7963**Example** 7964 7965```ts 7966import { image } from '@kit.ImageKit'; 7967import { UIContext } from '@kit.ArkUI'; 7968 7969@Entry 7970@Component 7971struct ComponentSnapshotExample { 7972 @State pixmap: image.PixelMap | undefined = undefined 7973 uiContext: UIContext = this.getUIContext(); 7974 @Builder 7975 RandomBuilder() { 7976 Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { 7977 Text('Test menu item 1') 7978 .fontSize(20) 7979 .width(100) 7980 .height(50) 7981 .textAlign(TextAlign.Center) 7982 Divider().height(10) 7983 Text('Test menu item 2') 7984 .fontSize(20) 7985 .width(100) 7986 .height(50) 7987 .textAlign(TextAlign.Center) 7988 } 7989 .width(100) 7990 .id("builder") 7991 } 7992 7993 build() { 7994 Column() { 7995 Button("click to generate UI snapshot") 7996 .onClick(() => { 7997 this.uiContext.getComponentSnapshot().createFromBuilder(() => { 7998 this.RandomBuilder() 7999 }, 8000 (error: Error, pixmap: image.PixelMap) => { 8001 if (error) { 8002 console.error("error: " + JSON.stringify(error)) 8003 return; 8004 } 8005 this.pixmap = pixmap 8006 }, 320, true, {scale : 2, waitUntilRenderFinished : true}) 8007 }) 8008 Image(this.pixmap) 8009 .margin(10) 8010 .height(200) 8011 .width(200) 8012 .border({ color: Color.Black, width: 2 }) 8013 }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300) 8014 } 8015} 8016``` 8017 8018### createFromBuilder<sup>12+</sup> 8019 8020createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap> 8021 8022Renders 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. 8023 8024> **NOTE** 8025> 8026> 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. 8027> 8028> 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. 8029 8030**Atomic service API**: This API can be used in atomic services since API version 12. 8031 8032**System capability**: SystemCapability.ArkUI.ArkUI.Full 8033 8034**Parameters** 8035 8036| Name | Type | Mandatory| Description | 8037| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- | 8038| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | Yes | Builder for the custom component.<br>**NOTE**<br>The global builder is not supported.| 8039 8040**Return value** 8041 8042| Type | Description | 8043| ------------------------------------------------------------ | ---------------- | 8044| Promise<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Promise used to return the result.| 8045| 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| 8046| 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**| 8047| options<sup>12+</sup> | [SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | No | Custom settings of the snapshot.| 8048 8049**Error codes** 8050 8051For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 8052 8053| ID| Error Message | 8054| -------- | ------------------------------------------------------------ | 8055| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 8056| 100001 | The builder is not a valid build function. | 8057| 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. | 8058 8059**Example** 8060 8061```ts 8062import { image } from '@kit.ImageKit'; 8063import { UIContext } from '@kit.ArkUI'; 8064 8065@Entry 8066@Component 8067struct ComponentSnapshotExample { 8068 @State pixmap: image.PixelMap | undefined = undefined 8069 uiContext: UIContext = this.getUIContext(); 8070 @Builder 8071 RandomBuilder() { 8072 Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { 8073 Text('Test menu item 1') 8074 .fontSize(20) 8075 .width(100) 8076 .height(50) 8077 .textAlign(TextAlign.Center) 8078 Divider().height(10) 8079 Text('Test menu item 2') 8080 .fontSize(20) 8081 .width(100) 8082 .height(50) 8083 .textAlign(TextAlign.Center) 8084 } 8085 .width(100) 8086 .id("builder") 8087 } 8088 build() { 8089 Column() { 8090 Button("click to generate UI snapshot") 8091 .onClick(() => { 8092 this.uiContext.getComponentSnapshot() 8093 .createFromBuilder(() => { 8094 this.RandomBuilder() 8095 }, 320, true, {scale : 2, waitUntilRenderFinished : true}) 8096 .then((pixmap: image.PixelMap) => { 8097 this.pixmap = pixmap 8098 }) 8099 .catch((err: Error) => { 8100 console.error("error: " + err) 8101 }) 8102 }) 8103 Image(this.pixmap) 8104 .margin(10) 8105 .height(200) 8106 .width(200) 8107 .border({ color: Color.Black, width: 2 }) 8108 }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300) 8109 } 8110} 8111``` 8112 8113### getSync<sup>12+</sup> 8114 8115getSync(id: string, options?: componentSnapshot.SnapshotOptions): image.PixelMap 8116 8117Obtains 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. 8118 8119> **NOTE** 8120> 8121> 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. 8122 8123**Atomic service API**: This API can be used in atomic services since API version 12. 8124 8125**System capability**: SystemCapability.ArkUI.ArkUI.Full 8126 8127**Parameters** 8128 8129| Name | Type | Mandatory | Description | 8130| ---- | ------ | ---- | ---------------------------------------- | 8131| id | string | Yes | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.| 8132| options | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | No | Custom settings of the snapshot.| 8133 8134**Return value** 8135 8136| Type | Description | 8137| ----------------------------- | -------- | 8138| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Promise used to return the result.| 8139 8140**Error codes** 8141 8142For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 8143 8144| ID | Error Message | 8145| ------ | ------------------- | 8146| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 8147| 100001 | Invalid ID. | 8148| 160002 | Timeout. | 8149 8150**Example** 8151 8152```ts 8153import { image } from '@kit.ImageKit'; 8154import { UIContext } from '@kit.ArkUI'; 8155 8156@Entry 8157@Component 8158struct SnapshotExample { 8159 @State pixmap: image.PixelMap | undefined = undefined 8160 8161 build() { 8162 Column() { 8163 Row() { 8164 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 8165 Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root") 8166 } 8167 Button("click to generate UI snapshot") 8168 .onClick(() => { 8169 try { 8170 let pixelmap = this.getUIContext().getComponentSnapshot().getSync("root", {scale : 2, waitUntilRenderFinished : true}) 8171 this.pixmap = pixelmap 8172 } catch (error) { 8173 console.error("getSync errorCode: " + error.code + " message: " + error.message) 8174 } 8175 }).margin(10) 8176 } 8177 .width('100%') 8178 .height('100%') 8179 .alignItems(HorizontalAlign.Center) 8180 } 8181} 8182``` 8183 8184### getWithUniqueId<sup>15+</sup> 8185 8186getWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap> 8187 8188Obtains 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. 8189 8190> **NOTE** 8191> 8192> 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. 8193 8194**Atomic service API**: This API can be used in atomic services since API version 15. 8195 8196**System capability**: SystemCapability.ArkUI.ArkUI.Full 8197 8198**Parameters** 8199 8200| Name | Type | Mandatory | Description | 8201| ---- | ------ | ---- | ---------------------------------------- | 8202| uniqueId | number | Yes | [Unique ID](js-apis-arkui-frameNode.md#getuniqueid12) of the target component.| 8203| options | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | No | Custom settings of the snapshot.| 8204 8205**Return value** 8206 8207| Type | Description | 8208| ------------------------------------------------------------ | ---------------- | 8209| Promise<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | Promise used to return the result.| 8210 8211**Error codes** 8212 8213For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 8214 8215| ID| Error Message | 8216| -------- | ------------------------------------------------------------ | 8217| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 8218| 100001 | Invalid ID. | 8219 8220**Example** 8221 8222```ts 8223import { NodeController, FrameNode, typeNode } from '@kit.ArkUI'; 8224import { image } from '@kit.ImageKit'; 8225import { UIContext } from '@kit.ArkUI'; 8226 8227class MyNodeController extends NodeController { 8228 public node: FrameNode | null = null; 8229 8230 public imageNode: FrameNode | null = null; 8231 8232 makeNode(uiContext: UIContext): FrameNode | null { 8233 this.node = new FrameNode(uiContext); 8234 this.node.commonAttribute.width('100%').height('100%') 8235 8236 let image = typeNode.createNode(uiContext, 'Image'); 8237 image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true) 8238 this.imageNode = image; 8239 8240 this.node.appendChild(image); 8241 return this.node; 8242 } 8243} 8244 8245@Entry 8246@Component 8247struct SnapshotExample { 8248 private myNodeController: MyNodeController = new MyNodeController(); 8249 8250 @State pixmap: image.PixelMap | undefined = undefined 8251 8252 build() { 8253 Column() { 8254 Row() { 8255 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 8256 NodeContainer(this.myNodeController).width(200).height(200).margin(5) 8257 } 8258 Button("UniqueId get snapshot") 8259 .onClick(() => { 8260 try { 8261 this.getUIContext() 8262 .getComponentSnapshot() 8263 .getWithUniqueId(this.myNodeController.imageNode?.getUniqueId(), {scale: 2, waitUntilRenderFinished: true}) 8264 .then((pixmap: image.PixelMap) => { 8265 this.pixmap = pixmap 8266 }) 8267 .catch((err: Error) => { 8268 console.log("error: " + err) 8269 }) 8270 } catch (error) { 8271 console.error("UniqueId get snapshot Error: " + JSON.stringify(error)) 8272 } 8273 }).margin(10) 8274 } 8275 .width('100%') 8276 .height('100%') 8277 .alignItems(HorizontalAlign.Center) 8278 } 8279} 8280``` 8281 8282### getSyncWithUniqueId<sup>15+</sup> 8283 8284getSyncWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): image.PixelMap 8285 8286Obtains 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. 8287 8288> **NOTE** 8289> 8290> 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. 8291 8292**Atomic service API**: This API can be used in atomic services since API version 15. 8293 8294**System capability**: SystemCapability.ArkUI.ArkUI.Full 8295 8296**Parameters** 8297 8298| Name | Type | Mandatory | Description | 8299| ---- | ------ | ---- | ---------------------------------------- | 8300| uniqueId | number | Yes | [Unique ID](js-apis-arkui-frameNode.md#getuniqueid12) of the target component.| 8301| options | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | No | Custom settings of the snapshot.| 8302 8303**Return value** 8304 8305| Type | Description | 8306| ----------------------------- | -------- | 8307| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | Promise used to return the result.| 8308 8309**Error codes** 8310 8311For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 8312 8313| ID | Error Message | 8314| ------ | ------------------- | 8315| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 8316| 100001 | Invalid ID. | 8317| 160002 | Timeout. | 8318 8319**Example** 8320 8321```ts 8322import { NodeController, FrameNode, typeNode } from '@kit.ArkUI'; 8323import { image } from '@kit.ImageKit'; 8324import { UIContext } from '@kit.ArkUI'; 8325 8326class MyNodeController extends NodeController { 8327 public node: FrameNode | null = null; 8328 8329 public imageNode: FrameNode | null = null; 8330 8331 makeNode(uiContext: UIContext): FrameNode | null { 8332 this.node = new FrameNode(uiContext); 8333 this.node.commonAttribute.width('100%').height('100%') 8334 8335 let image = typeNode.createNode(uiContext, 'Image'); 8336 image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true) 8337 this.imageNode = image; 8338 8339 this.node.appendChild(image); 8340 return this.node; 8341 } 8342} 8343 8344@Entry 8345@Component 8346struct SnapshotExample { 8347 private myNodeController: MyNodeController = new MyNodeController(); 8348 8349 @State pixmap: image.PixelMap | undefined = undefined 8350 8351 build() { 8352 Column() { 8353 Row() { 8354 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 8355 NodeContainer(this.myNodeController).width(200).height(200).margin(5) 8356 } 8357 Button("UniqueId getSync snapshot") 8358 .onClick(() => { 8359 try { 8360 this.pixmap = this.getUIContext() 8361 .getComponentSnapshot() 8362 .getSyncWithUniqueId(this.myNodeController.imageNode?.getUniqueId(), {scale: 2, waitUntilRenderFinished: true}) 8363 } catch (error) { 8364 console.error("UniqueId getSync snapshot Error: " + JSON.stringify(error)) 8365 } 8366 }).margin(10) 8367 } 8368 .width('100%') 8369 .height('100%') 8370 .alignItems(HorizontalAlign.Center) 8371 } 8372} 8373``` 8374 8375## FrameCallback<sup>12+</sup> 8376 8377Implements 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. 8378 8379### onFrame<sup>12+</sup> 8380 8381onFrame(frameTimeInNano: number): void 8382 8383Called when the next frame is rendered. 8384 8385**Atomic service API**: This API can be used in atomic services since API version 12. 8386 8387**System capability**: SystemCapability.ArkUI.ArkUI.Full 8388 8389**Parameters** 8390 8391| Name | Type | Mandatory| Description | 8392| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- | 8393| frameTimeInNano | number | Yes | Time when the rendering of the next frame starts, in nanoseconds.| 8394 8395**Example** 8396 8397```ts 8398import {FrameCallback } from '@kit.ArkUI'; 8399 8400class MyFrameCallback extends FrameCallback { 8401 private tag: string; 8402 8403 constructor(tag: string) { 8404 super() 8405 this.tag = tag; 8406 } 8407 8408 onFrame(frameTimeNanos: number) { 8409 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 8410 } 8411} 8412 8413@Entry 8414@Component 8415struct Index { 8416 build() { 8417 Row() { 8418 Column() { 8419 Button('Invoke postFrameCallback') 8420 .onClick(() => { 8421 this.getUIContext().postFrameCallback(new MyFrameCallback("normTask")); 8422 }) 8423 Button('Invoke postDelayedFrameCallback') 8424 .onClick(() => { 8425 this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5); 8426 }) 8427 } 8428 .width('100%') 8429 } 8430 .height('100%') 8431 } 8432} 8433``` 8434 8435### onIdle<sup>12+</sup> 8436 8437onIdle(timeLeftInNano: number): void 8438 8439Called 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. 8440 8441**Atomic service API**: This API can be used in atomic services since API version 12. 8442 8443**System capability**: SystemCapability.ArkUI.ArkUI.Full 8444 8445**Parameters** 8446 8447| Name | Type | Mandatory| Description | 8448| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- | 8449| timeLeftInNano | number | Yes | Remaining idle time for the current frame.| 8450 8451**Example** 8452 8453```ts 8454import { FrameCallback } from '@ohos.arkui.UIContext'; 8455 8456class MyIdleCallback extends FrameCallback { 8457 private tag: string; 8458 8459 constructor(tag: string) { 8460 super() 8461 this.tag = tag; 8462 } 8463 8464 onIdle(timeLeftInNano: number) { 8465 console.info('MyIdleCallback ' + this.tag + ' ' + timeLeftInNano.toString()); 8466 } 8467} 8468 8469@Entry 8470@Component 8471struct Index { 8472 build() { 8473 Row() { 8474 Column() { 8475 Button('Invoke postFrameCallback') 8476 .onClick(() => { 8477 this.getUIContext().postFrameCallback(new MyIdleCallback("normTask")); 8478 }) 8479 Button('Invoke postDelayedFrameCallback') 8480 .onClick(() => { 8481 this.getUIContext().postDelayedFrameCallback(new MyIdleCallback("delayTask"), 5); 8482 }) 8483 } 8484 .width('100%') 8485 } 8486 .height('100%') 8487 } 8488} 8489``` 8490 8491## DynamicSyncScene<sup>12+</sup> 8492 8493In 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. 8494 8495### setFrameRateRange<sup>12+</sup> 8496 8497setFrameRateRange(range: ExpectedFrameRateRange): void 8498 8499Sets the expected frame rate range. 8500 8501While 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. 8502 8503**Atomic service API**: This API can be used in atomic services since API version 12. 8504 8505**System capability**: SystemCapability.ArkUI.ArkUI.Full 8506 8507**Parameters** 8508 8509| Name | Type | Mandatory | Description | 8510| -------- | ---------- | ---- | ---- | 8511| 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}**| 8512 8513**Example** 8514 8515```ts 8516import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI' 8517 8518@Entry 8519@Component 8520struct Frame { 8521 @State ANIMATION:ExpectedFrameRateRange = {min:0, max:120, expected: 90} 8522 @State GESTURE:ExpectedFrameRateRange = {min:0, max:120, expected: 30} 8523 private scenes: SwiperDynamicSyncScene[] = [] 8524 8525 build() { 8526 Column() { 8527 Text("Animation"+ JSON.stringify(this.ANIMATION)) 8528 Text("Responsive"+ JSON.stringify(this.GESTURE)) 8529 Row(){ 8530 Swiper() { 8531 Text("one") 8532 Text("two") 8533 Text("three") 8534 } 8535 .width('100%') 8536 .height('300vp') 8537 .id("dynamicSwiper") 8538 .backgroundColor(Color.Blue) 8539 .autoPlay(true) 8540 .onAppear(()=>{ 8541 this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[] 8542 }) 8543 } 8544 8545 Button("set frame") 8546 .onClick(()=>{ 8547 this.scenes.forEach((scenes: SwiperDynamicSyncScene) => { 8548 8549 if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) { 8550 scenes.setFrameRateRange(this.ANIMATION) 8551 } 8552 8553 if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) { 8554 scenes.setFrameRateRange(this.GESTURE) 8555 } 8556 }); 8557 }) 8558 } 8559 } 8560} 8561``` 8562 8563### getFrameRateRange<sup>12+</sup> 8564 8565getFrameRateRange(): ExpectedFrameRateRange 8566 8567Obtains the expected frame rate range. 8568 8569**Atomic service API**: This API can be used in atomic services since API version 12. 8570 8571**System capability**: SystemCapability.ArkUI.ArkUI.Full 8572 8573**Return value** 8574 8575| Type | Description | 8576| ------------------- | ------- | 8577| [ExpectedFrameRateRange](../apis-arkui/arkui-ts/ts-explicit-animation.md#expectedframeraterange11) | Expected frame rate range.| 8578 8579**Example** 8580 8581```ts 8582import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI' 8583 8584@Entry 8585@Component 8586struct Frame { 8587 @State ANIMATION:ExpectedFrameRateRange = {min:0, max:120, expected: 90} 8588 @State GESTURE:ExpectedFrameRateRange = {min:0, max:120, expected: 30} 8589 private scenes: SwiperDynamicSyncScene[] = [] 8590 8591 build() { 8592 Column() { 8593 Text("Animation"+ JSON.stringify(this.ANIMATION)) 8594 Text("Responsive"+ JSON.stringify(this.GESTURE)) 8595 Row(){ 8596 Swiper() { 8597 Text("one") 8598 Text("two") 8599 Text("three") 8600 } 8601 .width('100%') 8602 .height('300vp') 8603 .id("dynamicSwiper") 8604 .backgroundColor(Color.Blue) 8605 .autoPlay(true) 8606 .onAppear(()=>{ 8607 this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[] 8608 }) 8609 } 8610 8611 Button("set frame") 8612 .onClick(()=>{ 8613 this.scenes.forEach((scenes: SwiperDynamicSyncScene) => { 8614 8615 if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) { 8616 scenes.setFrameRateRange(this.ANIMATION) 8617 scenes.getFrameRateRange() 8618 } 8619 8620 if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) { 8621 scenes.setFrameRateRange(this.GESTURE) 8622 scenes.getFrameRateRange() 8623 } 8624 }); 8625 }) 8626 } 8627 } 8628} 8629``` 8630## SwiperDynamicSyncScene<sup>12+</sup> 8631 8632Inherits from [DynamicSyncScene](#dynamicsyncscene12) and represents the dynamic sync scene of the **Swiper** component. 8633 8634**Atomic service API**: This API can be used in atomic services since API version 12. 8635 8636**System capability**: SystemCapability.ArkUI.ArkUI.Full 8637 8638| Name | Type | Read Only| Optional| Description | 8639| --------- | --------------------------------------------------------- | ---- | ---- | ---------------------------------- | 8640| type | [SwiperDynamicSyncSceneType](#swiperdynamicsyncscenetype12) | Yes | No | Dynamic sync scene of the **Swiper** component. | 8641 8642## SwiperDynamicSyncSceneType<sup>12+</sup> 8643 8644Enumerates the dynamic sync scene types. 8645 8646**Atomic service API**: This API can be used in atomic services since API version 12. 8647 8648**System capability**: SystemCapability.ArkUI.ArkUI.Full 8649 8650| Name | Value | Description | 8651| -------- | ---- | ---------------------- | 8652| GESTURE | 0 | Gesture operation.| 8653| ANIMATION | 1 | Animation transition.| 8654 8655## MarqueeDynamicSyncScene<sup>14+</sup> 8656 8657Inherits from [DynamicSyncScene](#dynamicsyncscene12) and represents the dynamic sync scene of the [Marquee](arkui-ts/ts-basic-components-marquee.md) component. 8658 8659**Atomic service API**: This API can be used in atomic services since API version 14. 8660 8661**System capability**: SystemCapability.ArkUI.ArkUI.Full 8662 8663| Name | Type | Read Only| Optional| Description | 8664| --------- | --------------------------------------------------------- | ---- | ---- | ---------------------------------- | 8665| type | [MarqueeDynamicSyncSceneType](#marqueedynamicsyncscenetype14) | Yes | No | Dynamic sync scene of the **Marquee** component. | 8666 8667## MarqueeDynamicSyncSceneType<sup>14+</sup> 8668 8669Enumerates the dynamic sync scene types for the **Marquee** component. 8670 8671**Atomic service API**: This API can be used in atomic services since API version 14. 8672 8673**System capability**: SystemCapability.ArkUI.ArkUI.Full 8674 8675| Name | Value | Description | 8676| -------- | ---- | ---------------------- | 8677| ANIMATION | 1 | Animation transition.| 8678 8679**Example** 8680 8681```ts 8682import { MarqueeDynamicSyncSceneType, MarqueeDynamicSyncScene } from '@kit.ArkUI' 8683 8684@Entry 8685@Component 8686struct MarqueeExample { 8687 @State start: boolean = false 8688 @State src: string = '' 8689 @State marqueeText: string = 'Running Marquee' 8690 private fromStart: boolean = true 8691 private step: number = 10 8692 private loop: number = Number.POSITIVE_INFINITY 8693 controller: TextClockController = new TextClockController() 8694 convert2time(value: number): string{ 8695 let date = new Date(Number(value+'000')); 8696 let hours = date.getHours().toString().padStart(2, '0'); 8697 let minutes = date.getMinutes().toString().padStart(2, '0'); 8698 let seconds = date.getSeconds().toString().padStart(2, '0'); 8699 return hours+ ":" + minutes + ":" + seconds; 8700 } 8701 @State ANIMATION: ExpectedFrameRateRange = {min:0, max:120, expected:30} 8702 private scenes: MarqueeDynamicSyncScene[] = [] 8703 8704 build() { 8705 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 8706 Marquee({ 8707 start: this.start, 8708 step: this.step, 8709 loop: this.loop, 8710 fromStart: this.fromStart, 8711 src: this.marqueeText + this.src 8712 }) 8713 .marqueeUpdateStrategy(MarqueeUpdateStrategy.PRESERVE_POSITION) 8714 .width(300) 8715 .height(80) 8716 .fontColor('#FFFFFF') 8717 .fontSize(48) 8718 .fontWeight(700) 8719 .backgroundColor('#182431') 8720 .margin({ bottom: 40 }) 8721 .id('dynamicMarquee') 8722 .onAppear(()=>{ 8723 this.scenes = this.getUIContext().requireDynamicSyncScene('dynamicMarquee') as MarqueeDynamicSyncScene[] 8724 }) 8725 Button('Start') 8726 .onClick(() => { 8727 this.start = true 8728 this.controller.start() 8729 this.scenes.forEach((scenes: MarqueeDynamicSyncScene) => { 8730 if (scenes.type == MarqueeDynamicSyncSceneType.ANIMATION) { 8731 scenes.setFrameRateRange(this.ANIMATION) 8732 } 8733 }); 8734 }) 8735 .width(120) 8736 .height(40) 8737 .fontSize(16) 8738 .fontWeight(500) 8739 .backgroundColor('#007DFF') 8740 TextClock({ timeZoneOffset: -8, controller: this.controller }) 8741 .format('hms') 8742 .onDateChange((value: number) => { 8743 this.src = this.convert2time(value); 8744 }) 8745 .margin(20) 8746 .fontSize(30) 8747 } 8748 .width('100%') 8749 .height('100%') 8750 } 8751} 8752``` 8753