1# Class (UIContext) 2<!--Kit: ArkUI--> 3<!--Subsystem: ArkUI--> 4<!--Owner: @xiang-shouxing--> 5<!--Designer: @xiang-shouxing--> 6<!--Tester: @sally__--> 7<!--Adviser: @HelloCrease--> 8 9Implements a **UIContext** instance. 10 11> **NOTE** 12> 13> - 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. 14> 15> - You can preview how this component looks on a real device, but not in DevEco Studio Previewer. 16> 17> - In the following API examples, you must first use [getUIContext()](arkts-apis-window-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**. 18 19**Example** 20 21The following example demonstrates two methods to obtain a **UIContext** instance. 22 23```ts 24// Both approaches return identical UIContext instances. 25//index.ets 26import { UIContext } from '@kit.ArkUI'; 27 28@Entry 29@Component 30struct Index { 31 build() { 32 Column() { 33 Button("Button") 34 .onClick(()=>{ 35 // Approach 1: using the built-in component method 36 this.getUIContext() 37 // Additional logic 38 }) 39 } 40 } 41} 42 43//EntryAbility.ets 44import { AbilityConstant, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; 45import { hilog } from '@kit.PerformanceAnalysisKit'; 46import { window } from '@kit.ArkUI'; 47 48const DOMAIN = 0x0000; 49 50export default class EntryAbility extends UIAbility { 51 onWindowStageCreate(windowStage: window.WindowStage): void { 52 // Approach 2: using ohos.window 53 windowStage.getMainWindowSync().getUIContext() 54 // Additional logic 55 } 56} 57``` 58 59## isAvailable<sup>20+</sup> 60 61isAvailable(): boolean 62 63Checks whether the UI instance corresponding to this **UIContext** object is valid. The **UIContext** object can be obtained using the [getUIContext](arkts-apis-window-Window.md#getuicontext10) API. A UI instance is considered valid when the backend UI instance exists. UIContext objects created using **new UIContext()** have no corresponding UI instance. After multiple [loadContent](arkts-apis-window-Window.md#loadcontent9) operations, old UI instances become invalid. In multi-window scenarios, when a window is closed, its UI instance becomes invalid. In summary, a UIContext object is invalid when it has no corresponding backend UI instance. 64 65**Atomic service API**: This API can be used in atomic services since API version 20. 66 67**System capability**: SystemCapability.ArkUI.ArkUI.Full 68 69**Return value** 70 71| Type | Description | 72| ------------- | ----------- | 73| boolean | Whether the UI instance corresponding to the current **UIContext** object is valid. The value **true** means that the UI instance is valid, and **false** means the opposite.| 74 75**Example** 76 77```ts 78import { UIContext } from '@kit.ArkUI' 79 80@Entry 81@Component 82struct UIContextCompare { 83 @State result1: string = "" 84 @State result2: string = "" 85 86 build() { 87 Column() { 88 Text("getUIContext() result: " + this.result1) 89 .fontSize(20) 90 .margin(10) 91 92 Text("new UIContext() result: " + this.result2) 93 .fontSize(20) 94 .margin(10) 95 96 Divider().margin(20) 97 98 Button("getUIContext()") 99 .width("70%") 100 .height(50) 101 .margin(10) 102 .onClick(() => { 103 try { 104 const ctx: UIContext = this.getUIContext(); 105 const available: boolean = ctx.isAvailable(); 106 this.result1 = `Status: ${available} (Valid UI instance)`; 107 console.log("getUIContext test:", available); 108 } catch (e) { 109 this.result1 = "Error: " + (e instanceof Error ? e.message : String(e)); 110 } 111 }) 112 113 Button("new UIContext()") 114 .width("70%") 115 .height(50) 116 .margin(10) 117 .onClick(() => { 118 try { 119 const ctx: UIContext = new UIContext(); 120 const available: boolean = ctx.isAvailable(); 121 this.result2 = `Status: ${available} (Invalid UI instance)`; 122 console.log("new UIContext test:", available); 123 } catch (e) { 124 this.result2 = "Error: " + (e instanceof Error ? e.message : String(e)); 125 } 126 }) 127 } 128 .width("100%") 129 .height("100%") 130 .padding(20) 131 } 132} 133``` 134 135## getFont 136 137getFont(): Font 138 139Obtains a **Font** object. 140 141**Atomic service API**: This API can be used in atomic services since API version 11. 142 143**System capability**: SystemCapability.ArkUI.ArkUI.Full 144 145**Return value** 146 147| Type | Description | 148| ------------- | ----------- | 149| [Font](./arkts-apis-uicontext-font.md) | **Font** object.| 150 151**Example** 152 153See the example for [Font](arkts-apis-uicontext-font.md). 154 155## getComponentUtils 156 157getComponentUtils(): ComponentUtils 158 159Obtains the **ComponentUtils** object. 160 161**Atomic service API**: This API can be used in atomic services since API version 11. 162 163**System capability**: SystemCapability.ArkUI.ArkUI.Full 164 165**Return value** 166 167| Type | Description | 168| --------------------------------- | --------------------- | 169| [ComponentUtils](arkts-apis-uicontext-componentutils.md) | **ComponentUtils** object.| 170 171**Example** 172 173See the example for [getComponentUtils](js-apis-arkui-componentUtils.md). 174 175## getUIInspector 176 177getUIInspector(): UIInspector 178 179Obtains the **UIInspector** object. 180 181**Atomic service API**: This API can be used in atomic services since API version 11. 182 183**System capability**: SystemCapability.ArkUI.ArkUI.Full 184 185**Return value** 186 187| Type | Description | 188| --------------------------- | ------------------ | 189| [UIInspector](./arkts-apis-uicontext-uiinspector.md) | **UIInspector** object.| 190 191**Example** 192 193See the example for [UIInspector](./arkts-apis-uicontext-uiinspector.md). 194 195## getUIObserver<sup>11+</sup> 196 197getUIObserver(): UIObserver 198 199Obtains the **UIObserver** object. 200 201**Atomic service API**: This API can be used in atomic services since API version 12. 202 203**System capability**: SystemCapability.ArkUI.ArkUI.Full 204 205**Return value** 206 207| Type | Description | 208| --------------------------- | ------------------ | 209| [UIObserver](./arkts-apis-uicontext-uiobserver.md) | **UIObserver** object.| 210 211**Example** 212 213```ts 214@Component 215struct PageOne { 216 build() { 217 NavDestination() { 218 Text("pageOne") 219 }.title("pageOne") 220 } 221} 222 223@Entry 224@Component 225struct Index { 226 private stack: NavPathStack = new NavPathStack(); 227 228 @Builder 229 PageBuilder(name: string) { 230 PageOne() 231 } 232 233 aboutToAppear() { 234 this.getUIContext().getUIObserver().on('navDestinationUpdate', (info) => { 235 console.info('NavDestination state update', JSON.stringify(info)); 236 }); 237 } 238 239 aboutToDisappear() { 240 this.getUIContext().getUIObserver().off('navDestinationUpdate'); 241 } 242 243 build() { 244 Column() { 245 Navigation(this.stack) { 246 Button("push").onClick(() => { 247 this.stack.pushPath({ name: "pageOne" }); 248 }) 249 } 250 .title("Navigation") 251 .navDestination(this.PageBuilder) 252 } 253 .width('100%') 254 .height('100%') 255 } 256} 257``` 258 259## getMediaQuery 260 261getMediaQuery(): MediaQuery 262 263Obtains a **MediaQuery** object. 264 265**Atomic service API**: This API can be used in atomic services since API version 11. 266 267**System capability**: SystemCapability.ArkUI.ArkUI.Full 268 269**Return value** 270 271| Type | Description | 272| ------------------------- | ----------------- | 273| [MediaQuery](arkts-apis-uicontext-mediaquery.md) | **MediaQuery** object.| 274 275**Example** 276 277See the [mediaquery Example](js-apis-mediaquery.md#example). 278 279## getRouter 280 281getRouter(): Router 282 283Obtains a **Router** object. 284 285**Atomic service API**: This API can be used in atomic services since API version 11. 286 287**System capability**: SystemCapability.ArkUI.ArkUI.Full 288 289**Return value** 290 291| Type | Description | 292| ----------------- | ------------- | 293| [Router](arkts-apis-uicontext-router.md) | **Router** object.| 294 295**Example** 296 297See the example for [pushUrl](arkts-apis-uicontext-router.md#pushurl). 298 299## getPromptAction 300 301getPromptAction(): PromptAction 302 303Obtains a **PromptAction** object. 304 305**Atomic service API**: This API can be used in atomic services since API version 11. 306 307**System capability**: SystemCapability.ArkUI.ArkUI.Full 308 309**Return value** 310 311| Type | Description | 312| ----------------------------- | ------------------- | 313| [PromptAction](arkts-apis-uicontext-promptaction.md) | **PromptAction** object.| 314 315**Example** 316 317See the example for [PromptAction](arkts-apis-uicontext-promptaction.md). 318 319## getOverlayManager<sup>12+</sup> 320 321getOverlayManager(): OverlayManager 322 323Obtains the **OverlayManager** object. 324 325**Atomic service API**: This API can be used in atomic services since API version 12. 326 327**System capability**: SystemCapability.ArkUI.ArkUI.Full 328 329**Return value** 330 331| Type | Description | 332| ----------------------------- | ------------------- | 333| [OverlayManager](arkts-apis-uicontext-overlaymanager.md) | **OverlayManager** instance obtained.| 334 335**Example** 336 337See the example for [OverlayManager](arkts-apis-uicontext-overlaymanager.md). 338 339## setOverlayManagerOptions<sup>15+</sup> 340 341setOverlayManagerOptions(options: OverlayManagerOptions): boolean 342 343Sets the parameters for [OverlayManager](arkts-apis-uicontext-overlaymanager.md). This API initializes the parameters of the **OverlayManager** before using its capabilities, including properties such as whether to render the overlay root node. It must be called before **getOverlayManager** and takes effect only once. 344 345**Atomic service API**: This API can be used in atomic services since API version 15. 346 347**System capability**: SystemCapability.ArkUI.ArkUI.Full 348 349**Parameters** 350 351| Name | Type | Mandatory | Description | 352| ----- | ---------------------------------------- | ---- | ------------------------------------- | 353| options | [OverlayManagerOptions](arkts-apis-uicontext-i.md#overlaymanageroptions15) | Yes| Parameters for **OverlayManager**.| 354 355**Return value** 356 357| Type | Description | 358| ------- | -------------- | 359| boolean | Whether the setting is successful.<br>Returns **true** if the setting is successful; returns **false** otherwise.| 360 361**Example** 362 363See the example for [OverlayManager](arkts-apis-uicontext-overlaymanager.md). 364 365## getOverlayManagerOptions<sup>15+</sup> 366 367getOverlayManagerOptions(): OverlayManagerOptions 368 369Obtains the current parameters of [OverlayManager](arkts-apis-uicontext-overlaymanager.md). 370 371**Atomic service API**: This API can be used in atomic services since API version 15. 372 373**System capability**: SystemCapability.ArkUI.ArkUI.Full 374 375**Return value** 376 377| Type | Description | 378| ----------------------------- | ------------------- | 379| [OverlayManagerOptions](arkts-apis-uicontext-i.md#overlaymanageroptions15) | Current parameters of **OverlayManager**.| 380 381**Example** 382 383See the example for [OverlayManager](arkts-apis-uicontext-overlaymanager.md). 384 385## animateTo 386 387animateTo(value: AnimateParam, event: () => void): void 388 389Applies a transition animation for state changes. 390 391**Atomic service API**: This API can be used in atomic services since API version 11. 392 393**System capability**: SystemCapability.ArkUI.ArkUI.Full 394 395**Parameters** 396 397| Name | Type | Mandatory | Description | 398| ----- | ---------------------------------------- | ---- | ------------------------------------- | 399| value | [AnimateParam](arkui-ts/ts-explicit-animation.md#animateparam) | Yes | Animation settings. | 400| event | () => void | Yes | Closure function that displays the animation. The system automatically inserts the transition animation if the state changes in the closure function.| 401 402**Example** 403 404```ts 405// xxx.ets 406@Entry 407@Component 408struct AnimateToExample { 409 @State widthSize: number = 250; 410 @State heightSize: number = 100; 411 @State rotateAngle: number = 0; 412 private flag: boolean = true; 413 uiContext: UIContext | undefined = undefined; 414 415 aboutToAppear() { 416 this.uiContext = this.getUIContext(); 417 if (!this.uiContext) { 418 console.warn("no uiContext"); 419 return; 420 } 421 } 422 423 build() { 424 Column() { 425 Button('change size') 426 .width(this.widthSize) 427 .height(this.heightSize) 428 .margin(30) 429 .onClick(() => { 430 if (this.flag) { 431 this.uiContext?.animateTo({ 432 duration: 2000, 433 curve: Curve.EaseOut, 434 iterations: 3, 435 playMode: PlayMode.Normal, 436 onFinish: () => { 437 console.info('play end'); 438 } 439 }, () => { 440 this.widthSize = 150; 441 this.heightSize = 60; 442 }); 443 } else { 444 this.uiContext?.animateTo({}, () => { 445 this.widthSize = 250; 446 this.heightSize = 100; 447 }); 448 } 449 this.flag = !this.flag; 450 }) 451 Button('stop rotating') 452 .margin(50) 453 .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle }) 454 .onAppear(() => { 455 // The animation starts when the component appears. 456 this.uiContext?.animateTo({ 457 duration: 1200, 458 curve: Curve.Friction, 459 delay: 500, 460 iterations: -1, // The value -1 indicates that the animation is played for an unlimited number of times. 461 playMode: PlayMode.Alternate, 462 expectedFrameRateRange: { 463 min: 10, 464 max: 120, 465 expected: 60, 466 } 467 }, () => { 468 this.rotateAngle = 90 469 }); 470 }) 471 .onClick(() => { 472 this.uiContext?.animateTo({ duration: 0 }, () => { 473 // 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. 474 this.rotateAngle = 0; 475 }); 476 }) 477 }.width('100%').margin({ top: 5 }) 478 } 479} 480``` 481 482## getSharedLocalStorage<sup>12+</sup> 483 484getSharedLocalStorage(): LocalStorage | undefined 485 486Obtains the **LocalStorage** instance shared by this stage. 487 488**Atomic service API**: This API can be used in atomic services since API version 12. 489 490**System capability**: SystemCapability.ArkUI.ArkUI.Full 491 492**Model restriction**: This API can be used only in the stage model. 493 494**Return value** 495 496| Type | Description | 497| ------------------------------ | ----------------- | 498| [LocalStorage](arkui-ts/ts-state-management.md#localstorage9) \| undefined | **LocalStorage** instance if it exists; **undefined** if it does not exist.| 499 500**Example** 501 502```ts 503// EntryAbility.ets 504import { UIAbility } from '@kit.AbilityKit'; 505import { window } from '@kit.ArkUI'; 506 507export default class EntryAbility extends UIAbility { 508 storage: LocalStorage = new LocalStorage(); 509 510 onWindowStageCreate(windowStage: window.WindowStage) { 511 windowStage.loadContent('pages/Index', this.storage); 512 } 513} 514``` 515 516```ts 517// Index.ets 518 519@Entry 520@Component 521struct SharedLocalStorage { 522 localStorage = this.getUIContext().getSharedLocalStorage(); 523 524 build() { 525 Row() { 526 Column() { 527 Button("Change Local Storage to 47") 528 .onClick(() => { 529 this.localStorage?.setOrCreate("propA", 47); 530 }) 531 Button("Get Local Storage") 532 .onClick(() => { 533 console.info(`localStorage: ${this.localStorage?.get("propA")}`); 534 }) 535 } 536 .width('100%') 537 } 538 .height('100%') 539 } 540} 541``` 542 543## getHostContext<sup>12+</sup> 544 545getHostContext(): Context | undefined 546 547Obtains the context of this ability. 548 549**Atomic service API**: This API can be used in atomic services since API version 12. 550 551**System capability**: SystemCapability.ArkUI.ArkUI.Full 552 553**Model restriction**: This API can be used only in the stage model. 554 555**Return value** 556 557| Type| Description | 558| ------ | ------------------------------- | 559| [Context](arkts-apis-uicontext-t.md#context12) \| undefined | Context of the ability. The context type depends on the ability type. For example, if this API is called in a page within a UIAbility window, the returned context type is [UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontext-1). If this API is called in a page within an ExtensionAbility window, the returned context type is [ExtensionContext](../apis-ability-kit/js-apis-inner-application-extensionContext.md). If the ability context does not exist, **undefined** is returned.| 560 561**Example** 562 563```ts 564@Entry 565@Component 566struct Index { 567 uiContext = this.getUIContext(); 568 569 build() { 570 Row() { 571 Column() { 572 Text("cacheDir='"+this.uiContext?.getHostContext()?.cacheDir+"'") 573 .fontSize(25) 574 .border({ color:Color.Red, width:2 }) 575 .padding(50) 576 Text("bundleCodeDir='"+this.uiContext?.getHostContext()?.bundleCodeDir+"'") 577 .fontSize(25) 578 .border({ color:Color.Red, width:2 }) 579 .padding(50) 580 } 581 .width('100%') 582 } 583 .height('100%') 584 } 585} 586``` 587 588## getFrameNodeById<sup>12+</sup> 589 590getFrameNodeById(id: string): FrameNode | null 591 592Obtains a FrameNode on the component tree based on the component ID. 593 594**Atomic service API**: This API can be used in atomic services since API version 12. 595 596**System capability**: SystemCapability.ArkUI.ArkUI.Full 597 598**Parameters** 599 600| Name | Type | Mandatory | Description | 601| ----- | ---------------------------------------- | ---- | ------------------------------------- | 602| id | string | Yes | [Component ID](arkui-ts/ts-universal-attributes-component-id.md) of the target node. | 603 604**Return value** 605 606| Type | Description | 607| ---------------------------------------- | ------------- | 608| [FrameNode](js-apis-arkui-frameNode.md) \| null | FrameNode of the component or **null** if no matching component is found.| 609 610> **NOTE** 611> 612> 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. 613 614**Example** 615 616See [Example of Obtaining the Root Node](js-apis-arkui-frameNode.md#example-of-obtaining-the-root-node). 617 618## getAttachedFrameNodeById<sup>12+</sup> 619 620getAttachedFrameNodeById(id: string): FrameNode | null 621 622Obtains the FrameNode attached to the current window based on its component ID. 623 624**Atomic service API**: This API can be used in atomic services since API version 12. 625 626**System capability**: SystemCapability.ArkUI.ArkUI.Full 627 628**Parameters** 629 630| Name | Type | Mandatory | Description | 631| ----- | ---------------------------------------- | ---- | ------------------------------------- | 632| id | string | Yes | [Component ID](arkui-ts/ts-universal-attributes-component-id.md) of the target node. | 633 634**Return value** 635 636| Type | Description | 637| ---------------------------------------- | ------------- | 638| [FrameNode](js-apis-arkui-frameNode.md) \| null | FrameNode of the component or **null** if no matching component is found.| 639 640> **NOTE** 641> 642> **getAttachedFrameNodeById** can only obtain nodes that are currently rendered on the screen. 643 644**Example** 645 646```ts 647@Entry 648@Component 649struct MyComponent { 650 @State message: string = 'Hello World'; 651 652 build() { 653 RelativeContainer() { 654 Text(this.message) 655 .id('HelloWorld') 656 .fontSize($r('app.float.page_text_font_size')) 657 .fontWeight(FontWeight.Bold) 658 .alignRules({ 659 center: { anchor: '__container__', align: VerticalAlign.Center }, 660 middle: { anchor: '__container__', align: HorizontalAlign.Center } 661 }) 662 .onClick(() => { 663 let node = this.getUIContext().getAttachedFrameNodeById("HelloWorld"); 664 console.log(`Find HelloWorld Tag:${node!.getNodeType()} id:${node!.getUniqueId()}`); 665 }) 666 } 667 .height('100%') 668 .width('100%') 669 } 670} 671``` 672 673## getFrameNodeByUniqueId<sup>12+</sup> 674 675getFrameNodeByUniqueId(id: number): FrameNode | null 676 677Obtains the FrameNode of a component on the component tree using its **uniqueId**. The return value depends on the type of component associated with the **uniqueId**. 6781. If the **uniqueId** corresponds to a built-in component, the associated FrameNode is returned. 6792. If the **uniqueId** corresponds to a custom component: If the component has rendered content, its root node is returned, with the type __Common__; if the component has no rendered content, the FrameNode of its first child component is returned. 6803. If the **uniqueId** does not correspond to any component, **null** is returned. 681 682**Atomic service API**: This API can be used in atomic services since API version 12. 683 684**System capability**: SystemCapability.ArkUI.ArkUI.Full 685 686**Parameters** 687 688| Name | Type | Mandatory | Description | 689| ----- | ---------------------------------------- | ---- | ------------------------------------- | 690| id | number | Yes | Unique ID of the target node. | 691 692**Return value** 693 694| Type | Description | 695| ---------------------------------------- | ------------- | 696| [FrameNode](js-apis-arkui-frameNode.md) \| null | FrameNode of the component or **null** if no matching component is found.| 697 698**Example** 699 700```ts 701import { UIContext, FrameNode } from '@kit.ArkUI'; 702 703@Entry 704@Component 705struct MyComponent { 706 aboutToAppear() { 707 let uniqueId: number = this.getUniqueId(); 708 let uiContext: UIContext = this.getUIContext(); 709 if (uiContext) { 710 let node: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 711 } 712 } 713 714 build() { 715 // ... 716 } 717} 718``` 719 720## getPageInfoByUniqueId<sup>12+</sup> 721 722getPageInfoByUniqueId(id: number): PageInfo 723 724Obtains the router or navigation destination page information corresponding to the node that matches the specified **uniqueId**. 7251. If the node that matches the specified **uniqueId** is in a page, the router information (**routerPageInfo**) is returned. 7262. If the node that matches the specified **uniqueId** is in a **NavDestination** component, the navigation destination page information (**navDestinationInfo**) is returned. 7273. If the node that matches the specified **uniqueId** does not have the corresponding router or navigation destination page information, **undefined** is returned. 7284. 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**. 729 730**Atomic service API**: This API can be used in atomic services since API version 12. 731 732**System capability**: SystemCapability.ArkUI.ArkUI.Full 733 734**Parameters** 735 736| Name | Type | Mandatory | Description | 737| ----- | ---------------------------------------- | ---- | ------------------------------------- | 738| id | number | Yes | Unique ID of the target node. | 739 740**Return value** 741 742| Type | Description | 743| ---------------------------------------- | ------------- | 744| [PageInfo](arkts-apis-uicontext-i.md#pageinfo12) | Router or navigation destination page information corresponding to the specified node.| 745 746**Example** 747 748```ts 749import { UIContext, PageInfo } from '@kit.ArkUI'; 750 751@Entry 752@Component 753struct PageInfoExample { 754 @Provide('pageInfos') pageInfos: NavPathStack = new NavPathStack(); 755 756 build() { 757 Column() { 758 Navigation(this.pageInfos) { 759 NavDestination() { 760 MyComponent() 761 } 762 }.id('navigation') 763 } 764 } 765} 766 767@Component 768struct MyComponent { 769 @State content: string = ''; 770 771 build() { 772 Column() { 773 Text('PageInfoExample') 774 Button('click').onClick(() => { 775 const uiContext: UIContext = this.getUIContext(); 776 const uniqueId: number = this.getUniqueId(); 777 const pageInfo: PageInfo = uiContext.getPageInfoByUniqueId(uniqueId); 778 console.info('pageInfo: ' + JSON.stringify(pageInfo)); 779 console.info('navigationInfo: ' + JSON.stringify(uiContext.getNavigationInfoByUniqueId(uniqueId))); 780 }) 781 TextArea({ 782 text: this.content 783 }) 784 .width('100%') 785 .height(100) 786 } 787 .width('100%') 788 .alignItems(HorizontalAlign.Center) 789 } 790} 791``` 792 793## getNavigationInfoByUniqueId<sup>12+</sup> 794 795getNavigationInfoByUniqueId(id: number): observer.NavigationInfo | undefined 796 797Obtains the navigation information corresponding to the node that matches the specified **uniqueId**. 7981. If the node that matches the specified **uniqueId** is in a **Navigation** component, the navigation information is returned. 7992. If the node that matches the specified **uniqueId** does not have the corresponding navigation information, **undefined** is returned. 800 801**Atomic service API**: This API can be used in atomic services since API version 12. 802 803**System capability**: SystemCapability.ArkUI.ArkUI.Full 804 805**Parameters** 806 807| Name | Type | Mandatory | Description | 808| ----- | ---------------------------------------- | ---- | ------------------------------------- | 809| id | number | Yes | Unique ID of the target node. | 810 811**Return value** 812 813| Type | Description | 814| ---------------------------------------- | ------------- | 815| observer.[NavigationInfo](js-apis-arkui-observer.md#navigationinfo12) \| undefined | Navigation information corresponding to the specified node.| 816 817**Example** 818 819See the example of [getPageInfoByUniqueId](#getpageinfobyuniqueid12). 820 821## showAlertDialog 822 823showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions): void 824 825Shows an alert dialog box. 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 | [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.| 836 837 838**Example** 839 840```ts 841@Entry 842@Component 843struct Index { 844 uiContext: UIContext = this.getUIContext() 845 846 build() { 847 Column() { 848 Button('showAlertDialog') 849 .onClick(() => { 850 this.uiContext.showAlertDialog( 851 { 852 title: 'title', 853 message: 'text', 854 autoCancel: true, 855 alignment: DialogAlignment.Bottom, 856 offset: { dx: 0, dy: -20 }, 857 gridCount: 3, 858 confirm: { 859 value: 'button', 860 action: () => { 861 console.info('Button-clicking callback'); 862 } 863 }, 864 cancel: () => { 865 console.info('Closed callbacks'); 866 } 867 } 868 ); 869 }) 870 }.height('100%').width('100%').justifyContent(FlexAlign.Center) 871 } 872} 873``` 874 875## showActionSheet 876 877showActionSheet(value: ActionSheetOptions): void 878 879Shows an action sheet in the given settings. 880 881**Atomic service API**: This API can be used in atomic services since API version 11. 882 883**System capability**: SystemCapability.ArkUI.ArkUI.Full 884 885**Parameters** 886 887| Name| Type | Mandatory| Description | 888| ------ | ------------------------------------------------------------ | ---- | -------------------- | 889| value | [ActionSheetOptions](arkui-ts/ts-methods-action-sheet.md#actionsheetoptions) | Yes | Parameters of the action sheet.| 890 891**Example** 892 893```ts 894@Entry 895@Component 896struct Index { 897 uiContext: UIContext = this.getUIContext() 898 899 build() { 900 Column() { 901 Button('showActionSheet') 902 .onClick(() => { 903 this.uiContext.showActionSheet({ 904 title: 'ActionSheet title', 905 message: 'message', 906 autoCancel: true, 907 confirm: { 908 value: 'Confirm button', 909 action: () => { 910 console.info('Get ActionSheet handled'); 911 } 912 }, 913 cancel: () => { 914 console.info('ActionSheet canceled'); 915 }, 916 alignment: DialogAlignment.Bottom, 917 offset: { dx: 0, dy: -10 }, 918 sheets: [ 919 { 920 title: 'apples', 921 action: () => { 922 console.info('apples'); 923 } 924 }, 925 { 926 title: 'bananas', 927 action: () => { 928 console.info('bananas'); 929 } 930 }, 931 { 932 title: 'pears', 933 action: () => { 934 console.info('pears'); 935 } 936 } 937 ] 938 }); 939 }) 940 }.height('100%').width('100%').justifyContent(FlexAlign.Center) 941 } 942} 943``` 944 945## showDatePickerDialog 946 947showDatePickerDialog(options: DatePickerDialogOptions): void 948 949Shows a date picker dialog box in the given settings. 950 951**Atomic service API**: This API can be used in atomic services since API version 11. 952 953**System capability**: SystemCapability.ArkUI.ArkUI.Full 954 955**Device behavior differences**: On wearables, calling this API results in a runtime exception indicating that the API is undefined. On other devices, the API works correctly. 956 957**Parameters** 958 959| Name | Type | Mandatory| Description | 960| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 961| options | [DatePickerDialogOptions](arkui-ts/ts-methods-datepicker-dialog.md#datepickerdialogoptions) | Yes | Parameters of the date picker dialog box.| 962 963**Example** 964 965```ts 966// xxx.ets 967@Entry 968@Component 969struct DatePickerDialogExample { 970 selectedDate: Date = new Date("2010-1-1"); 971 972 build() { 973 Column() { 974 Button("DatePickerDialog") 975 .margin(20) 976 .onClick(() => { 977 this.getUIContext().showDatePickerDialog({ 978 start: new Date("2000-1-1"), 979 end: new Date("2100-12-31"), 980 selected: this.selectedDate, 981 showTime: true, 982 useMilitaryTime: false, 983 dateTimeOptions: { hour: "numeric", minute: "2-digit" }, 984 onDateAccept: (value: Date) => { 985 // 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. 986 this.selectedDate = value; 987 console.info("DatePickerDialog:onDateAccept()" + value.toString()); 988 }, 989 onCancel: () => { 990 console.info("DatePickerDialog:onCancel()"); 991 }, 992 onDateChange: (value: Date) => { 993 console.info("DatePickerDialog:onDateChange()" + value.toString()); 994 }, 995 onDidAppear: () => { 996 console.info("DatePickerDialog:onDidAppear()"); 997 }, 998 onDidDisappear: () => { 999 console.info("DatePickerDialog:onDidDisappear()"); 1000 }, 1001 onWillAppear: () => { 1002 console.info("DatePickerDialog:onWillAppear()"); 1003 }, 1004 onWillDisappear: () => { 1005 console.info("DatePickerDialog:onWillDisappear()"); 1006 } 1007 }) 1008 }) 1009 }.width('100%') 1010 } 1011} 1012``` 1013 1014## showTimePickerDialog 1015 1016showTimePickerDialog(options: TimePickerDialogOptions): void 1017 1018Shows a time picker dialog box in the given settings. 1019 1020**Atomic service API**: This API can be used in atomic services since API version 11. 1021 1022**System capability**: SystemCapability.ArkUI.ArkUI.Full 1023 1024**Device behavior differences**: On wearables, calling this API results in a runtime exception indicating that the API is undefined. On other devices, the API works correctly. 1025 1026**Parameters** 1027 1028| Name | Type | Mandatory| Description | 1029| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 1030| options | [TimePickerDialogOptions](arkui-ts/ts-methods-timepicker-dialog.md#timepickerdialogoptions) | Yes | Parameters of the time picker dialog box.| 1031 1032**Example** 1033 1034```ts 1035// xxx.ets 1036 1037class SelectTime{ 1038 selectTime: Date = new Date('2020-12-25T08:30:00'); 1039 hours(h:number,m:number){ 1040 this.selectTime.setHours(h, m); 1041 } 1042} 1043 1044@Entry 1045@Component 1046struct TimePickerDialogExample { 1047 @State selectTime: Date = new Date('2023-12-25T08:30:00'); 1048 1049 build() { 1050 Column() { 1051 Button('showTimePickerDialog') 1052 .margin(30) 1053 .onClick(() => { 1054 this.getUIContext().showTimePickerDialog({ 1055 selected: this.selectTime, 1056 onAccept: (value: TimePickerResult) => { 1057 // 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. 1058 let time = new SelectTime(); 1059 if(value.hour && value.minute){ 1060 time.hours(value.hour, value.minute); 1061 } 1062 console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)); 1063 }, 1064 onCancel: () => { 1065 console.info("TimePickerDialog:onCancel()"); 1066 }, 1067 onChange: (value: TimePickerResult) => { 1068 console.info("TimePickerDialog:onChange()" + JSON.stringify(value)); 1069 } 1070 }); 1071 }) 1072 }.width('100%').margin({ top: 5 }) 1073 } 1074} 1075``` 1076 1077## showTextPickerDialog 1078 1079showTextPickerDialog(options: TextPickerDialogOptions): void 1080 1081Shows a text picker dialog box in the given settings. 1082 1083**Atomic service API**: This API can be used in atomic services since API version 11. 1084 1085**System capability**: SystemCapability.ArkUI.ArkUI.Full 1086 1087**Device behavior differences**: On wearables, calling this API results in a runtime exception indicating that the API is undefined. On other devices, the API works correctly. 1088 1089**Parameters** 1090 1091| Name | Type | Mandatory| Description | 1092| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 1093| options | [TextPickerDialogOptions](arkui-ts/ts-methods-textpicker-dialog.md#textpickerdialogoptions) | Yes | Parameters of the text picker dialog box.| 1094 1095**Example** 1096 1097```ts 1098// xxx.ets 1099 1100class SelectedValue{ 1101 select: number = 2; 1102 set(val: number){ 1103 this.select = val; 1104 } 1105} 1106class SelectedArray{ 1107 select: number[] = []; 1108 set(val: number[]){ 1109 this.select = val; 1110 } 1111} 1112@Entry 1113@Component 1114struct TextPickerDialogExample { 1115 @State selectTime: Date = new Date('2023-12-25T08:30:00'); 1116 private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5']; 1117 private select: number = 0; 1118 build() { 1119 Column() { 1120 Button('showTextPickerDialog') 1121 .margin(30) 1122 .onClick(() => { 1123 this.getUIContext().showTextPickerDialog({ 1124 range: this.fruits, 1125 selected: this.select, 1126 onAccept: (value: TextPickerResult) => { 1127 // 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. 1128 let selectedVal = new SelectedValue(); 1129 let selectedArr = new SelectedArray(); 1130 if (value.index){ 1131 value.index instanceof Array?selectedArr.set(value.index) : selectedVal.set(value.index); 1132 } 1133 console.info("TextPickerDialog:onAccept()" + JSON.stringify(value)); 1134 }, 1135 onCancel: () => { 1136 console.info("TextPickerDialog:onCancel()"); 1137 }, 1138 onChange: (value: TextPickerResult) => { 1139 console.info("TextPickerDialog:onChange()" + JSON.stringify(value)); 1140 } 1141 }); 1142 }) 1143 }.width('100%').margin({ top: 5 }) 1144 } 1145} 1146``` 1147 1148## showTextPickerDialog<sup>20+</sup> 1149 1150showTextPickerDialog(style: TextPickerDialogOptions\|TextPickerDialogOptionsExt): void 1151 1152Shows a text picker dialog box in the given settings. This API extends **showTextPickerDialog** by adding support for the **TextPickerDialogOptionsExt** parameter. 1153 1154**Atomic service API**: This API can be used in atomic services since API version 20. 1155 1156**System capability**: SystemCapability.ArkUI.ArkUI.Full 1157 1158**Device behavior differences**: On wearables, calling this API results in a runtime exception indicating that the API is undefined. On other devices, the API works correctly. 1159 1160**Parameters** 1161 1162| Name | Type | Mandatory| Description | 1163| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 1164| style | [TextPickerDialogOptions](arkui-ts/ts-methods-textpicker-dialog.md#textpickerdialogoptions)\| [TextPickerDialogOptionsExt](arkui-ts/ts-methods-textpicker-dialog.md#textpickerdialogoptionsext20) | Yes | Parameters of the text picker dialog box.| 1165 1166## createAnimator 1167 1168createAnimator(options: AnimatorOptions): AnimatorResult 1169 1170Creates an **Animator** object. 1171 1172**Atomic service API**: This API can be used in atomic services since API version 11. 1173 1174**System capability**: SystemCapability.ArkUI.ArkUI.Full 1175 1176**Parameters** 1177 1178| Name | Type | Mandatory | Description | 1179| ------- | ---------------------------------------- | ---- | ------- | 1180| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) | Yes | Animator options.| 1181 1182**Return value** 1183 1184| Type | Description | 1185| ---------------------------------------- | ------------- | 1186| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator result.| 1187 1188 1189**Error codes** 1190 1191For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1192 1193| ID| Error Message| 1194| ------- | -------- | 1195| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1196 1197**Example** 1198 1199```ts 1200// EntryAbility.ets 1201import { AbilityConstant, Configuration, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; 1202import { AnimatorOptions, window } from '@kit.ArkUI'; 1203import { hilog } from '@kit.PerformanceAnalysisKit'; 1204 1205export default class EntryAbility extends UIAbility { 1206 onWindowStageCreate(windowStage: window.WindowStage) { 1207 // Create the main window and set the home page for this ability. 1208 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1209 windowStage.loadContent('pages/Index', (err, data) => { 1210 if (err.code) { 1211 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1212 return; 1213 } 1214 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1215 let uiContext = windowStage.getMainWindowSync().getUIContext(); 1216 let options:AnimatorOptions = { 1217 duration: 1500, 1218 easing: "friction", 1219 delay: 0, 1220 fill: "forwards", 1221 direction: "normal", 1222 iterations: 3, 1223 begin: 200.0, 1224 end: 400.0 1225 }; 1226 uiContext.createAnimator(options); 1227 }); 1228 } 1229} 1230``` 1231 1232## createAnimator<sup>18+</sup> 1233 1234createAnimator(options: AnimatorOptions | SimpleAnimatorOptions): AnimatorResult 1235 1236Creates an **AnimatorResult** object for animations. Compared to the previous [createAnimator](#createanimator) API, this API adds support for the [SimpleAnimatorOptions](js-apis-animator.md#simpleanimatoroptions18) type. 1237 1238**Atomic service API**: This API can be used in atomic services since API version 18. 1239 1240**System capability**: SystemCapability.ArkUI.ArkUI.Full 1241 1242**Parameters** 1243 1244| Name | Type | Mandatory | Description | 1245| ------- | ---------------------------------------- | ---- | ------- | 1246| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) \| [SimpleAnimatorOptions](js-apis-animator.md#simpleanimatoroptions18) | Yes | Animator options.| 1247 1248**Return value** 1249 1250| Type | Description | 1251| ---------------------------------------- | ------------- | 1252| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator result.| 1253 1254**Error codes** 1255 1256For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1257 1258| ID| Error Message| 1259| ------- | -------- | 1260| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1261 1262**Example** 1263 1264```ts 1265// EntryAbility.ets 1266import { AbilityConstant, Configuration, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit'; 1267import { SimpleAnimatorOptions, window } from '@kit.ArkUI'; 1268import { hilog } from '@kit.PerformanceAnalysisKit'; 1269 1270export default class EntryAbility extends UIAbility { 1271 onWindowStageCreate(windowStage: window.WindowStage) { 1272 // Create the main window and set the home page for this ability. 1273 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1274 windowStage.loadContent('pages/Index', (err, data) => { 1275 if (err.code) { 1276 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1277 return; 1278 } 1279 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1280 let uiContext = windowStage.getMainWindowSync().getUIContext(); 1281 let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).duration(2000); 1282 uiContext.createAnimator(options); 1283 }); 1284 } 1285} 1286``` 1287 1288## runScopedTask 1289 1290runScopedTask(callback: () => void): void 1291 1292Executes the specified callback in this UI context. 1293 1294**Atomic service API**: This API can be used in atomic services since API version 11. 1295 1296**System capability**: SystemCapability.ArkUI.ArkUI.Full 1297 1298**Parameters** 1299 1300| Name | Type | Mandatory | Description | 1301| -------- | ---------- | ---- | ---- | 1302| callback | () => void | Yes | Callback used to return the result.| 1303 1304**Example** 1305 1306```ts 1307@Entry 1308@Component 1309struct Index { 1310 uiContext = this.getUIContext(); 1311 1312 build() { 1313 Row() { 1314 Column() { 1315 Button("run task").onClick(()=>{ 1316 this.uiContext.runScopedTask(()=>{ 1317 // do something 1318 }) 1319 }) 1320 } 1321 .width('100%') 1322 } 1323 .height('100%') 1324 } 1325} 1326``` 1327 1328## setKeyboardAvoidMode<sup>11+</sup> 1329 1330setKeyboardAvoidMode(value: KeyboardAvoidMode): void 1331 1332Sets the avoidance mode for the virtual keyboard. 1333 1334**Atomic service API**: This API can be used in atomic services since API version 11. 1335 1336**System capability**: SystemCapability.ArkUI.ArkUI.Full 1337 1338**Parameters** 1339 1340| Name | Type | Mandatory | Description | 1341| -------- | ---------- | ---- | ---- | 1342| value | [KeyboardAvoidMode](arkts-apis-uicontext-e.md#keyboardavoidmode11)| Yes | Avoidance mode for the virtual keyboard.<br>Default value: **KeyboardAvoidMode.OFFSET**| 1343 1344> **NOTE** 1345> 1346> With **KeyboardAvoidMode.RESIZE**, the page is resized to prevent the virtual keyboard from obstructing the view. Regarding components on the page, those whose width and height are set in percentage are resized with the page, and those whose width and height are set to specific values are laid out according to their settings. With **KeyboardAvoidMode.RESIZE**, **expandSafeArea([SafeAreaType.KEYBOARD],[SafeAreaEdge.BOTTOM])** does not take effect. 1347> 1348> With **KeyboardAvoidMode.NONE**, keyboard avoidance is disabled, and the page will be covered by the displayed keyboard. 1349> 1350> **setKeyboardAvoidMode** only affects page layouts. It does not apply to popup components, including the following: **Dialog**, **Popup**, **Menu**, **BindSheet**, **BindContentCover**, **Toast**, **OverlayManager**. For details about the avoidance mode of popup components, see [CustomDialogControllerOptions](./arkui-ts/ts-methods-custom-dialog-box.md#customdialogcontrolleroptions). 1351 1352**Example** 1353 1354See [Example 4: Setting the Keyboard Avoidance Mode to Resize](./arkui-ts/ts-universal-attributes-expand-safe-area.md#example-4-setting-the-keyboard-avoidance-mode-to-resize), [Example 5: Setting Keyboard Avoidance Mode to Offset](./arkui-ts/ts-universal-attributes-expand-safe-area.md#example-5-setting-keyboard-avoidance-mode-to-offset), and [Example 6: Switching Avoidance Modes](./arkui-ts/ts-universal-attributes-expand-safe-area.md#example-6-switching-avoidance-modes). 1355 1356```ts 1357// EntryAbility.ets 1358import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI'; 1359import { hilog } from '@kit.PerformanceAnalysisKit'; 1360 1361export default class EntryAbility extends UIAbility{ 1362 onWindowStageCreate(windowStage: window.WindowStage) { 1363 // Main window is created, set main page for this ability 1364 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1365 1366 windowStage.loadContent('pages/Index', (err, data) => { 1367 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 1368 uiContext.setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE); 1369 if (err.code) { 1370 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1371 return; 1372 } 1373 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1374 }); 1375 } 1376} 1377``` 1378 1379## getKeyboardAvoidMode<sup>11+</sup> 1380 1381getKeyboardAvoidMode(): KeyboardAvoidMode 1382 1383Obtains the avoidance mode for the virtual keyboard. 1384 1385**Atomic service API**: This API can be used in atomic services since API version 11. 1386 1387**System capability**: SystemCapability.ArkUI.ArkUI.Full 1388 1389**Return value** 1390 1391| Type | Description | 1392| ---------- | ---- | 1393| [KeyboardAvoidMode](arkts-apis-uicontext-e.md#keyboardavoidmode11)| Avoidance mode for the virtual keyboard.| 1394 1395**Example** 1396 1397See [Example 4: Setting the Keyboard Avoidance Mode to Resize](./arkui-ts/ts-universal-attributes-expand-safe-area.md#example-4-setting-the-keyboard-avoidance-mode-to-resize), [Example 5: Setting Keyboard Avoidance Mode to Offset](./arkui-ts/ts-universal-attributes-expand-safe-area.md#example-5-setting-keyboard-avoidance-mode-to-offset), and [Example 6: Switching Avoidance Modes](./arkui-ts/ts-universal-attributes-expand-safe-area.md#example-6-switching-avoidance-modes). 1398 1399```ts 1400// EntryAbility.ets 1401import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI'; 1402import { hilog } from '@kit.PerformanceAnalysisKit'; 1403 1404export default class EntryAbility extends UIAbility{ 1405 onWindowStageCreate(windowStage: window.WindowStage) { 1406 // Main window is created, set main page for this ability 1407 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1408 1409 windowStage.loadContent('pages/Index', (err, data) => { 1410 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 1411 let KeyboardAvoidMode = uiContext.getKeyboardAvoidMode(); 1412 hilog.info(0x0000, "KeyboardAvoidMode:", JSON.stringify(KeyboardAvoidMode)); 1413 if (err.code) { 1414 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1415 return; 1416 } 1417 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1418 }); 1419 } 1420} 1421``` 1422 1423## getAtomicServiceBar<sup>11+</sup> 1424 1425getAtomicServiceBar(): Nullable\<AtomicServiceBar> 1426 1427Obtains an **AtomicServiceBar** object, which can be used to set the properties of the atomic service menu bar. 1428 1429**Atomic service API**: This API can be used in atomic services since API version 11. 1430 1431**System capability**: SystemCapability.ArkUI.ArkUI.Full 1432 1433**Return value** 1434 1435| Type | Description | 1436| ------------------------------------------------- | ------------------------------------------------------------ | 1437| Nullable<[AtomicServiceBar](arkts-apis-uicontext-atomicservicebar.md)> | Returns the **AtomicServerBar** type if the service is an atomic service; returns **undefined** type otherwise.| 1438 1439**Example** 1440 1441```ts 1442// EntryAbility.ets 1443import { UIAbility } from '@kit.AbilityKit'; 1444import { UIContext, AtomicServiceBar, window } from '@kit.ArkUI'; 1445import { hilog } from '@kit.PerformanceAnalysisKit'; 1446export default class EntryAbility extends UIAbility { 1447 onWindowStageCreate(windowStage: window.WindowStage) { 1448 // Main window is created, set main page for this ability 1449 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 1450 windowStage.loadContent('pages/Index', (err, data) => { 1451 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 1452 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 1453 if (atomicServiceBar != undefined) { 1454 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 1455 } else { 1456 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 1457 } 1458 }); 1459 } 1460} 1461``` 1462## getDragController<sup>11+</sup> 1463 1464getDragController(): DragController 1465 1466Obtains the **DragController** object, which can be used to create and initiate dragging. 1467 1468**Atomic service API**: This API can be used in atomic services since API version 12. 1469 1470**System capability**: SystemCapability.ArkUI.ArkUI.Full 1471 1472**Return value** 1473 1474|Type|Description| 1475|----|----| 1476|[DragController](js-apis-arkui-dragController.md)| **DragController** object.| 1477 1478**Example** 1479 1480See the example for [DragController](./arkts-apis-uicontext-dragcontroller.md). 1481 1482## keyframeAnimateTo<sup>11+</sup> 1483 1484keyframeAnimateTo(param: KeyframeAnimateParam, keyframes: Array<KeyframeState>): void 1485 1486Generates a key frame animation. For details about how to use this API, see [keyframeAnimateTo](arkui-ts/ts-keyframeAnimateTo.md). 1487 1488**Atomic service API**: This API can be used in atomic services since API version 12. 1489 1490**System capability**: SystemCapability.ArkUI.ArkUI.Full 1491 1492**Parameters** 1493 1494| Name| Type | Mandatory| Description | 1495| ------------ | ---------------------------------------------------- | ------- | ---------------------------- | 1496| param | [KeyframeAnimateParam](arkui-ts/ts-keyframeAnimateTo.md#keyframeanimateparam) | Yes | Overall animation parameter of the keyframe animation. | 1497| keyframes | Array<[KeyframeState](arkui-ts/ts-keyframeAnimateTo.md#keyframestate)> | Yes | States of all keyframes. | 1498 1499**Example** 1500 1501```ts 1502// xxx.ets 1503import { UIContext } from '@kit.ArkUI'; 1504 1505@Entry 1506@Component 1507struct KeyframeDemo { 1508 @State myScale: number = 1.0; 1509 uiContext: UIContext | undefined = undefined; 1510 1511 aboutToAppear() { 1512 this.uiContext = this.getUIContext(); 1513 } 1514 1515 build() { 1516 Column() { 1517 Circle() 1518 .width(100) 1519 .height(100) 1520 .fill("#46B1E3") 1521 .margin(100) 1522 .scale({ x: this.myScale, y: this.myScale }) 1523 .onClick(() => { 1524 if (!this.uiContext) { 1525 console.info("no uiContext, keyframe failed"); 1526 return; 1527 } 1528 this.myScale = 1; 1529 // Configure the keyframe animation to play three times. 1530 this.uiContext.keyframeAnimateTo({ 1531 iterations: 3, 1532 expectedFrameRateRange: { 1533 min: 10, 1534 max: 120, 1535 expected: 60, 1536 } 1537 }, [ 1538 { 1539 // The first keyframe animation lasts for 800 ms, during which the scale attribute changes from 1 to 1.5. 1540 duration: 800, 1541 event: () => { 1542 this.myScale = 1.5; 1543 } 1544 }, 1545 { 1546 // The second keyframe animation lasts for 500 ms, during which the scale attribute changes from 1.5 to 1. 1547 duration: 500, 1548 event: () => { 1549 this.myScale = 1; 1550 } 1551 } 1552 ]); 1553 }) 1554 }.width('100%').margin({ top: 5 }) 1555 } 1556} 1557``` 1558 1559## getFocusController<sup>12+</sup> 1560 1561getFocusController(): FocusController 1562 1563Obtains a [FocusController](arkts-apis-uicontext-focuscontroller.md) object, which can be used to control the focus. 1564 1565**Atomic service API**: This API can be used in atomic services since API version 12. 1566 1567**System capability**: SystemCapability.ArkUI.ArkUI.Full 1568 1569**Return value** 1570 1571|Type|Description| 1572|----|----| 1573|[FocusController](arkts-apis-uicontext-focuscontroller.md)| **FocusController** object.| 1574 1575**Example** 1576 1577See the example for [FocusController](arkts-apis-uicontext-focuscontroller.md). 1578 1579## getFilteredInspectorTree<sup>12+</sup> 1580 1581getFilteredInspectorTree(filters?: Array\<string\>): string 1582 1583Obtains the component tree and component attributes. This API has a long processing time and is intended for testing scenarios only. 1584 1585**Atomic service API**: This API can be used in atomic services since API version 12. 1586 1587**System capability**: SystemCapability.ArkUI.ArkUI.Full 1588 1589**Parameters** 1590 1591| Name | Type | Mandatory| Description | 1592| ------- | --------------- | ---- | ------------------------------------------------------------ | 1593| filters | Array\<string\> | No | List of component attributes used for filtering. Currently, only the following filter fields are supported:<br>**"id"**: unique ID of the component.<br>**"src"**: source of the resource.<br>**"content"**: information or data contained in the element, component, or object.<br>**"editable"**: whether the component is editable.<br>**"scrollable"**: whether the component is scrollable.<br>**"selectable"**: whether the component is selectable.<br>**"focusable"**: whether the component is focusable.<br>**"focused"**: whether the component is currently focused.<br>If **filters** includes one or more fields, unspecified fields will be filtered out from the results. If **filters** is not provided or is an empty array, none of the aforementioned fields will be filtered out.<br>The following filter field is supported since API version 20:<br>**"isLayoutInspector"**: whether the component tree contains [custom components](../../ui/state-management/arkts-create-custom-components.md). If **filters** is omitted or does not contain **"isLayoutInspector"**, the returned component tree will not include custom component details.<br>Other filter fields are used only in testing scenarios.| 1594 1595**Return value** 1596 1597| Type | Description | 1598| ------ | ---------------------------------- | 1599| string | JSON string of the component tree and component attributes. For details about each field in the component, see the return value description of [getInspectorInfo](./js-apis-arkui-frameNode.md#getinspectorinfo12).| 1600 1601**Error codes** 1602 1603For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1604 1605| ID| Error Message| 1606| ------- | -------- | 1607| 401 | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified. <br> 2. Incorrect parameters types. <br> 3. Parameter verification failed. | 1608 1609**Example** 1610 1611<!--code_no_check--> 1612```ts 1613uiContext.getFilteredInspectorTree(['id', 'src', 'content']); 1614``` 1615 1616<!--code_no_check--> 1617```ts 1618// xxx.ets 1619import { UIContext } from '@kit.ArkUI'; 1620@Entry 1621@Component 1622struct ComponentPage { 1623 loopConsole(inspectorStr: string, i: string) { 1624 console.log(`InsTree ${i}| type: ${JSON.parse(inspectorStr).$type}, ID: ${JSON.parse(inspectorStr).$ID}`); 1625 if (JSON.parse(inspectorStr).$children) { 1626 i += '-'; 1627 for (let index = 0; index < JSON.parse(inspectorStr).$children.length; index++) { 1628 this.loopConsole(JSON.stringify(JSON.parse(inspectorStr).$children[index]), i); 1629 } 1630 } 1631 } 1632 1633 build() { 1634 Column() { 1635 Button('content').onClick(() => { 1636 const uiContext: UIContext = this.getUIContext(); 1637 let inspectorStr = uiContext.getFilteredInspectorTree(['content']); 1638 console.log(`InsTree : ${inspectorStr}`); 1639 inspectorStr = JSON.stringify(JSON.parse(inspectorStr)); 1640 this.loopConsole(inspectorStr, '-'); 1641 }) 1642 Button('isLayoutInspector').onClick(() => { 1643 const uiContext: UIContext = this.getUIContext(); 1644 let inspectorStr = uiContext.getFilteredInspectorTree(['isLayoutInspector']); 1645 console.log(`InsTree : ${inspectorStr}`); 1646 inspectorStr = JSON.stringify(JSON.parse(inspectorStr).content); 1647 this.loopConsole(inspectorStr, '-'); 1648 }) 1649 } 1650 .width('100%') 1651 .height('100%') 1652 } 1653} 1654``` 1655 1656When the **"content"** filter field is passed, the returned JSON string has the following structure: 1657 1658<!--code_no_check--> 1659```ts 1660InsTree : {"$type":"root","width":"720.000000","height":"1280.000000","$resolution":"1.500000","$children":[{"$type":"Column","$ID":15,"type":"build-in","$rect":"[0.00, 72.00],[720.00,1208.00]","$debugLine":"","$attrs":{},"$children":[{"$type":"Button","$ID":16,"type":"build-in","$rect":"[293.00, 72.00],[427.00,132.00]","$debugLine":"","$attrs":{}},{"$type":"Button","$ID":18,"type":"build-in","$rect":"[237.00, 132.00],[484.00,192.00]","$debugLine":"","$attrs":{}}]}]}\ 1661InsTree -| type: root, ID: undefined 1662InsTree --| type: Column, ID: 15 1663InsTree ---| type: Button, ID: 16 1664InsTree ---| type: Button, ID: 18 1665``` 1666 1667Since API version 20, when the **"isLayoutInspector"** filter field is passed, the returned JSON string structure includes an outer layer with **"type"** and **"content"** fields, where **"content"** contains the original JSON structure (as returned without this field), and the return value structure includes custom components. This JSON string structure is as follows: 1668 1669<!--code_no_check--> 1670```ts 1671InsTree : {"type":"root","content":{"$type":"root","width":"720.000000","height":"1280.000000","$resolution":"1.500000","$children":[{"$type":"JsView","$ID":13,"type":"custom","state":{"observedPropertiesInfo":[],"viewInfo":{"componentName":"ComponentPage","id":14,"isV2":false,"isViewActive_":true}},"$rect":"[0.00, 72.00],[720.00,1208.00]","$debugLine":"{\"$line\":\"(0:0)\"}","viewTag":"ComponentPage","$attrs":{"viewKey":"13"},"$children":[{"$type":"Column","$ID":15, "type":"build-in","$rect":"[0.00, 72.00],[720.00,1208.00]","$debugLine":"","$attrs":{ ... 1672InsTree -| type: root, ID: undefined 1673InsTree --| type: JsView, ID: 13 1674InsTree ---| type: Column, ID: 15 1675InsTree ----| type: Button, ID: 16 1676InsTree ----| type: Button, ID: 18 1677``` 1678 1679## getFilteredInspectorTreeById<sup>12+</sup> 1680 1681getFilteredInspectorTreeById(id: string, depth: number, filters?: Array\<string\>): string 1682 1683Obtains the attributes of the specified component and its child components. This API has a long processing time and is intended for testing scenarios only. 1684 1685**Atomic service API**: This API can be used in atomic services since API version 12. 1686 1687**System capability**: SystemCapability.ArkUI.ArkUI.Full 1688 1689**Parameters** 1690 1691| Name | Type | Mandatory| Description | 1692| ------- | --------------- | ---- | ------------------------------------------------------------ | 1693| id | string | Yes | [ID](arkui-ts/ts-universal-attributes-component-id.md) of the target component.| 1694| 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.| 1695| filters | Array\<string\> | No | List of component attributes used for filtering. Currently, only the following filter fields are supported:<br>**"id"**: unique ID of the component.<br>**"src"**: source of the resource.<br>**"content"**: information or data contained in the element, component, or object.<br>**"editable"**: whether the component is editable.<br>**"scrollable"**: whether the component is scrollable.<br>**"selectable"**: whether the component is selectable.<br>**"focusable"**: whether the component is focusable.<br>**"focused"**: whether the component is currently focused.<br>If **filters** includes one or more fields, unspecified fields will be filtered out from the results. If **filters** is not provided or is an empty array, none of the aforementioned fields will be filtered out.<br>Other filter fields are used only in testing scenarios.| 1696 1697**Return value** 1698 1699| Type | Description | 1700| ------ | -------------------------------------------- | 1701| string | JSON string of the attributes of the specified component and its child components. For details about each field in the component, see the return value description of [getInspectorInfo](./js-apis-arkui-frameNode.md#getinspectorinfo12).| 1702 1703 1704**Error codes** 1705 1706For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1707 1708| ID| Error Message| 1709| ------- | -------- | 1710| 401 | Parameter error. Possible causes: <br> 1. Mandatory parameters are left unspecified. <br> 2. Incorrect parameters types. <br> 3. Parameter verification failed. | 1711 1712**Example** 1713 1714<!--code_no_check--> 1715```ts 1716uiContext.getFilteredInspectorTreeById('testId', 0, ['id', 'src', 'content']); 1717``` 1718 1719<!--code_no_check--> 1720```ts 1721import { UIContext } from '@kit.ArkUI'; 1722@Entry 1723@Component 1724struct ComponentPage { 1725 build() { 1726 Column() { 1727 Text("Hello World") 1728 .fontSize(20) 1729 .id("TEXT") 1730 Button('getFilteredInspectorTreeById').onClick(() => { 1731 const uiContext: UIContext = this.getUIContext(); 1732 try { 1733 let inspectorStr = uiContext.getFilteredInspectorTreeById('TEXT', 1, ["id", "src"]); 1734 console.info(`result1: ${inspectorStr}`); 1735 inspectorStr = JSON.stringify(JSON.parse(inspectorStr)['$children'][0]); 1736 console.info(`result2: ${inspectorStr}`); 1737 inspectorStr = uiContext.getFilteredInspectorTreeById('TEXT', 1, ["src"]); 1738 inspectorStr = JSON.stringify(JSON.parse(inspectorStr)['$children'][0]); 1739 console.info(`result3: ${inspectorStr}`); 1740 } catch(e) { 1741 console.info(`getFilteredInspectorTreeById error: ${e}`); 1742 } 1743 }) 1744 } 1745 .width('100%') 1746 .height('100%') 1747 } 1748} 1749``` 1750This JSON string structure is as follows: 1751<!--code_no_check--> 1752```ts 1753result1: {"$type":"root","width":"1260.000000","height":"2720.000000","$resolution":"3.250000","$children":[{"$type":"Text","$ID":6,"type":"build-in","$rect":"[457.00, 123.00],[804.00,199.00]","$debugLine":"","$attrs":{"id":"TEXT","isLayoutDirtyMarked":false,"isRenderDirtyMarked":false,"isMeasureBoundary":false,"hasPendingRequest":false,"isFirstBuilding":false}}]} 1754result2: {"$type":"Text","$ID":6,"type":"build-in","$rect":"[457.00, 123.00],[804.00,199.00]","$debugLine":"","$attrs":{"id":"TEXT","isLayoutDirtyMarked":false,"isRenderDirtyMarked":false,"isMeasureBoundary":false,"hasPendingRequest":false,"isFirstBuilding":false}} 1755result3: {"$type":"Text","$ID":6,"type":"build-in","$rect":"[457.00, 123.00],[804.00,199.00]","$debugLine":"","$attrs":{"isLayoutDirtyMarked":false,"isRenderDirtyMarked":false,"isMeasureBoundary":false,"hasPendingRequest":false,"isFirstBuilding":false}} 1756``` 1757To obtain the component specified by the **id** parameter in the **getFilteredInspectorTreeById** API, you must first convert the API's result into a JSON object (as demonstrated in the sample code), and then extract the first item from the **$children** array. A comparison between **result2** and **result3** reveals that, if the **filters** parameter is changed from **["id", "src"]** to **["src"]**, the **$attrs** property obtained does not contain the **id** key. 1758 1759## getCursorController<sup>12+</sup> 1760 1761getCursorController(): CursorController 1762 1763Obtains a [CursorController](js-apis-arkui-UIContext.md#cursorcontroller12) object, which can be used to control the cursor. 1764 1765**Atomic service API**: This API can be used in atomic services since API version 12. 1766 1767**System capability**: SystemCapability.ArkUI.ArkUI.Full 1768 1769**Return value** 1770 1771|Type|Description| 1772|----|----| 1773|[CursorController](arkts-apis-uicontext-cursorcontroller.md)| **CursorController** object.| 1774 1775**Example** 1776 1777See the example for [CursorController](arkts-apis-uicontext-contextmenucontroller.md). 1778 1779## getContextMenuController<sup>12+</sup> 1780 1781getContextMenuController(): ContextMenuController 1782 1783Obtains a [ContextMenuController](arkts-apis-uicontext-contextmenucontroller.md) object, which can be used to control menus. 1784 1785**Atomic service API**: This API can be used in atomic services since API version 12. 1786 1787**System capability**: SystemCapability.ArkUI.ArkUI.Full 1788 1789**Return value** 1790 1791|Type|Description| 1792|----|----| 1793|[ContextMenuController](arkts-apis-uicontext-contextmenucontroller.md)| **ContextMenuController** object.| 1794 1795## getMeasureUtils<sup>12+</sup> 1796 1797getMeasureUtils(): MeasureUtils 1798 1799Obtains a **MeasureUtils** object for text calculation. 1800 1801**Atomic service API**: This API can be used in atomic services since API version 12. 1802 1803**System capability**: SystemCapability.ArkUI.ArkUI.Full 1804 1805**Return value** 1806 1807| Type | Description | 1808| ------ | -------------------------------------------- | 1809| [MeasureUtils](arkts-apis-uicontext-measureutils.md) | Text metrics, such as text height and width.| 1810 1811**Example** 1812 1813See the example for [MeasureUtils](arkts-apis-uicontext-measureutils.md). 1814 1815## getComponentSnapshot<sup>12+</sup> 1816 1817getComponentSnapshot(): ComponentSnapshot 1818 1819Obtains a **ComponentSnapshot** object, which can be used to obtain a component snapshot. 1820 1821For typical use cases (for example, long screenshots) and best practices of component snapshots, see [Using Component Snapshot (ComponentSnapshot)](../../ui/arkts-uicontext-component-snapshot.md). 1822 1823**Atomic service API**: This API can be used in atomic services since API version 12. 1824 1825**System capability**: SystemCapability.ArkUI.ArkUI.Full 1826 1827**Return value** 1828 1829| Type | Description | 1830| ------------------------------------------------------------ | --------------------------- | 1831| [ComponentSnapshot](arkts-apis-uicontext-componentsnapshot.md) | **ComponentSnapshot** object.| 1832 1833**Example** 1834 1835See the example for [ComponentSnapshot](arkts-apis-uicontext-componentsnapshot.md). 1836 1837## vp2px<sup>12+</sup> 1838 1839vp2px(value : number) : number 1840 1841Converts a value in units of vp to a value in units of px. 1842 1843Conversion formula: px value = vp value × pixel density 1844 1845Pixel density: effective pixel density of the current window, which is the screen's physical pixel density [VirtualScreenConfig.density](js-apis-display.md#virtualscreenconfig16). 1846 1847> **NOTE** 1848> 1849> **getUIContext** must be called after [windowStage.loadContent](./arkts-apis-window-WindowStage.md#loadcontent9) to ensure the UIContext is initialized before this API is called. Otherwise, accurate results cannot be guaranteed. 1850 1851**Atomic service API**: This API can be used in atomic services since API version 12. 1852 1853**System capability**: SystemCapability.ArkUI.ArkUI.Full 1854 1855**Parameters** 1856 1857| Name| Type | Mandatory| Description | 1858| ------ | ------ | ---- | -------------------------------------- | 1859| value | number | Yes | Value to convert.<br>Value range: (-∞, +∞)| 1860 1861**Return value** 1862 1863| Type | Description | 1864| ------ | -------------- | 1865| number | Value after conversion.<br>Value range: (-∞, +∞)| 1866 1867**Example** 1868 1869```ts 1870@Entry 1871@Component 1872struct MatrixExample { 1873 build() { 1874 Column({ space: 100 }) { 1875 Text('Hello1') 1876 .textAlign(TextAlign.Center) 1877 .width(100) 1878 .height(60) 1879 .backgroundColor(0xAFEEEE) 1880 .borderWidth(1) 1881 .rotate({ 1882 z: 1, 1883 angle: 90, 1884 centerX: this.getUIContext().vp2px(50), 1885 centerY: this.getUIContext().vp2px(30) 1886 }) 1887 }.width('100%') 1888 .height('100%') 1889 } 1890} 1891``` 1892 1893## px2vp<sup>12+</sup> 1894 1895px2vp(value : number) : number 1896 1897Converts a value in units of px to a value in units of vp. 1898 1899Conversion formula: vp value = px value/pixel density 1900 1901Pixel density: effective pixel density of the current window, which is the screen's physical pixel density [VirtualScreenConfig.density](js-apis-display.md#virtualscreenconfig16). 1902 1903> **NOTE** 1904> 1905> **getUIContext** must be called after [windowStage.loadContent](./arkts-apis-window-WindowStage.md#loadcontent9) to ensure the UIContext is initialized before this API is called. Otherwise, accurate results cannot be guaranteed. 1906 1907**Atomic service API**: This API can be used in atomic services since API version 12. 1908 1909**System capability**: SystemCapability.ArkUI.ArkUI.Full 1910 1911**Parameters** 1912 1913| Name| Type | Mandatory| Description | 1914| ------ | ------ | ---- | -------------------------------------- | 1915| value | number | Yes | Value to convert.<br>Value range: (-∞, +∞)| 1916 1917**Return value** 1918 1919| Type | Description | 1920| ------ | -------------- | 1921| number | Value after conversion.<br>Value range: (-∞, +∞)| 1922 1923**Example** 1924 1925```ts 1926@Entry 1927@Component 1928struct MatrixExample { 1929 build() { 1930 Column({ space: 100 }) { 1931 Text('Hello1') 1932 .textAlign(TextAlign.Center) 1933 .width(100) 1934 .height(60) 1935 .backgroundColor(0xAFEEEE) 1936 .borderWidth(1) 1937 .rotate({ 1938 z: 1, 1939 angle: 90, 1940 centerX: this.getUIContext().px2vp(50), 1941 centerY: this.getUIContext().px2vp(30) 1942 }) 1943 }.width('100%') 1944 .height('100%') 1945 } 1946} 1947``` 1948 1949## fp2px<sup>12+</sup> 1950 1951fp2px(value : number) : number 1952 1953Converts a value in units of fp to a value in units of px. 1954 1955Conversion formula: px value = fp value × pixel density × font scale factor 1956 1957Pixel density: effective pixel density of the current window, which is the screen's physical pixel density [VirtualScreenConfig.density](js-apis-display.md#virtualscreenconfig16). 1958 1959Font scale factor: system font scaling coefficient ([Configuration.fontScale](arkui-ts/ts-types.md#configuration)). 1960 1961> **NOTE** 1962> 1963> **getUIContext** must be called after [windowStage.loadContent](./arkts-apis-window-WindowStage.md#loadcontent9) to ensure the UIContext is initialized before this API is called. Otherwise, accurate results cannot be guaranteed. 1964 1965**Atomic service API**: This API can be used in atomic services since API version 12. 1966 1967**System capability**: SystemCapability.ArkUI.ArkUI.Full 1968 1969**Parameters** 1970 1971| Name| Type | Mandatory| Description | 1972| ------ | ------ | ---- | -------------------------------------- | 1973| value | number | Yes | Value to convert.<br>Value range: (-∞, +∞)| 1974 1975**Return value** 1976 1977| Type | Description | 1978| ------ | -------------- | 1979| number | Value after conversion.<br>Value range: (-∞, +∞)| 1980 1981**Example** 1982 1983```ts 1984@Entry 1985@Component 1986struct MatrixExample { 1987 build() { 1988 Column({ space: 100 }) { 1989 Text('Hello1') 1990 .textAlign(TextAlign.Center) 1991 .width(100) 1992 .height(60) 1993 .backgroundColor(0xAFEEEE) 1994 .borderWidth(1) 1995 .rotate({ 1996 z: 1, 1997 angle: 90, 1998 centerX: this.getUIContext().fp2px(50), 1999 centerY: this.getUIContext().fp2px(30) 2000 }) 2001 }.width('100%') 2002 .height('100%') 2003 } 2004} 2005``` 2006 2007## px2fp<sup>12+</sup> 2008 2009px2fp(value : number) : number 2010 2011Converts a value in units of px to a value in units of fp. 2012 2013Conversion formula: fp value = px value/pixel density/font scale factor 2014 2015Pixel density: effective pixel density of the current window, which is typically the screen's physical pixel density [VirtualScreenConfig.density](js-apis-display.md#virtualscreenconfig16). 2016 2017Font scale factor: system font scaling coefficient ([Configuration.fontScale](arkui-ts/ts-types.md#configuration)). 2018 2019> **NOTE** 2020> 2021> **getUIContext** must be called after [windowStage.loadContent](./arkts-apis-window-WindowStage.md#loadcontent9) to ensure the UIContext is initialized before this API is called. Otherwise, accurate results cannot be guaranteed. 2022 2023**Atomic service API**: This API can be used in atomic services since API version 12. 2024 2025**System capability**: SystemCapability.ArkUI.ArkUI.Full 2026 2027**Parameters** 2028 2029| Name| Type | Mandatory| Description | 2030| ------ | ------ | ---- | -------------------------------------- | 2031| value | number | Yes | Value to convert.<br>Value range: (-∞, +∞)| 2032 2033**Return value** 2034 2035| Type | Description | 2036| ------ | -------------- | 2037| number | Value after conversion.<br>Value range: (-∞, +∞)| 2038 2039**Example** 2040 2041```ts 2042@Entry 2043@Component 2044struct MatrixExample { 2045 build() { 2046 Column({ space: 100 }) { 2047 Text('Hello1') 2048 .textAlign(TextAlign.Center) 2049 .width(100) 2050 .height(60) 2051 .backgroundColor(0xAFEEEE) 2052 .borderWidth(1) 2053 .rotate({ 2054 z: 1, 2055 angle: 90, 2056 centerX: this.getUIContext().px2fp(50), 2057 centerY: this.getUIContext().px2fp(30) 2058 }) 2059 }.width('100%') 2060 .height('100%') 2061 } 2062} 2063``` 2064 2065## lpx2px<sup>12+</sup> 2066 2067lpx2px(value : number) : number 2068 2069Converts a value in units of lpx to a value in units of px. 2070 2071Conversion formula: px value = lpx value × (actual screen width/logical width), where the logical width is configured using [designWidth](../../quick-start/module-configuration-file.md#pages) 2072 2073> **NOTE** 2074> 2075> **getUIContext** must be called after [windowStage.loadContent](./arkts-apis-window-WindowStage.md#loadcontent9) to ensure the UIContext is initialized before this API is called. Otherwise, accurate results cannot be guaranteed. 2076 2077**Atomic service API**: This API can be used in atomic services since API version 12. 2078 2079**System capability**: SystemCapability.ArkUI.ArkUI.Full 2080 2081**Parameters** 2082 2083| Name| Type | Mandatory| Description | 2084| ------ | ------ | ---- | --------------------------------------- | 2085| value | number | Yes | Value to convert.<br>Value range: (-∞, +∞)| 2086 2087**Return value** 2088 2089| Type | Description | 2090| ------ | -------------- | 2091| number | Value after conversion.<br>Value range: (-∞, +∞)| 2092 2093**Example** 2094 2095```ts 2096@Entry 2097@Component 2098struct MatrixExample { 2099 build() { 2100 Column({ space: 100 }) { 2101 Text('Hello1') 2102 .textAlign(TextAlign.Center) 2103 .width(100) 2104 .height(60) 2105 .backgroundColor(0xAFEEEE) 2106 .borderWidth(1) 2107 .rotate({ 2108 z: 1, 2109 angle: 90, 2110 centerX: this.getUIContext().lpx2px(50), 2111 centerY: this.getUIContext().lpx2px(30) 2112 }) 2113 }.width('100%') 2114 .height('100%') 2115 } 2116} 2117``` 2118 2119## px2lpx<sup>12+</sup> 2120 2121px2lpx(value : number) : number 2122 2123Converts a value in units of px to a value in units of lpx. 2124 2125Conversion formula: lpx value = px value/(actual screen width/logical width), where the logical width is configured using [designWidth](../../quick-start/module-configuration-file.md#pages) 2126 2127> **NOTE** 2128> 2129> **getUIContext** must be called after [windowStage.loadContent](./arkts-apis-window-WindowStage.md#loadcontent9) to ensure the UIContext is initialized before this API is called. Otherwise, accurate results cannot be guaranteed. 2130 2131**Atomic service API**: This API can be used in atomic services since API version 12. 2132 2133**System capability**: SystemCapability.ArkUI.ArkUI.Full 2134 2135**Parameters** 2136 2137| Name| Type | Mandatory| Description | 2138| ------ | ------ | ---- | --------------------------------------- | 2139| value | number | Yes | Value to convert.<br>Value range: (-∞, +∞)| 2140 2141**Return value** 2142 2143| Type | Description | 2144| ------ | -------------- | 2145| number | Value after conversion.<br>Value range: (-∞, +∞)| 2146 2147**Example** 2148 2149```ts 2150@Entry 2151@Component 2152struct MatrixExample { 2153 build() { 2154 Column({ space: 100 }) { 2155 Text('Hello1') 2156 .textAlign(TextAlign.Center) 2157 .width(100) 2158 .height(60) 2159 .backgroundColor(0xAFEEEE) 2160 .borderWidth(1) 2161 .rotate({ 2162 z: 1, 2163 angle: 90, 2164 centerX: this.getUIContext().px2lpx(50), 2165 centerY: this.getUIContext().px2lpx(30) 2166 }) 2167 }.width('100%') 2168 .height('100%') 2169 } 2170} 2171``` 2172 2173## getWindowName<sup>12+</sup> 2174 2175getWindowName(): string | undefined 2176 2177Obtains the name of the window where this instance is located. 2178 2179**Atomic service API**: This API can be used in atomic services since API version 12. 2180 2181**System capability**: SystemCapability.ArkUI.ArkUI.Full 2182 2183**Return value** 2184 2185| Type | Description | 2186| ------ | -------------------------------------------- | 2187| string \| undefined | Name of the window where the current instance is located. If the window does not exist, **undefined** is returned.| 2188 2189**Example** 2190 2191```ts 2192import { window } from '@kit.ArkUI'; 2193 2194@Entry 2195@Component 2196struct Index { 2197 @State message: string = 'Hello World'; 2198 2199 aboutToAppear() { 2200 const windowName = this.getUIContext().getWindowName(); 2201 console.info('WindowName ' + windowName); 2202 const currWindow = window.findWindow(windowName); 2203 const windowProperties = currWindow.getWindowProperties(); 2204 console.info(`Window width ${windowProperties.windowRect.width}, height ${windowProperties.windowRect.height}`); 2205 } 2206 2207 build() { 2208 Row() { 2209 Column() { 2210 Text(this.message) 2211 .fontSize(50) 2212 .fontWeight(FontWeight.Bold) 2213 } 2214 .width('100%') 2215 } 2216 .height('100%') 2217 } 2218} 2219``` 2220 2221## getWindowWidthBreakpoint<sup>13+</sup> 2222 2223getWindowWidthBreakpoint(): WidthBreakpoint 2224 2225Obtains 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). 2226 2227**Atomic service API**: This API can be used in atomic services since API version 13. 2228 2229**System capability**: SystemCapability.ArkUI.ArkUI.Full 2230 2231**Return value** 2232 2233| Type | Description | 2234| ------ | -------------------------------------------- | 2235| [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.| 2236 2237**Example** 2238 2239```ts 2240import { UIContext } from '@kit.ArkUI'; 2241 2242@Entry 2243@Component 2244struct Index { 2245 @State message: string = 'Hello World'; 2246 2247 build() { 2248 Row() { 2249 Column() { 2250 Text(this.message) 2251 .fontSize(30) 2252 .fontWeight(FontWeight.Bold) 2253 Button() { 2254 Text('test') 2255 .fontSize(30) 2256 } 2257 .onClick(() => { 2258 let uiContext: UIContext = this.getUIContext(); 2259 let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint(); 2260 console.info(`Window widthBp: ${widthBp}`); 2261 }) 2262 } 2263 .width('100%') 2264 } 2265 .height('100%') 2266 } 2267} 2268``` 2269 2270## getWindowHeightBreakpoint<sup>13+</sup> 2271 2272getWindowHeightBreakpoint(): HeightBreakpoint 2273 2274Obtains 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). 2275 2276**Atomic service API**: This API can be used in atomic services since API version 13. 2277 2278**System capability**: SystemCapability.ArkUI.ArkUI.Full 2279 2280**Return value** 2281 2282| Type | Description | 2283| ------ | -------------------------------------------- | 2284| [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.| 2285 2286**Example** 2287 2288```ts 2289import { UIContext } from '@kit.ArkUI'; 2290 2291@Entry 2292@Component 2293struct Index { 2294 @State message: string = 'Hello World'; 2295 2296 build() { 2297 Row() { 2298 Column() { 2299 Text(this.message) 2300 .fontSize(30) 2301 .fontWeight(FontWeight.Bold) 2302 Button() { 2303 Text('test') 2304 .fontSize(30) 2305 } 2306 .onClick(() => { 2307 let uiContext: UIContext = this.getUIContext(); 2308 let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint(); 2309 let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint(); 2310 console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`); 2311 }) 2312 } 2313 .width('100%') 2314 } 2315 .height('100%') 2316 } 2317} 2318``` 2319 2320## postFrameCallback<sup>12+</sup> 2321 2322postFrameCallback(frameCallback: FrameCallback): void 2323 2324Registers a callback that is executed when the next frame is rendered. 2325 2326**Atomic service API**: This API can be used in atomic services since API version 12. 2327 2328**System capability**: SystemCapability.ArkUI.ArkUI.Full 2329 2330**Parameters** 2331 2332| Name| Type | Mandatory| Description | 2333| ------ | ------ | ---- | --------------------------------------- | 2334| frameCallback | [FrameCallback](arkts-apis-uicontext-framecallback.md) | Yes | Callback to be executed for the next frame.| 2335 2336**Example** 2337 2338```ts 2339import {FrameCallback } from '@kit.ArkUI'; 2340 2341class MyFrameCallback extends FrameCallback { 2342 private tag: string; 2343 2344 constructor(tag: string) { 2345 super(); 2346 this.tag = tag; 2347 } 2348 2349 onFrame(frameTimeNanos: number) { 2350 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 2351 } 2352} 2353 2354@Entry 2355@Component 2356struct Index { 2357 build() { 2358 Row() { 2359 Button('Invoke postFrameCallback') 2360 .onClick(() => { 2361 this.getUIContext().postFrameCallback(new MyFrameCallback("normTask")); 2362 }) 2363 } 2364 } 2365} 2366``` 2367 2368## postDelayedFrameCallback<sup>12+</sup> 2369 2370postDelayedFrameCallback(frameCallback: FrameCallback, delayTime: number): void 2371 2372Registers a callback to be executed on the next frame after a delay. 2373 2374**Atomic service API**: This API can be used in atomic services since API version 12. 2375 2376**System capability**: SystemCapability.ArkUI.ArkUI.Full 2377 2378**Parameters** 2379 2380| Name| Type | Mandatory| Description | 2381| ------ | ------ | ---- | --------------------------------------- | 2382| frameCallback | [FrameCallback](arkts-apis-uicontext-framecallback.md) | Yes | Callback to be executed for the next frame.| 2383| 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**.| 2384 2385**Example** 2386 2387```ts 2388import {FrameCallback } from '@kit.ArkUI'; 2389 2390class MyFrameCallback extends FrameCallback { 2391 private tag: string; 2392 2393 constructor(tag: string) { 2394 super(); 2395 this.tag = tag; 2396 } 2397 2398 onFrame(frameTimeNanos: number) { 2399 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 2400 } 2401} 2402 2403@Entry 2404@Component 2405struct Index { 2406 build() { 2407 Row() { 2408 Button('Invoke postDelayedFrameCallback') 2409 .onClick(() => { 2410 this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5); 2411 }) 2412 } 2413 } 2414} 2415``` 2416 2417## requireDynamicSyncScene<sup>12+</sup> 2418 2419requireDynamicSyncScene(id: string): Array<DynamicSyncScene> 2420 2421Requests the dynamic sync scene of a component for customizing related frame rate configuration. 2422 2423**Atomic service API**: This API can be used in atomic services since API version 12. 2424 2425**System capability**: SystemCapability.ArkUI.ArkUI.Full 2426 2427**Parameters** 2428 2429| Name| Type | Mandatory| Description | 2430| ------ | ------ | ---- | --------------------------------------- | 2431| id | string | Yes | [Component ID](arkui-ts/ts-universal-attributes-component-id.md) of the target node.| 2432 2433**Return value** 2434 2435| Type | Description | 2436| ------ | -------------------------------------------- | 2437| Array<DynamicSyncScene> | **DynamicSyncScene** object array.| 2438 2439**Example** 2440 2441```ts 2442import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI'; 2443 2444@Entry 2445@Component 2446struct Frame { 2447 @State ANIMATION: ExpectedFrameRateRange = { min: 0, max: 120, expected: 90 }; 2448 @State GESTURE: ExpectedFrameRateRange = { min: 0, max: 120, expected: 30}; 2449 private scenes: SwiperDynamicSyncScene[] = []; 2450 2451 build() { 2452 Column() { 2453 Text("Animation "+ JSON.stringify(this.ANIMATION)) 2454 Text("Gesture "+ JSON.stringify(this.GESTURE)) 2455 Row(){ 2456 Swiper() { 2457 Text("one") 2458 Text("two") 2459 Text("three") 2460 } 2461 .width('100%') 2462 .height('300vp') 2463 .id("dynamicSwiper") 2464 .backgroundColor(Color.Blue) 2465 .autoPlay(true) 2466 .onAppear(()=>{ 2467 this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[]; 2468 }) 2469 } 2470 2471 Button("set frame") 2472 .onClick(() => { 2473 this.scenes.forEach((scenes: SwiperDynamicSyncScene) => { 2474 2475 if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) { 2476 scenes.setFrameRateRange(this.ANIMATION); 2477 } 2478 2479 if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) { 2480 scenes.setFrameRateRange(this.GESTURE); 2481 } 2482 }); 2483 }) 2484 } 2485 } 2486} 2487``` 2488 2489## openBindSheet<sup>12+</sup> 2490 2491openBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions?: SheetOptions, targetId?: number): Promise<void> 2492 2493Creates a sheet whose content is as defined in **bindSheetContent** and displays the sheet. This API uses a promise to return the result. 2494 2495> **NOTE** 2496> 2497> 1. When calling this API, if no valid value is provided for **targetId**, you won't be able to set **SheetOptions.preferType** to **POPUP** or **SheetOptions.mode** to **EMBEDDED**. 2498> 2499> 2. Since [updateBindSheet](#updatebindsheet12) and [closeBindSheet](#closebindsheet12) depend on **bindSheetContent**, you need to maintain the passed **bindSheetContent** yourself. 2500> 2501> 3. Setting **SheetOptions.UIContext** is not supported. 2502> 2503 2504**Atomic service API**: This API can be used in atomic services since API version 12. 2505 2506**System capability**: SystemCapability.ArkUI.ArkUI.Full 2507 2508**Parameters** 2509 2510| Name | Type | Mandatory | Description | 2511| ------- | ---------------------------------------- | ---- | ------- | 2512| bindSheetContent | [ComponentContent\<T>](js-apis-arkui-ComponentContent.md) | Yes| Content to display on the sheet.| 2513| 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).| 2514| targetId | number | No | ID of the component to be bound. If this parameter is not set, no component is bound.| 2515 2516**Return value** 2517 2518| Type | Description | 2519| ---------------------------------------- | ------- | 2520| Promise<void> | Promise used to return the result.| 2521 2522**Error codes** 2523 2524For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Sheet Error Codes](errorcode-bindSheet.md). 2525 2526| ID | Error Message | 2527| ------ | ---------------------------------- | 2528| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 2529| 120001 | The bindSheetContent is incorrect. | 2530| 120002 | The bindSheetContent already exists. | 2531| 120004 | The targetId does not exist. | 2532| 120005 | The node of targetId is not in the component tree. | 2533| 120006 | The node of targetId is not a child of the page node or NavDestination node. | 2534 2535**Example** 2536 2537```ts 2538import { FrameNode, ComponentContent } from "@kit.ArkUI"; 2539import { BusinessError } from '@kit.BasicServicesKit'; 2540 2541class Params { 2542 text: string = ""; 2543 2544 constructor(text: string) { 2545 this.text = text; 2546 } 2547} 2548 2549let contentNode: ComponentContent<Params>; 2550let gUIContext: UIContext; 2551 2552@Builder 2553function buildText(params: Params) { 2554 Column() { 2555 Text(params.text) 2556 Button('Update BindSheet') 2557 .fontSize(20) 2558 .onClick(() => { 2559 gUIContext.updateBindSheet(contentNode, { 2560 backgroundColor: Color.Pink, 2561 }, true) 2562 .then(() => { 2563 console.info('updateBindSheet success'); 2564 }) 2565 .catch((err: BusinessError) => { 2566 console.info('updateBindSheet error: ' + err.code + ' ' + err.message); 2567 }) 2568 }) 2569 2570 Button('Close BindSheet') 2571 .fontSize(20) 2572 .onClick(() => { 2573 gUIContext.closeBindSheet(contentNode) 2574 .then(() => { 2575 console.info('closeBindSheet success'); 2576 }) 2577 .catch((err: BusinessError) => { 2578 console.info('closeBindSheet error: ' + err.code + ' ' + err.message); 2579 }) 2580 }) 2581 } 2582} 2583 2584@Entry 2585@Component 2586struct UIContextBindSheet { 2587 @State message: string = 'BindSheet'; 2588 2589 aboutToAppear() { 2590 gUIContext = this.getUIContext(); 2591 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 2592 } 2593 2594 build() { 2595 RelativeContainer() { 2596 Column() { 2597 Button('Open BindSheet') 2598 .fontSize(20) 2599 .onClick(() => { 2600 let uiContext = this.getUIContext(); 2601 let uniqueId = this.getUniqueId(); 2602 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 2603 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 2604 uiContext.openBindSheet(contentNode, { 2605 height: SheetSize.MEDIUM, 2606 backgroundColor: Color.Green, 2607 title: { title: "Title", subtitle: "subtitle" } 2608 }, targetId) 2609 .then(() => { 2610 console.info('openBindSheet success'); 2611 }) 2612 .catch((err: BusinessError) => { 2613 console.info('openBindSheet error: ' + err.code + ' ' + err.message); 2614 }) 2615 }) 2616 } 2617 } 2618 .height('100%') 2619 .width('100%') 2620 } 2621} 2622``` 2623 2624## updateBindSheet<sup>12+</sup> 2625 2626updateBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions: SheetOptions, partialUpdate?: boolean ): Promise<void> 2627 2628Updates the style of the sheet corresponding to the provided **bindSheetContent**. This API uses a promise to return the result. 2629 2630> **NOTE** 2631> 2632> **SheetOptions.UIContext**, **SheetOptions.mode**, and callback functions cannot be updated. 2633> 2634 2635**Atomic service API**: This API can be used in atomic services since API version 12. 2636 2637**System capability**: SystemCapability.ArkUI.ArkUI.Full 2638 2639**Parameters** 2640 2641| Name | Type | Mandatory | Description | 2642| ------- | ---------------------------------------- | ---- | ------- | 2643| bindSheetContent | [ComponentContent\<T>](js-apis-arkui-ComponentContent.md) | Yes| Content to display on the sheet.| 2644| 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.| 2645| partialUpdate | boolean | No | Whether to update the sheet in incremental mode.<br>Default value: **false**<br>**NOTE**<br>1. **true**: incremental update, where the specified properties in **SheetOptions** are updated, and other properties stay at their current value.<br>2. **false**: full update, where all properties except those specified in **SheetOptions** are restored to default values.| 2646 2647**Return value** 2648 2649| Type | Description | 2650| ---------------------------------------- | ------- | 2651| Promise<void> | Promise used to return the result.| 2652 2653**Error codes** 2654 2655For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Sheet Error Codes](errorcode-bindSheet.md). 2656 2657| ID | Error Message | 2658| ------ | ---------------------------------- | 2659| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 2660| 120001 | The bindSheetContent is incorrect. | 2661| 120003 | The bindSheetContent cannot be found. | 2662 2663**Example** 2664 2665```ts 2666import { FrameNode, ComponentContent } from "@kit.ArkUI"; 2667import { BusinessError } from '@kit.BasicServicesKit'; 2668 2669class Params { 2670 text: string = ""; 2671 2672 constructor(text: string) { 2673 this.text = text; 2674 } 2675} 2676 2677let contentNode: ComponentContent<Params>; 2678let gUIContext: UIContext; 2679 2680@Builder 2681function buildText(params: Params) { 2682 Column() { 2683 Text(params.text) 2684 Button('Update BindSheet') 2685 .fontSize(20) 2686 .onClick(() => { 2687 gUIContext.updateBindSheet(contentNode, { 2688 backgroundColor: Color.Pink, 2689 }, true) 2690 .then(() => { 2691 console.info('updateBindSheet success'); 2692 }) 2693 .catch((err: BusinessError) => { 2694 console.info('updateBindSheet error: ' + err.code + ' ' + err.message); 2695 }) 2696 }) 2697 2698 Button('Close BindSheet') 2699 .fontSize(20) 2700 .onClick(() => { 2701 gUIContext.closeBindSheet(contentNode) 2702 .then(() => { 2703 console.info('closeBindSheet success'); 2704 }) 2705 .catch((err: BusinessError) => { 2706 console.info('closeBindSheet error: ' + err.code + ' ' + err.message); 2707 }) 2708 }) 2709 } 2710} 2711 2712@Entry 2713@Component 2714struct UIContextBindSheet { 2715 @State message: string = 'BindSheet'; 2716 2717 aboutToAppear() { 2718 gUIContext = this.getUIContext(); 2719 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 2720 } 2721 2722 build() { 2723 RelativeContainer() { 2724 Column() { 2725 Button('Open BindSheet') 2726 .fontSize(20) 2727 .onClick(() => { 2728 let uiContext = this.getUIContext(); 2729 let uniqueId = this.getUniqueId(); 2730 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 2731 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 2732 uiContext.openBindSheet(contentNode, { 2733 height: SheetSize.MEDIUM, 2734 backgroundColor: Color.Green, 2735 title: { title: "Title", subtitle: "subtitle" } 2736 }, targetId) 2737 .then(() => { 2738 console.info('openBindSheet success'); 2739 }) 2740 .catch((err: BusinessError) => { 2741 console.info('openBindSheet error: ' + err.code + ' ' + err.message); 2742 }) 2743 }) 2744 } 2745 } 2746 .height('100%') 2747 .width('100%') 2748 } 2749} 2750``` 2751 2752## closeBindSheet<sup>12+</sup> 2753 2754closeBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>): Promise<void> 2755 2756Closes the sheet corresponding to **bindSheetContent**. This API uses a promise to return the result. 2757 2758> **NOTE** 2759> 2760> Closing a sheet using this API will not invoke the **shouldDismiss** callback. 2761> 2762 2763**Atomic service API**: This API can be used in atomic services since API version 12. 2764 2765**System capability**: SystemCapability.ArkUI.ArkUI.Full 2766 2767**Parameters** 2768 2769| Name | Type | Mandatory | Description | 2770| ------- | ---------------------------------------- | ---- | ------- | 2771| bindSheetContent | [ComponentContent\<T>](js-apis-arkui-ComponentContent.md) | Yes| Content to display on the sheet.| 2772 2773**Return value** 2774 2775| Type | Description | 2776| ---------------------------------------- | ------- | 2777| Promise<void> | Promise used to return the result.| 2778 2779**Error codes** 2780 2781For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Sheet Error Codes](errorcode-bindSheet.md). 2782 2783| ID | Error Message | 2784| ------ | ---------------------------------- | 2785| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 2786| 120001 | The bindSheetContent is incorrect. | 2787| 120003 | The bindSheetContent cannot be found. | 2788 2789**Example** 2790 2791```ts 2792import { FrameNode, ComponentContent } from "@kit.ArkUI"; 2793import { BusinessError } from '@kit.BasicServicesKit'; 2794 2795class Params { 2796 text: string = ""; 2797 2798 constructor(text: string) { 2799 this.text = text; 2800 } 2801} 2802 2803let contentNode: ComponentContent<Params>; 2804let gUIContext: UIContext; 2805 2806@Builder 2807function buildText(params: Params) { 2808 Column() { 2809 Text(params.text) 2810 Button('Update BindSheet') 2811 .fontSize(20) 2812 .onClick(() => { 2813 gUIContext.updateBindSheet(contentNode, { 2814 backgroundColor: Color.Pink, 2815 }, true) 2816 .then(() => { 2817 console.info('updateBindSheet success'); 2818 }) 2819 .catch((err: BusinessError) => { 2820 console.info('updateBindSheet error: ' + err.code + ' ' + err.message); 2821 }) 2822 }) 2823 2824 Button('Close BindSheet') 2825 .fontSize(20) 2826 .onClick(() => { 2827 gUIContext.closeBindSheet(contentNode) 2828 .then(() => { 2829 console.info('closeBindSheet success'); 2830 }) 2831 .catch((err: BusinessError) => { 2832 console.info('closeBindSheet error: ' + err.code + ' ' + err.message); 2833 }) 2834 }) 2835 } 2836} 2837 2838@Entry 2839@Component 2840struct UIContextBindSheet { 2841 @State message: string = 'BindSheet'; 2842 2843 aboutToAppear() { 2844 gUIContext = this.getUIContext(); 2845 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 2846 } 2847 2848 build() { 2849 RelativeContainer() { 2850 Column() { 2851 Button('Open BindSheet') 2852 .fontSize(20) 2853 .onClick(() => { 2854 let uiContext = this.getUIContext(); 2855 let uniqueId = this.getUniqueId(); 2856 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 2857 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 2858 uiContext.openBindSheet(contentNode, { 2859 height: SheetSize.MEDIUM, 2860 backgroundColor: Color.Green, 2861 title: { title: "Title", subtitle: "subtitle" } 2862 }, targetId) 2863 .then(() => { 2864 console.info('openBindSheet success'); 2865 }) 2866 .catch((err: BusinessError) => { 2867 console.info('openBindSheet error: ' + err.code + ' ' + err.message); 2868 }) 2869 }) 2870 } 2871 } 2872 .height('100%') 2873 .width('100%') 2874 } 2875} 2876``` 2877 2878## isFollowingSystemFontScale<sup>13+</sup> 2879 2880isFollowingSystemFontScale(): boolean 2881 2882Checks whether this UI context follows the system font scale settings. 2883 2884**Atomic service API**: This API can be used in atomic services since API version 13. 2885 2886**System capability**: SystemCapability.ArkUI.ArkUI.Full 2887 2888**Return value** 2889 2890| Type | Description | 2891|---------|---------------| 2892| boolean | Whether the current UI context follows the system font scale settings.<br> **true**: The current UI context follows the system font scale settings.<br>**false**: The current UI context does not follow the system font scale settings.| 2893 2894**Example** 2895 2896<!--code_no_check--> 2897```ts 2898uiContext.isFollowingSystemFontScale(); 2899``` 2900 2901## getMaxFontScale<sup>13+</sup> 2902 2903getMaxFontScale(): number 2904 2905Obtains the maximum font scale of this UI context. 2906 2907**Atomic service API**: This API can be used in atomic services since API version 13. 2908 2909**System capability**: SystemCapability.ArkUI.ArkUI.Full 2910 2911**Return value** 2912 2913| Type | Description | 2914|---------|-----------| 2915| number | Maximum font scale of the current UI context.| 2916 2917**Example** 2918 2919<!--code_no_check--> 2920```ts 2921uiContext.getMaxFontScale(); 2922``` 2923 2924## bindTabsToScrollable<sup>13+</sup> 2925 2926bindTabsToScrollable(tabsController: TabsController, scroller: Scroller): void 2927 2928Binds a **Tabs** component with a scrollable container, which can be a [List](./arkui-ts/ts-container-list.md), [Scroll](./arkui-ts/ts-container-scroll.md), [Grid](./arkui-ts/ts-container-grid.md), or [WaterFlow](./arkui-ts/ts-container-waterflow.md) component. This way, scrolling the scrollable container triggers the display and hide animations of the tab bar for all **Tabs** components that are bound to it – scrolling up triggers the hide animation, and scrolling down triggers the show animation. A **TabsController** instance can be bound with multiple **Scroller** instances, and conversely, a **Scroller** instance can be bound with multiple **TabsController** instances. 2929 2930> **NOTE** 2931> 2932> When multiple scrollable containers are bound to the same **Tabs** component, scrolling any of the bound containers will trigger the appearance and disappearance animations of the tab bar. In addition, when any scrollable container reaches the bottom, the tab bar immediately triggers the appearance animation. Therefore, avoid scrolling multiple scrollable containers simultaneously whenever possible. 2933 2934**Atomic service API**: This API can be used in atomic services since API version 13. 2935 2936**System capability**: SystemCapability.ArkUI.ArkUI.Full 2937 2938**Parameters** 2939 2940| Name | Type | Mandatory | Description | 2941| ------- | ---------------------------------------- | ---- | ------- | 2942| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | Yes| Controller of the target **Tabs** component.| 2943| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target scrollable container.| 2944 2945**Example** 2946 2947```ts 2948@Entry 2949@Component 2950struct TabsExample { 2951 private arr: string[] = []; 2952 private parentTabsController: TabsController = new TabsController(); 2953 private childTabsController: TabsController = new TabsController(); 2954 private listScroller: Scroller = new Scroller(); 2955 private parentScroller: Scroller = new Scroller(); 2956 private childScroller: Scroller = new Scroller(); 2957 2958 aboutToAppear(): void { 2959 for (let i = 0; i < 20; i++) { 2960 this.arr.push(i.toString()); 2961 } 2962 let context = this.getUIContext(); 2963 context.bindTabsToScrollable(this.parentTabsController, this.listScroller); 2964 context.bindTabsToScrollable(this.childTabsController, this.listScroller); 2965 context.bindTabsToNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller); 2966 } 2967 2968 aboutToDisappear(): void { 2969 let context = this.getUIContext(); 2970 context.unbindTabsFromScrollable(this.parentTabsController, this.listScroller); 2971 context.unbindTabsFromScrollable(this.childTabsController, this.listScroller); 2972 context.unbindTabsFromNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller); 2973 } 2974 2975 build() { 2976 Tabs({ barPosition: BarPosition.End, controller: this.parentTabsController }) { 2977 TabContent() { 2978 Tabs({ controller: this.childTabsController }) { 2979 TabContent() { 2980 List({ space: 20, initialIndex: 0, scroller: this.listScroller }) { 2981 ForEach(this.arr, (item: string) => { 2982 ListItem() { 2983 Text(item) 2984 .width('100%') 2985 .height(100) 2986 .fontSize(16) 2987 .textAlign(TextAlign.Center) 2988 .borderRadius(10) 2989 .backgroundColor(Color.Gray) 2990 } 2991 }, (item: string) => item) 2992 } 2993 .scrollBar(BarState.Off) 2994 .width('90%') 2995 .height('100%') 2996 .contentStartOffset(56) 2997 .contentEndOffset(52) 2998 }.tabBar(SubTabBarStyle.of('Top tab')) 2999 } 3000 .width('100%') 3001 .height('100%') 3002 .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. 3003 .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. 3004 }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), 'Scroller linked with TabsControllers')) 3005 3006 TabContent() { 3007 Scroll(this.parentScroller) { 3008 List({ space: 20, initialIndex: 0, scroller: this.childScroller }) { 3009 ForEach(this.arr, (item: string) => { 3010 ListItem() { 3011 Text(item) 3012 .width('100%') 3013 .height(100) 3014 .fontSize(16) 3015 .textAlign(TextAlign.Center) 3016 .borderRadius(10) 3017 .backgroundColor(Color.Gray) 3018 } 3019 }, (item: string) => item) 3020 } 3021 .scrollBar(BarState.Off) 3022 .width('90%') 3023 .height('100%') 3024 .contentEndOffset(52) 3025 .nestedScroll({ scrollForward: NestedScrollMode.SELF_FIRST, scrollBackward: NestedScrollMode.SELF_FIRST }) 3026 } 3027 .width('100%') 3028 .height('100%') 3029 .scrollBar(BarState.Off) 3030 .scrollable(ScrollDirection.Vertical) 3031 .edgeEffect(EdgeEffect.Spring) 3032 }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), 'Nested Scroller linked with TabsController')) 3033 } 3034 .width('100%') 3035 .height('100%') 3036 .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. 3037 .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. 3038 } 3039} 3040``` 3041 3042 3043 3044## unbindTabsFromScrollable<sup>13+</sup> 3045 3046unbindTabsFromScrollable(tabsController: TabsController, scroller: Scroller): void 3047 3048Unbinds a **Tabs** component from a scrollable container. 3049 3050**Atomic service API**: This API can be used in atomic services since API version 13. 3051 3052**System capability**: SystemCapability.ArkUI.ArkUI.Full 3053 3054**Parameters** 3055 3056| Name | Type | Mandatory | Description | 3057| ------- | ---------------------------------------- | ---- | ------- | 3058| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | Yes| Controller of the target **Tabs** component.| 3059| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target scrollable container.| 3060 3061**Example** 3062 3063See the example for [bindTabsToScrollable](#bindtabstoscrollable13). 3064 3065## bindTabsToNestedScrollable<sup>13+</sup> 3066 3067bindTabsToNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void 3068 3069Binds a **Tabs** component with a nested scrollable container, which can be a [List](./arkui-ts/ts-container-list.md), [Scroll](./arkui-ts/ts-container-scroll.md), [Grid](./arkui-ts/ts-container-grid.md), or [WaterFlow](./arkui-ts/ts-container-waterflow.md) component. This way, scrolling the parent or child component triggers the display and hide animations of the tab bar for all **Tabs** components that are bound to it – scrolling up triggers the hide animation, and scrolling down triggers the show animation. A **TabsController** instance can be bound with multiple nested **Scroller** instances, and conversely, a nested **Scroller** instance can be bound with multiple **TabsController** instances. 3070 3071**Atomic service API**: This API can be used in atomic services since API version 13. 3072 3073**System capability**: SystemCapability.ArkUI.ArkUI.Full 3074 3075**Parameters** 3076 3077| Name | Type | Mandatory | Description | 3078| ------- | ---------------------------------------- | ---- | ------- | 3079| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | Yes| Controller of the target **Tabs** component.| 3080| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target parent scrollable container.| 3081| 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**.| 3082 3083**Example** 3084 3085See the example for [bindTabsToScrollable](#bindtabstoscrollable13). 3086 3087## unbindTabsFromNestedScrollable<sup>13+</sup> 3088 3089unbindTabsFromNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void 3090 3091Unbinds a **Tabs** component from a nested scrollable container. 3092 3093**Atomic service API**: This API can be used in atomic services since API version 13. 3094 3095**System capability**: SystemCapability.ArkUI.ArkUI.Full 3096 3097**Parameters** 3098 3099| Name | Type | Mandatory | Description | 3100| ------- | ---------------------------------------- | ---- | ------- | 3101| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | Yes| Controller of the target **Tabs** component.| 3102| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | Yes| Controller of the target parent scrollable container.| 3103| 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**.| 3104 3105**Example** 3106 3107See the example for [bindTabsToScrollable](#bindtabstoscrollable13). 3108 3109## enableSwipeBack<sup>18+</sup> 3110 3111enableSwipeBack(enabled: Optional\<boolean\>): void 3112 3113Sets whether to enable the horizontal swipe-to-go-back gesture within the application. 3114 3115**Atomic service API**: This API can be used in atomic services since API version 18. 3116 3117**System capability**: SystemCapability.ArkUI.ArkUI.Circle 3118 3119**Parameters** 3120 3121| Name | Type | Mandatory | Description | 3122| --- | --- | --- | --- | 3123| enabled | Optional\<boolean> | Yes| Whether to enable the horizontal swipe-to-go-back gesture.<br>Default value: **true**.<br>**true**: The horizontal swipe-to-go-back gesture is enabled.<br>**false**: The horizontal swipe-to-go-back gesture is disabled.| 3124 3125**Example** 3126 3127```js 3128@Entry 3129@Component 3130struct Index { 3131 @State isEnable: boolean = true; 3132 3133 build() { 3134 RelativeContainer() { 3135 Button(`enable swipe back: ${this.isEnable}`).onClick(() => { 3136 this.isEnable = !this.isEnable; 3137 this.getUIContext().enableSwipeBack(this.isEnable); 3138 }) 3139 } 3140 .height('100%') 3141 .width('100%') 3142 } 3143} 3144``` 3145 3146## getTextMenuController<sup>16+</sup> 3147 3148getTextMenuController(): TextMenuController 3149 3150Obtains a [TextMenuController](arkts-apis-uicontext-textmenucontroller.md) object, which can be used to control the context menu on selection. 3151 3152**Atomic service API**: This API can be used in atomic services since API version 16. 3153 3154**System capability**: SystemCapability.ArkUI.ArkUI.Full 3155 3156**Return value** 3157 3158|Type|Description| 3159|----|----| 3160|[TextMenuController](arkts-apis-uicontext-textmenucontroller.md)| Obtained **TextMenuController** object.| 3161 3162**Example** 3163 3164See the example for [TextMenuController](arkts-apis-uicontext-textmenucontroller.md). 3165 3166## createUIContextWithoutWindow<sup>17+</sup> 3167 3168static createUIContextWithoutWindow(context: common.UIAbilityContext | common.ExtensionContext) : UIContext | undefined 3169 3170Creates a UI instance that does not depend on a window and returns its UI context. The created UI instance is a singleton. 3171 3172> **NOTE** 3173> 3174> The returned UI context can only be used to create [custom nodes](../../ui/arkts-user-defined-node.md). It cannot be used for other UI operations. 3175 3176**Atomic service API**: This API can be used in atomic services since API version 17. 3177 3178**System capability**: SystemCapability.ArkUI.ArkUI.Full 3179 3180**Parameters** 3181 3182| Name | Type | Mandatory| Description | 3183| ------- | ---------------------------------------- | ---- | ----------- | 3184| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) \| common.[ExtensionContext](../apis-ability-kit/js-apis-inner-application-extensionContext.md) | Yes | Context corresponding to [UIAbility](../apis-ability-kit/js-apis-app-ability-uiAbility.md) or [ExtensionAbility](../apis-ability-kit/js-apis-app-ability-extensionAbility.md).| 3185 3186**Return value** 3187 3188|Type|Description| 3189|----|----| 3190| UIContext \| undefined | Context of the created UI instance, or **undefined** if creation fails.| 3191 3192**Error codes** 3193 3194For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [UI Context Error Codes](errorcode-uicontext.md). 3195 3196| ID | Error Message | 3197| ------ | ---------------------------------- | 3198| 401 | Parameter error. Possible causes: <br> 1. The number of parameters is incorrect.<br> 2. Invalid parameter type of context. | 3199| 100001 | Internal error. | 3200 3201 3202**Example** 3203 3204```ts 3205// EntryAbility.ets 3206import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 3207import { hilog } from '@kit.PerformanceAnalysisKit'; 3208import { UIContext } from '@kit.ArkUI'; 3209 3210export default class EntryAbility extends UIAbility { 3211 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 3212 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 3213 let uiContext : UIContext | undefined = UIContext.createUIContextWithoutWindow(this.context); 3214 } 3215 3216 // ...... 3217} 3218``` 3219 3220## destroyUIContextWithoutWindow<sup>17+</sup> 3221 3222static destroyUIContextWithoutWindow(): void 3223 3224Destroys the UI instance created using [createUIContextWithoutWindow](#createuicontextwithoutwindow17). 3225 3226**Atomic service API**: This API can be used in atomic services since API version 17. 3227 3228**System capability**: SystemCapability.ArkUI.ArkUI.Full 3229 3230**Example** 3231 3232```ts 3233// EntryAbility.ets 3234import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 3235import { hilog } from '@kit.PerformanceAnalysisKit'; 3236import { UIContext } from '@kit.ArkUI'; 3237 3238export default class EntryAbility extends UIAbility { 3239 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 3240 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 3241 let uiContext : UIContext | undefined = UIContext.createUIContextWithoutWindow(this.context); 3242 UIContext.destroyUIContextWithoutWindow(); 3243 } 3244 3245 // ...... 3246} 3247``` 3248 3249## dispatchKeyEvent<sup>15+</sup> 3250 3251dispatchKeyEvent(node: number | string, event: KeyEvent): boolean 3252 3253Dispatches a key event to the specified component. To ensure predictable behavior, the target component must be within the subtree of the dispatching component. 3254 3255**Atomic service API**: This API can be used in atomic services since API version 15. 3256 3257**System capability**: SystemCapability.ArkUI.ArkUI.Full 3258 3259**Parameters** 3260 3261| Name| Type | Mandatory| Description | 3262| ------ | ----------------------------- | ---- | ------------------ | 3263| node | number \| string | Yes | ID or unique ID of the target component.| 3264| event |[KeyEvent](./arkui-ts/ts-universal-events-key.md#keyevent) | Yes | **KeyEvent** object.| 3265 3266**Return value** 3267 3268| Type | Description | 3269|---------|---------------| 3270| boolean | Whether the key event was successfully dispatched to the specified component.<br> The value **true** means the dispatch was successful, and **false** means the dispatch failed.| 3271 3272**Example** 3273 3274```ts 3275@Entry 3276@Component 3277struct Index { 3278 build() { 3279 Row() { 3280 Row() { 3281 Button('Button1').id('Button1').onKeyEvent((event) => { 3282 console.log("Button1"); 3283 return true; 3284 }) 3285 Button('Button2').id('Button2').onKeyEvent((event) => { 3286 console.log("Button2"); 3287 return true; 3288 }) 3289 } 3290 .width('100%') 3291 .height('100%') 3292 .id('Row1') 3293 .onKeyEventDispatch((event) => { 3294 let context = this.getUIContext(); 3295 context.getFocusController().requestFocus('Button1'); 3296 return context.dispatchKeyEvent('Button1', event); 3297 }) 3298 3299 } 3300 .height('100%') 3301 .width('100%') 3302 .onKeyEventDispatch((event) => { 3303 if (event.type == KeyType.Down) { 3304 let context = this.getUIContext(); 3305 context.getFocusController().requestFocus('Row1'); 3306 return context.dispatchKeyEvent('Row1', event); 3307 } 3308 return true; 3309 }) 3310 } 3311} 3312``` 3313## setPixelRoundMode<sup>18+</sup> 3314 3315setPixelRoundMode(mode: PixelRoundMode): void 3316 3317Sets the pixel rounding mode for this page. 3318 3319**Atomic service API**: This API can be used in atomic services since API version 18. 3320 3321**System capability**: SystemCapability.ArkUI.ArkUI.Full 3322 3323**Parameters** 3324 3325| Name | Type | Mandatory | Description | 3326| -------- | ---------- | ---- | ---- | 3327| mode | [PixelRoundMode](./arkui-ts/ts-appendix-enums.md#pixelroundmode18)| Yes | Pixel rounding mode.<br>Default value: **PixelRoundMode.PIXEL_ROUND_ON_LAYOUT_FINISH**.| 3328 3329**Example** 3330 3331```ts 3332// EntryAbility.ets 3333import { UIContext } from '@kit.ArkUI'; 3334import { hilog } from '@kit.PerformanceAnalysisKit'; 3335 3336export default class EntryAbility extends UIAbility{ 3337 onWindowStageCreate(windowStage: window.WindowStage) { 3338 // Main window is created, set main page for this ability 3339 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 3340 3341 windowStage.loadContent('pages/Index', (err, data) => { 3342 let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext(); 3343 uiContext.setPixelRoundMode(PixelRoundMode.PIXEL_ROUND_ON_LAYOUT_FINISH); 3344 if (err.code) { 3345 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 3346 return; 3347 } 3348 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 3349 }); 3350 } 3351} 3352``` 3353 3354## getPixelRoundMode<sup>18+</sup> 3355 3356getPixelRoundMode(): PixelRoundMode 3357 3358Obtains the pixel rounding mode for this page. 3359 3360**Atomic service API**: This API can be used in atomic services since API version 18. 3361 3362**System capability**: SystemCapability.ArkUI.ArkUI.Full 3363 3364**Return value** 3365 3366| Type | Description | 3367| ---------- | ---- | 3368| [PixelRoundMode](./arkui-ts/ts-appendix-enums.md#pixelroundmode18)| Pixel rounding mode of the current page.| 3369 3370**Example** 3371 3372```ts 3373// EntryAbility.ets 3374import { UIContext } from '@kit.ArkUI'; 3375import { hilog } from '@kit.PerformanceAnalysisKit'; 3376 3377export default class EntryAbility extends UIAbility{ 3378 onWindowStageCreate(windowStage: window.WindowStage) { 3379 // Main window is created, set main page for this ability 3380 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 3381 3382 windowStage.loadContent('pages/Index', (err, data) => { 3383 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 3384 console.info("pixelRoundMode : " + uiContext.getPixelRoundMode().valueOf()); 3385 if (err.code) { 3386 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 3387 return; 3388 } 3389 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 3390 }); 3391 } 3392} 3393``` 3394<!--no_check-->