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