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