1# Class (UIContext) 2<!--Kit: ArkUI--> 3<!--Subsystem: ArkUI--> 4<!--Owner: @xiang-shouxing--> 5<!--Designer: @xiang-shouxing--> 6<!--Tester: @sally__--> 7<!--Adviser: @HelloCrease--> 8 9UIContext实例对象。 10 11> **说明:** 12> 13> - 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 14> 15> - 示例效果请以真机运行为准,当前DevEco Studio预览器不支持。 16> 17> - 以下API需先使用ohos.window中的[getUIContext()](arkts-apis-window-Window.md#getuicontext10)方法获取UIContext实例,再通过此实例调用对应方法。或者可以通过自定义组件内置方法[getUIContext()](arkui-ts/ts-custom-component-api.md#getuicontext)获取。本文中UIContext对象以uiContext表示。 18 19**示例:** 20 21以下示例展示了两种获取UIContext实例的方法。 22 23```ts 24//两种方法获取到的UIContext没有差异 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 //通过自定义组件内置方法获取 36 this.getUIContext() 37 //其他运行逻辑 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 //通过ohos.window获取 53 windowStage.getMainWindowSync().getUIContext() 54 //其他运行逻辑 55 } 56} 57``` 58 59## isAvailable<sup>20+</sup> 60 61isAvailable(): boolean 62 63判断UIContext对象对应的UI实例是否有效。使用[getUIContext](arkts-apis-window-Window.md#getuicontext10)方法获取UIContext对象。后端UI实例存在时,该UI实例有效。通过new UIContext()创建的UIContext对象无对应的UI实例;多次[loadContent](arkts-apis-window-Window.md#loadcontent9)后,旧的UI实例会失效。多窗口应用场景,当窗口关闭后,该窗口的UI实例失效。总而言之,当UIContext对象没有对应的后端UI实例时,该对象是无效的。 64 65**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。 66 67**系统能力:** SystemCapability.ArkUI.ArkUI.Full 68 69**返回值:** 70 71| 类型 | 说明 | 72| ------------- | ----------- | 73| boolean | 返回UIContext对象对应的UI实例是否有效。true表示有效,false表示无效。 | 74 75**示例:** 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() 结果: " + this.result1) 89 .fontSize(20) 90 .margin(10) 91 92 Text("new UIContext() 结果: " + 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 = `可用状态: ${available} UI实例有效 `; 107 console.info("getUIContext测试:", available); 108 } catch (e) { 109 this.result1 = "错误: " + (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 = `可用状态: ${available} UI实例无效`; 122 console.info("new UIContext测试:", available); 123 } catch (e) { 124 this.result2 = "错误: " + (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 139获取Font对象。 140 141**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 142 143**系统能力:** SystemCapability.ArkUI.ArkUI.Full 144 145**返回值:** 146 147| 类型 | 说明 | 148| ------------- | ----------- | 149| [Font](./arkts-apis-uicontext-font.md) | 返回Font实例对象。 | 150 151**示例:** 152 153完整示例请参考[Font](arkts-apis-uicontext-font.md)中的示例。 154 155## getComponentUtils 156 157getComponentUtils(): ComponentUtils 158 159获取ComponentUtils对象。 160 161**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 162 163**系统能力:** SystemCapability.ArkUI.ArkUI.Full 164 165**返回值:** 166 167| 类型 | 说明 | 168| --------------------------------- | --------------------- | 169| [ComponentUtils](arkts-apis-uicontext-componentutils.md) | 返回ComponentUtils实例对象。 | 170 171**示例:** 172 173完整示例请参考[getComponentUtils](js-apis-arkui-componentUtils.md)中的示例。 174 175## getUIInspector 176 177getUIInspector(): UIInspector 178 179获取UIInspector对象。 180 181**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 182 183**系统能力:** SystemCapability.ArkUI.ArkUI.Full 184 185**返回值:** 186 187| 类型 | 说明 | 188| --------------------------- | ------------------ | 189| [UIInspector](./arkts-apis-uicontext-uiinspector.md) | 返回UIInspector实例对象。 | 190 191**示例:** 192 193完整示例请参考[UIInspector](./arkts-apis-uicontext-uiinspector.md)中的示例。 194 195## getUIObserver<sup>11+</sup> 196 197getUIObserver(): UIObserver 198 199获取UIObserver对象。 200 201**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 202 203**系统能力:** SystemCapability.ArkUI.ArkUI.Full 204 205**返回值:** 206 207| 类型 | 说明 | 208| --------------------------- | ------------------ | 209| [UIObserver](./arkts-apis-uicontext-uiobserver.md) | 返回UIObserver实例对象。 | 210 211**示例:** 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 263获取MediaQuery对象。 264 265**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 266 267**系统能力:** SystemCapability.ArkUI.ArkUI.Full 268 269**返回值:** 270 271| 类型 | 说明 | 272| ------------------------- | ----------------- | 273| [MediaQuery](arkts-apis-uicontext-mediaquery.md) | 返回MediaQuery实例对象。 | 274 275**示例:** 276 277完整示例请参考[mediaquery示例](js-apis-mediaquery.md#示例)。 278 279## getRouter 280 281getRouter(): Router 282 283获取Router对象。 284 285**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 286 287**系统能力:** SystemCapability.ArkUI.ArkUI.Full 288 289**返回值:** 290 291| 类型 | 说明 | 292| ----------------- | ------------- | 293| [Router](arkts-apis-uicontext-router.md) | 返回Router实例对象。 | 294 295**示例:** 296 297完整示例请参考[pushUrl](arkts-apis-uicontext-router.md#pushurl)。 298 299## getPromptAction 300 301getPromptAction(): PromptAction 302 303获取PromptAction对象。 304 305**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 306 307**系统能力:** SystemCapability.ArkUI.ArkUI.Full 308 309**返回值:** 310 311| 类型 | 说明 | 312| ----------------------------- | ------------------- | 313| [PromptAction](arkts-apis-uicontext-promptaction.md) | 返回PromptAction实例对象。 | 314 315**示例:** 316 317完整示例请参考[PromptAction](arkts-apis-uicontext-promptaction.md)中的示例。 318 319## getOverlayManager<sup>12+</sup> 320 321getOverlayManager(): OverlayManager 322 323获取OverlayManager对象。 324 325**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 326 327**系统能力:**: SystemCapability.ArkUI.ArkUI.Full 328 329**返回值:** 330 331| 类型 | 说明 | 332| ----------------------------- | ------------------- | 333| [OverlayManager](arkts-apis-uicontext-overlaymanager.md) | 返回OverlayManager实例对象。 | 334 335**示例:** 336 337完整示例请参考[OverlayManager](arkts-apis-uicontext-overlaymanager.md)中的示例。 338 339## setOverlayManagerOptions<sup>15+</sup> 340 341setOverlayManagerOptions(options: OverlayManagerOptions): boolean 342 343设置[OverlayManager](arkts-apis-uicontext-overlaymanager.md)参数。用于在使用OverlayManager能力之前先初始化overlayManager的参数,包括是否需要渲染overlay根节点等属性。该方法需要在执行getOverlayManager方法之前执行生效,且该方法只生效一次。 344 345**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 346 347**系统能力:**: SystemCapability.ArkUI.ArkUI.Full 348 349**参数:** 350 351| 参数名 | 类型 | 必填 | 说明 | 352| ----- | ---------------------------------------- | ---- | ------------------------------------- | 353| options | [OverlayManagerOptions](arkts-apis-uicontext-i.md#overlaymanageroptions15) | 是 | OverlayManager参数。| 354 355**返回值:** 356 357| 类型 | 说明 | 358| ------- | -------------- | 359| boolean | 是否设置成功。<br/>返回true表示设置成功。返回false表示设置失败。 | 360 361**示例:** 362 363完整示例请参考[OverlayManager](arkts-apis-uicontext-overlaymanager.md)中的示例。 364 365## getOverlayManagerOptions<sup>15+</sup> 366 367getOverlayManagerOptions(): OverlayManagerOptions 368 369用于获取当前[OverlayManagerOptions](arkts-apis-uicontext-i.md#overlaymanageroptions15)参数。 370 371**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 372 373**系统能力:**: SystemCapability.ArkUI.ArkUI.Full 374 375**返回值:** 376 377| 类型 | 说明 | 378| ----------------------------- | ------------------- | 379| [OverlayManagerOptions](arkts-apis-uicontext-i.md#overlaymanageroptions15) | 返回当前OverlayManagerOptions。 | 380 381**示例:** 382 383完整示例请参考[OverlayManager](arkts-apis-uicontext-overlaymanager.md)中的示例。 384 385## animateTo 386 387animateTo(value: AnimateParam, event: () => void): void 388 389提供animateTo接口来指定由于闭包代码导致的状态变化插入过渡动效。 390 391**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 392 393**系统能力:** SystemCapability.ArkUI.ArkUI.Full 394 395> **说明:** 396> - 不推荐在aboutToAppear、aboutToDisappear中调用动画。 397> - 如果在[aboutToAppear](../apis-arkui/arkui-ts/ts-custom-component-lifecycle.md#abouttoappear)中调用动画,自定义组件内的build还未执行,内部组件还未创建,动画时机过早,动画属性没有初值无法对组件产生动画。 398> - 执行[aboutToDisappear](../apis-arkui/arkui-ts/ts-custom-component-lifecycle.md#abouttodisappear)时,组件即将销毁,不能在aboutToDisappear里面做动画。 399> - 在组件出现和消失时,可以通过[组件内转场](../apis-arkui/arkui-ts/ts-transition-animation-component.md)添加动画效果。 400> - 组件内转场不支持的属性,可以参考[显式动画](./arkui-ts/ts-explicit-animation.md)中的[示例2](./arkui-ts/ts-explicit-animation.md#示例2动画执行结束后组件消失),使用animateTo实现动画执行结束后组件消失的效果。 401> - 某些场景下,在[状态管理V2](../../ui/state-management/arkts-state-management-overview.md#状态管理v2)中使用animateTo动画,会产生异常效果,具体可参考:[在状态管理V2中使用animateTo动画效果异常](../../ui/state-management/arkts-new-local.md#在状态管理v2中使用animateto动画效果异常)。 402 403**参数:** 404 405| 参数名 | 类型 | 必填 | 说明 | 406| ----- | ---------------------------------------- | ---- | ------------------------------------- | 407| value | [AnimateParam](arkui-ts/ts-explicit-animation.md#animateparam对象说明) | 是 | 设置动画效果相关参数。 | 408| event | () => void | 是 | 指定显示动效的闭包函数,在闭包函数中导致的状态变化系统会自动插入过渡动画。 | 409 410**示例:** 411 412```ts 413// xxx.ets 414@Entry 415@Component 416struct AnimateToExample { 417 @State widthSize: number = 250; 418 @State heightSize: number = 100; 419 @State rotateAngle: number = 0; 420 private flag: boolean = true; 421 uiContext: UIContext | undefined = undefined; 422 423 aboutToAppear() { 424 this.uiContext = this.getUIContext(); 425 if (!this.uiContext) { 426 console.warn("no uiContext"); 427 return; 428 } 429 } 430 431 build() { 432 Column() { 433 Button('change size') 434 .width(this.widthSize) 435 .height(this.heightSize) 436 .margin(30) 437 .onClick(() => { 438 if (this.flag) { 439 this.uiContext?.animateTo({ 440 duration: 2000, 441 curve: Curve.EaseOut, 442 iterations: 3, 443 playMode: PlayMode.Normal, 444 onFinish: () => { 445 console.info('play end'); 446 } 447 }, () => { 448 this.widthSize = 150; 449 this.heightSize = 60; 450 }); 451 } else { 452 this.uiContext?.animateTo({}, () => { 453 this.widthSize = 250; 454 this.heightSize = 100; 455 }); 456 } 457 this.flag = !this.flag; 458 }) 459 Button('stop rotating') 460 .margin(50) 461 .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle }) 462 .onAppear(() => { 463 // 组件出现时开始做动画 464 this.uiContext?.animateTo({ 465 duration: 1200, 466 curve: Curve.Friction, 467 delay: 500, 468 iterations: -1, // 设置-1表示动画无限循环 469 playMode: PlayMode.Alternate, 470 expectedFrameRateRange: { 471 min: 10, 472 max: 120, 473 expected: 60, 474 } 475 }, () => { 476 this.rotateAngle = 90 477 }); 478 }) 479 .onClick(() => { 480 this.uiContext?.animateTo({ duration: 0 }, () => { 481 // this.rotateAngle之前为90,在duration为0的动画中修改属性,可以停止该属性之前的动画,按新设置的属性显示 482 this.rotateAngle = 0; 483 }); 484 }) 485 }.width('100%').margin({ top: 5 }) 486 } 487} 488``` 489 490## getSharedLocalStorage<sup>12+</sup> 491 492getSharedLocalStorage(): LocalStorage | undefined 493 494获取当前stage共享的LocalStorage实例。 495 496**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 497 498**系统能力:** SystemCapability.ArkUI.ArkUI.Full 499 500**模型约束:** 此接口仅可在Stage模型下使用。 501 502**返回值:** 503 504| 类型 | 说明 | 505| ------------------------------ | ----------------- | 506| [LocalStorage](arkui-ts/ts-state-management.md#localstorage9) \| undefined | 返回LocalStorage实例。共享的LocalStorage实例不存在时返回undefined。 | 507 508**示例:** 509 510```ts 511// EntryAbility.ets 512import { UIAbility } from '@kit.AbilityKit'; 513import { window } from '@kit.ArkUI'; 514 515export default class EntryAbility extends UIAbility { 516 storage: LocalStorage = new LocalStorage(); 517 518 onWindowStageCreate(windowStage: window.WindowStage) { 519 windowStage.loadContent('pages/Index', this.storage); 520 } 521} 522``` 523 524```ts 525// Index.ets 526 527@Entry 528@Component 529struct SharedLocalStorage { 530 localStorage = this.getUIContext().getSharedLocalStorage(); 531 532 build() { 533 Row() { 534 Column() { 535 Button("Change Local Storage to 47") 536 .onClick(() => { 537 this.localStorage?.setOrCreate("propA", 47); 538 }) 539 Button("Get Local Storage") 540 .onClick(() => { 541 console.info(`localStorage: ${this.localStorage?.get("propA")}`); 542 }) 543 } 544 .width('100%') 545 } 546 .height('100%') 547 } 548} 549``` 550 551## getHostContext<sup>12+</sup> 552 553getHostContext(): Context | undefined 554 555获得当前元能力的Context。 556 557**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 558 559**系统能力:** SystemCapability.ArkUI.ArkUI.Full 560 561**模型约束:** 此接口仅可在Stage模型下使用。 562 563**返回值:** 564 565| 类型 | 说明 | 566| ------ | ------------------------------- | 567| [Context](arkts-apis-uicontext-t.md#context12) \| undefined | 返回当前组件所在Ability的Context,Context的具体类型为当前Ability关联的Context对象。例如:在UIAbility窗口中的页面调用该接口,返回类型为[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md#uiabilitycontext-1)。在ExtensionAbility窗口中的页面调用该接口,返回类型为[ExtensionContext](../apis-ability-kit/js-apis-inner-application-extensionContext.md)。ability上下文不存在时返回undefined。 | 568 569**示例:** 570 571```ts 572@Entry 573@Component 574struct Index { 575 uiContext = this.getUIContext(); 576 577 build() { 578 Row() { 579 Column() { 580 Text("cacheDir='"+this.uiContext?.getHostContext()?.cacheDir+"'") 581 .fontSize(25) 582 .border({ color:Color.Red, width:2 }) 583 .padding(50) 584 Text("bundleCodeDir='"+this.uiContext?.getHostContext()?.bundleCodeDir+"'") 585 .fontSize(25) 586 .border({ color:Color.Red, width:2 }) 587 .padding(50) 588 } 589 .width('100%') 590 } 591 .height('100%') 592 } 593} 594``` 595 596## getFrameNodeById<sup>12+</sup> 597 598getFrameNodeById(id: string): FrameNode | null 599 600通过组件的id获取组件树的实体节点。 601 602**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 603 604**系统能力:** SystemCapability.ArkUI.ArkUI.Full 605 606**参数:** 607 608| 参数名 | 类型 | 必填 | 说明 | 609| ----- | ---------------------------------------- | ---- | ------------------------------------- | 610| id | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。 | 611 612**返回值:** 613 614| 类型 | 说明 | 615| ---------------------------------------- | ------------- | 616| [FrameNode](js-apis-arkui-frameNode.md) \| null | 返回的组件树的实体节点或者空节点。 | 617 618> **说明:** 619> 620> getFrameNodeById通过遍历查询对应id的节点,性能较差。推荐使用[getAttachedFrameNodeById](#getattachedframenodebyid12)。 621 622**示例:** 623 624完整示例请参考[获取根节点示例](js-apis-arkui-frameNode.md#获取根节点示例)。 625 626## getAttachedFrameNodeById<sup>12+</sup> 627 628getAttachedFrameNodeById(id: string): FrameNode | null 629 630通过组件的id获取当前窗口上的实体节点。 631 632**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 633 634**系统能力:** SystemCapability.ArkUI.ArkUI.Full 635 636**参数:** 637 638| 参数名 | 类型 | 必填 | 说明 | 639| ----- | ---------------------------------------- | ---- | ------------------------------------- | 640| id | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。 | 641 642**返回值:** 643 644| 类型 | 说明 | 645| ---------------------------------------- | ------------- | 646| [FrameNode](js-apis-arkui-frameNode.md) \| null | 返回的组件树的实体节点或者空节点。 | 647 648> **说明:** 649> 650> getAttachedFrameNodeById仅能查询上屏节点。 651 652**示例:** 653 654```ts 655@Entry 656@Component 657struct MyComponent { 658 @State message: string = 'Hello World'; 659 660 build() { 661 RelativeContainer() { 662 Text(this.message) 663 .id('HelloWorld') 664 .fontSize($r('app.float.page_text_font_size')) 665 .fontWeight(FontWeight.Bold) 666 .alignRules({ 667 center: { anchor: '__container__', align: VerticalAlign.Center }, 668 middle: { anchor: '__container__', align: HorizontalAlign.Center } 669 }) 670 .onClick(() => { 671 let node = this.getUIContext().getAttachedFrameNodeById("HelloWorld"); 672 console.info(`Find HelloWorld Tag:${node!.getNodeType()} id:${node!.getUniqueId()}`); 673 }) 674 } 675 .height('100%') 676 .width('100%') 677 } 678} 679``` 680 681## getFrameNodeByUniqueId<sup>12+</sup> 682 683getFrameNodeByUniqueId(id: number): FrameNode | null 684 685提供getFrameNodeByUniqueId接口通过组件的uniqueId获取组件树的实体节点。 6861. 当uniqueId对应的是系统组件时,返回组件所对应的FrameNode; 6872. 当uniqueId对应的是自定义组件时,若其有渲染内容,则返回该自定义组件的根节点,类型为__Common__;若其无渲染内容,则返回其第一个子组件的FrameNode。 6883. 当uniqueId无对应的组件时,返回null。 689 690**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 691 692**系统能力:** SystemCapability.ArkUI.ArkUI.Full 693 694**参数:** 695 696| 参数名 | 类型 | 必填 | 说明 | 697| ----- | ---------------------------------------- | ---- | ------------------------------------- | 698| id | number | 是 | 节点对应的UniqueId | 699 700**返回值:** 701 702| 类型 | 说明 | 703| ---------------------------------------- | ------------- | 704| [FrameNode](js-apis-arkui-frameNode.md) \| null | 返回的组件树的实体节点或者空节点。 | 705 706**示例:** 707 708```ts 709import { UIContext, FrameNode } from '@kit.ArkUI'; 710 711@Entry 712@Component 713struct MyComponent { 714 aboutToAppear() { 715 let uniqueId: number = this.getUniqueId(); 716 let uiContext: UIContext = this.getUIContext(); 717 if (uiContext) { 718 let node: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 719 } 720 } 721 722 build() { 723 // ... 724 } 725} 726``` 727 728## getPageInfoByUniqueId<sup>12+</sup> 729 730getPageInfoByUniqueId(id: number): PageInfo 731 732提供getPageInfoByUniqueId接口通过组件的uniqueId获取该节点对应的Router和NavDestination页面信息。 7331. 当uniqueId对应的节点在Page节点中,routerPageInfo属性为其对应的Router信息; 7342. 当uniqueId对应的节点在NavDestination节点中,navDestinationInfo属性为其对应的NavDestination信息; 7353. 当uniqueId对应的节点无对应的Router或NavDestination信息时,对应的属性为undefined; 7364. 模态弹窗并不在任何Page节点中。当uniqueId对应的节点在模态弹窗中,例如[CustomDialog](./arkui-ts/ts-methods-custom-dialog-box.md)、[bindSheet](./arkui-ts/ts-universal-attributes-sheet-transition.md#bindsheet)和[bindContentCover](./arkui-ts/ts-universal-attributes-modal-transition.md#bindcontentcover)构建的模态页面中,routerPageInfo属性为undefined。 737 738**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 739 740**系统能力:** SystemCapability.ArkUI.ArkUI.Full 741 742**参数:** 743 744| 参数名 | 类型 | 必填 | 说明 | 745| ----- | ---------------------------------------- | ---- | ------------------------------------- | 746| id | number | 是 | 节点对应的UniqueId。 | 747 748**返回值:** 749 750| 类型 | 说明 | 751| ---------------------------------------- | ------------- | 752| [PageInfo](arkts-apis-uicontext-i.md#pageinfo12) | 返回节点对应的Router和NavDestination信息。 | 753 754**示例:** 755 756```ts 757import { UIContext, PageInfo } from '@kit.ArkUI'; 758 759@Entry 760@Component 761struct PageInfoExample { 762 @Provide('pageInfos') pageInfos: NavPathStack = new NavPathStack(); 763 764 build() { 765 Column() { 766 Navigation(this.pageInfos) { 767 NavDestination() { 768 MyComponent() 769 } 770 }.id('navigation') 771 } 772 } 773} 774 775@Component 776struct MyComponent { 777 @State content: string = ''; 778 779 build() { 780 Column() { 781 Text('PageInfoExample') 782 Button('click').onClick(() => { 783 const uiContext: UIContext = this.getUIContext(); 784 const uniqueId: number = this.getUniqueId(); 785 const pageInfo: PageInfo = uiContext.getPageInfoByUniqueId(uniqueId); 786 console.info('pageInfo: ' + JSON.stringify(pageInfo)); 787 console.info('navigationInfo: ' + JSON.stringify(uiContext.getNavigationInfoByUniqueId(uniqueId))); 788 }) 789 TextArea({ 790 text: this.content 791 }) 792 .width('100%') 793 .height(100) 794 } 795 .width('100%') 796 .alignItems(HorizontalAlign.Center) 797 } 798} 799``` 800 801## getNavigationInfoByUniqueId<sup>12+</sup> 802 803getNavigationInfoByUniqueId(id: number): observer.NavigationInfo | undefined 804 805提供getNavigationInfoByUniqueId接口通过组件的uniqueId获取该节点对应的Navigation页面信息。 8061. 当uniqueId对应的节点在Navigation节点中,返回其对应的Navigation信息; 8072. 当uniqueId对应的节点无对应的Navigation信息时,返回undefined。 808 809**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 810 811**系统能力:** SystemCapability.ArkUI.ArkUI.Full 812 813**参数:** 814 815| 参数名 | 类型 | 必填 | 说明 | 816| ----- | ---------------------------------------- | ---- | ------------------------------------- | 817| id | number | 是 | 节点对应的UniqueId。 | 818 819**返回值:** 820 821| 类型 | 说明 | 822| ---------------------------------------- | ------------- | 823| observer.[NavigationInfo](js-apis-arkui-observer.md#navigationinfo12) \| undefined | 返回节点对应的Navigation信息。 | 824 825**示例:** 826 827请参考[getPageInfoByUniqueId](#getpageinfobyuniqueid12)的示例。 828 829## showAlertDialog 830 831showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions): void 832 833显示警告弹窗组件,可设置文本内容与响应回调。 834 835> **说明:** 836> 837> 不支持在输入法类型窗口中使用子窗(showInSubwindow为true)的showAlertDialog,详情见输入法框架的约束与限制说明[createPanel](../apis-ime-kit/js-apis-inputmethodengine.md#createpanel10-1)。 838 839**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 840 841**系统能力:** SystemCapability.ArkUI.ArkUI.Full 842 843**参数:** 844 845| 参数名 | 类型 | 必填 | 说明 | 846| ------- | ---------------------------------------- | ---- | ------------------- | 847| 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对象说明) | 是 | 定义并显示AlertDialog组件。 | 848 849 850**示例:** 851 852```ts 853@Entry 854@Component 855struct Index { 856 uiContext: UIContext = this.getUIContext() 857 858 build() { 859 Column() { 860 Button('showAlertDialog') 861 .onClick(() => { 862 this.uiContext.showAlertDialog( 863 { 864 title: 'title', 865 message: 'text', 866 autoCancel: true, 867 alignment: DialogAlignment.Bottom, 868 offset: { dx: 0, dy: -20 }, 869 gridCount: 3, 870 confirm: { 871 value: 'button', 872 action: () => { 873 console.info('Button-clicking callback'); 874 } 875 }, 876 cancel: () => { 877 console.info('Closed callbacks'); 878 } 879 } 880 ); 881 }) 882 }.height('100%').width('100%').justifyContent(FlexAlign.Center) 883 } 884} 885``` 886 887## showActionSheet 888 889showActionSheet(value: ActionSheetOptions): void 890 891定义列表弹窗并弹出。 892 893**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 894 895**系统能力:** SystemCapability.ArkUI.ArkUI.Full 896 897**参数:** 898 899| 参数名 | 类型 | 必填 | 说明 | 900| ------ | ------------------------------------------------------------ | ---- | -------------------- | 901| value | [ActionSheetOptions](arkui-ts/ts-methods-action-sheet.md#actionsheetoptions对象说明) | 是 | 配置列表弹窗的参数。 | 902 903**示例:** 904 905```ts 906@Entry 907@Component 908struct Index { 909 uiContext: UIContext = this.getUIContext() 910 911 build() { 912 Column() { 913 Button('showActionSheet') 914 .onClick(() => { 915 this.uiContext.showActionSheet({ 916 title: 'ActionSheet title', 917 message: 'message', 918 autoCancel: true, 919 confirm: { 920 value: 'Confirm button', 921 action: () => { 922 console.info('Get ActionSheet handled'); 923 } 924 }, 925 cancel: () => { 926 console.info('ActionSheet canceled'); 927 }, 928 alignment: DialogAlignment.Bottom, 929 offset: { dx: 0, dy: -10 }, 930 sheets: [ 931 { 932 title: 'apples', 933 action: () => { 934 console.info('apples'); 935 } 936 }, 937 { 938 title: 'bananas', 939 action: () => { 940 console.info('bananas'); 941 } 942 }, 943 { 944 title: 'pears', 945 action: () => { 946 console.info('pears'); 947 } 948 } 949 ] 950 }); 951 }) 952 }.height('100%').width('100%').justifyContent(FlexAlign.Center) 953 } 954} 955``` 956 957## showDatePickerDialog 958 959showDatePickerDialog(options: DatePickerDialogOptions): void 960 961定义日期滑动选择器弹窗并弹出。 962 963> **说明:** 964> 965> 不支持在输入法类型窗口中使用子窗(showInSubwindow为true)的showDatePickerDialog,详情见输入法框架的约束与限制说明[createPanel](../apis-ime-kit/js-apis-inputmethodengine.md#createpanel10-1)。 966 967**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 968 969**系统能力:** SystemCapability.ArkUI.ArkUI.Full 970 971**设备行为差异:** 该接口在Wearable设备上使用时,应用程序运行异常,异常信息中提示接口未定义,在其他设备中可正常调用。 972 973**参数:** 974 975| 参数名 | 类型 | 必填 | 说明 | 976| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 977| options | [DatePickerDialogOptions](arkui-ts/ts-methods-datepicker-dialog.md#datepickerdialogoptions对象说明) | 是 | 配置日期滑动选择器弹窗的参数。 | 978 979**示例:** 980 981```ts 982// xxx.ets 983@Entry 984@Component 985struct DatePickerDialogExample { 986 selectedDate: Date = new Date("2010-1-1"); 987 988 build() { 989 Column() { 990 Button("DatePickerDialog") 991 .margin(20) 992 .onClick(() => { 993 this.getUIContext().showDatePickerDialog({ 994 start: new Date("2000-1-1"), 995 end: new Date("2100-12-31"), 996 selected: this.selectedDate, 997 showTime: true, 998 useMilitaryTime: false, 999 dateTimeOptions: { hour: "numeric", minute: "2-digit" }, 1000 onDateAccept: (value: Date) => { 1001 // 通过Date的setFullYear方法设置按下确定按钮时的日期,这样当弹窗再次弹出时显示选中的是上一次确定的日期 1002 this.selectedDate = value; 1003 console.info("DatePickerDialog:onDateAccept()" + value.toString()); 1004 }, 1005 onCancel: () => { 1006 console.info("DatePickerDialog:onCancel()"); 1007 }, 1008 onDateChange: (value: Date) => { 1009 console.info("DatePickerDialog:onDateChange()" + value.toString()); 1010 }, 1011 onDidAppear: () => { 1012 console.info("DatePickerDialog:onDidAppear()"); 1013 }, 1014 onDidDisappear: () => { 1015 console.info("DatePickerDialog:onDidDisappear()"); 1016 }, 1017 onWillAppear: () => { 1018 console.info("DatePickerDialog:onWillAppear()"); 1019 }, 1020 onWillDisappear: () => { 1021 console.info("DatePickerDialog:onWillDisappear()"); 1022 } 1023 }) 1024 }) 1025 }.width('100%') 1026 } 1027} 1028``` 1029 1030## showTimePickerDialog 1031 1032showTimePickerDialog(options: TimePickerDialogOptions): void 1033 1034定义时间滑动选择器弹窗并弹出。 1035 1036> **说明:** 1037> 1038> 不支持在输入法类型窗口中使用子窗(showInSubwindow为true)的showTimePickerDialog,详情见输入法框架的约束与限制说明[createPanel](../apis-ime-kit/js-apis-inputmethodengine.md#createpanel10-1)。 1039 1040**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1041 1042**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1043 1044**设备行为差异:** 该接口在Wearable设备上使用时,应用程序运行异常,异常信息中提示接口未定义,在其他设备中可正常调用。 1045 1046**参数:** 1047 1048| 参数名 | 类型 | 必填 | 说明 | 1049| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 1050| options | [TimePickerDialogOptions](arkui-ts/ts-methods-timepicker-dialog.md#timepickerdialogoptions对象说明) | 是 | 配置时间滑动选择器弹窗的参数。 | 1051 1052**示例:** 1053 1054```ts 1055// xxx.ets 1056 1057class SelectTime{ 1058 selectTime: Date = new Date('2020-12-25T08:30:00'); 1059 hours(h:number,m:number){ 1060 this.selectTime.setHours(h, m); 1061 } 1062} 1063 1064@Entry 1065@Component 1066struct TimePickerDialogExample { 1067 @State selectTime: Date = new Date('2023-12-25T08:30:00'); 1068 1069 build() { 1070 Column() { 1071 Button('showTimePickerDialog') 1072 .margin(30) 1073 .onClick(() => { 1074 this.getUIContext().showTimePickerDialog({ 1075 selected: this.selectTime, 1076 onAccept: (value: TimePickerResult) => { 1077 // 设置selectTime为按下确定按钮时的时间,这样当弹窗再次弹出时显示选中的为上一次确定的时间 1078 let time = new SelectTime(); 1079 if(value.hour && value.minute){ 1080 time.hours(value.hour, value.minute); 1081 } 1082 console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)); 1083 }, 1084 onCancel: () => { 1085 console.info("TimePickerDialog:onCancel()"); 1086 }, 1087 onChange: (value: TimePickerResult) => { 1088 console.info("TimePickerDialog:onChange()" + JSON.stringify(value)); 1089 } 1090 }); 1091 }) 1092 }.width('100%').margin({ top: 5 }) 1093 } 1094} 1095``` 1096 1097## showTextPickerDialog 1098 1099showTextPickerDialog(options: TextPickerDialogOptions): void 1100 1101定义文本滑动选择器弹窗并弹出。 1102 1103> **说明:** 1104> 1105> 不支持在输入法类型窗口中使用子窗(showInSubwindow为true)的showTextPickerDialog,详情见输入法框架的约束与限制说明[createPanel](../apis-ime-kit/js-apis-inputmethodengine.md#createpanel10-1)。 1106 1107**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1108 1109**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1110 1111**设备行为差异:** 该接口在Wearable设备上使用时,应用程序运行异常,异常信息中提示接口未定义,在其他设备中可正常调用。 1112 1113**参数:** 1114 1115| 参数名 | 类型 | 必填 | 说明 | 1116| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 1117| options | [TextPickerDialogOptions](arkui-ts/ts-methods-textpicker-dialog.md#textpickerdialogoptions对象说明) | 是 | 配置文本滑动选择器弹窗的参数。 | 1118 1119**示例:** 1120 1121```ts 1122// xxx.ets 1123 1124class SelectedValue{ 1125 select: number = 2; 1126 set(val: number){ 1127 this.select = val; 1128 } 1129} 1130class SelectedArray{ 1131 select: number[] = []; 1132 set(val: number[]){ 1133 this.select = val; 1134 } 1135} 1136@Entry 1137@Component 1138struct TextPickerDialogExample { 1139 @State selectTime: Date = new Date('2023-12-25T08:30:00'); 1140 private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5']; 1141 private select: number = 0; 1142 build() { 1143 Column() { 1144 Button('showTextPickerDialog') 1145 .margin(30) 1146 .onClick(() => { 1147 this.getUIContext().showTextPickerDialog({ 1148 range: this.fruits, 1149 selected: this.select, 1150 onAccept: (value: TextPickerResult) => { 1151 // 设置select为按下确定按钮时候的选中项index,这样当弹窗再次弹出时显示选中的是上一次确定的选项 1152 let selectedVal = new SelectedValue(); 1153 let selectedArr = new SelectedArray(); 1154 if (value.index){ 1155 value.index instanceof Array?selectedArr.set(value.index) : selectedVal.set(value.index); 1156 } 1157 console.info("TextPickerDialog:onAccept()" + JSON.stringify(value)); 1158 }, 1159 onCancel: () => { 1160 console.info("TextPickerDialog:onCancel()"); 1161 }, 1162 onChange: (value: TextPickerResult) => { 1163 console.info("TextPickerDialog:onChange()" + JSON.stringify(value)); 1164 } 1165 }); 1166 }) 1167 }.width('100%').margin({ top: 5 }) 1168 } 1169} 1170``` 1171 1172## showTextPickerDialog<sup>20+</sup> 1173 1174showTextPickerDialog(style: TextPickerDialogOptions\|TextPickerDialogOptionsExt): void 1175 1176定义文本滑动选择器弹窗并弹出,相比API version 11,新增了TextPickerDialogOptionsExt参数支持。 1177 1178> **说明:** 1179> 1180> 不支持在输入法类型窗口中使用子窗(showInSubwindow为true)的showTextPickerDialog,详情见输入法框架的约束与限制说明[createPanel](../apis-ime-kit/js-apis-inputmethodengine.md#createpanel10-1)。 1181 1182**原子化服务API:** 从API version 20开始,该接口支持在原子化服务中使用。 1183 1184**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1185 1186**设备行为差异:** 该接口在Wearable设备上使用时,应用程序运行异常,异常信息中提示接口未定义,在其他设备中可正常调用。 1187 1188**参数:** 1189 1190| 参数名 | 类型 | 必填 | 说明 | 1191| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 1192| style | [TextPickerDialogOptions](arkui-ts/ts-methods-textpicker-dialog.md#textpickerdialogoptions对象说明)\| [TextPickerDialogOptionsExt](arkui-ts/ts-methods-textpicker-dialog.md#textpickerdialogoptionsext20对象说明) | 是 | 配置文本滑动选择器弹窗的参数。 | 1193 1194## createAnimator 1195 1196createAnimator(options: AnimatorOptions): AnimatorResult 1197 1198定义Animator类。 1199 1200**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1201 1202**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1203 1204**参数:** 1205 1206| 参数名 | 类型 | 必填 | 说明 | 1207| ------- | ---------------------------------------- | ---- | ------- | 1208| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) | 是 | 定义动画选项。 | 1209 1210**返回值:** 1211 1212| 类型 | 说明 | 1213| ---------------------------------------- | ------------- | 1214| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator结果接口。 | 1215 1216 1217**错误码**: 1218 1219以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。 1220 1221| 错误码ID | 错误信息 | 1222| ------- | -------- | 1223| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1224 1225**示例:** 1226 1227```ts 1228// EntryAbility.ets 1229import { UIAbility } from '@kit.AbilityKit'; 1230import { AnimatorOptions, window } from '@kit.ArkUI'; 1231import { hilog } from '@kit.PerformanceAnalysisKit'; 1232 1233export default class EntryAbility extends UIAbility { 1234 onWindowStageCreate(windowStage: window.WindowStage) { 1235 // 创建主窗口,设置此功能的主页 1236 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1237 windowStage.loadContent('pages/Index', (err, data) => { 1238 if (err.code) { 1239 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', err.message); 1240 return; 1241 } 1242 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1243 let uiContext = windowStage.getMainWindowSync().getUIContext(); 1244 let options:AnimatorOptions = { 1245 duration: 1500, 1246 easing: "friction", 1247 delay: 0, 1248 fill: "forwards", 1249 direction: "normal", 1250 iterations: 3, 1251 begin: 200.0, 1252 end: 400.0 1253 }; 1254 uiContext.createAnimator(options); 1255 }); 1256 } 1257} 1258``` 1259 1260## createAnimator<sup>18+</sup> 1261 1262createAnimator(options: AnimatorOptions | SimpleAnimatorOptions): AnimatorResult 1263 1264创建animator动画结果对象(AnimatorResult)。与[createAnimator](#createanimator)相比,新增对[SimpleAnimatorOptions](js-apis-animator.md#simpleanimatoroptions18)类型入参的支持。 1265 1266**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1267 1268**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1269 1270**参数:** 1271 1272| 参数名 | 类型 | 必填 | 说明 | 1273| ------- | ---------------------------------------- | ---- | ------- | 1274| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) \| [SimpleAnimatorOptions](js-apis-animator.md#simpleanimatoroptions18) | 是 | 定义动画选项。 | 1275 1276**返回值:** 1277 1278| 类型 | 说明 | 1279| ---------------------------------------- | ------------- | 1280| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator结果接口。 | 1281 1282**错误码**: 1283 1284以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。 1285 1286| 错误码ID | 错误信息 | 1287| ------- | -------- | 1288| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1289 1290**示例:** 1291 1292```ts 1293// EntryAbility.ets 1294import { UIAbility } from '@kit.AbilityKit'; 1295import { SimpleAnimatorOptions, window } from '@kit.ArkUI'; 1296import { hilog } from '@kit.PerformanceAnalysisKit'; 1297 1298export default class EntryAbility extends UIAbility { 1299 onWindowStageCreate(windowStage: window.WindowStage) { 1300 // 创建主窗口,设置此功能的主页 1301 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1302 windowStage.loadContent('pages/Index', (err, data) => { 1303 if (err.code) { 1304 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', err.message); 1305 return; 1306 } 1307 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1308 let uiContext = windowStage.getMainWindowSync().getUIContext(); 1309 let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).duration(2000); 1310 uiContext.createAnimator(options); 1311 }); 1312 } 1313} 1314``` 1315 1316## runScopedTask 1317 1318runScopedTask(callback: () => void): void 1319 1320在当前UI上下文执行传入的回调函数。 1321 1322**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1323 1324**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1325 1326**参数:** 1327 1328| 参数名 | 类型 | 必填 | 说明 | 1329| -------- | ---------- | ---- | ---- | 1330| callback | () => void | 是 | 回调函数 | 1331 1332**示例:** 1333 1334```ts 1335@Entry 1336@Component 1337struct Index { 1338 uiContext = this.getUIContext(); 1339 1340 build() { 1341 Row() { 1342 Column() { 1343 Button("run task").onClick(()=>{ 1344 this.uiContext.runScopedTask(()=>{ 1345 // do something 1346 }) 1347 }) 1348 } 1349 .width('100%') 1350 } 1351 .height('100%') 1352 } 1353} 1354``` 1355 1356## setKeyboardAvoidMode<sup>11+</sup> 1357 1358setKeyboardAvoidMode(value: KeyboardAvoidMode): void 1359 1360配置虚拟键盘弹出时,页面的避让模式。 1361 1362**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1363 1364**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1365 1366**参数:** 1367 1368| 参数名 | 类型 | 必填 | 说明 | 1369| -------- | ---------- | ---- | ---- | 1370| value | [KeyboardAvoidMode](arkts-apis-uicontext-e.md#keyboardavoidmode11)| 是 | 键盘弹出时的页面避让模式。<br />默认值:KeyboardAvoidMode.OFFSET | 1371 1372> **说明:** 1373> 1374> KeyboardAvoidMode.RESIZE模式会压缩页面大小,页面中设置百分比宽高的组件会跟随页面压缩,而直接设置宽高的组件会按设置的固定大小布局。设置KeyboardAvoidMode的RESIZE模式时,expandSafeArea([SafeAreaType.KEYBOARD],[SafeAreaEdge.BOTTOM])不生效。 1375> 1376> KeyboardAvoidMode.NONE模式配置页面不避让键盘,页面会被抬起的键盘遮盖。 1377> 1378> setKeyboardAvoidMode针对页面生效,对于弹窗类组件不生效,比如Dialog、Popup、Menu、BindSheet、BindContentCover、Toast、OverlayManager。弹窗类组件的避让模式可以参考[CustomDialogControllerOptions对象说明](./arkui-ts/ts-methods-custom-dialog-box.md#customdialogcontrolleroptions对象说明)。 1379 1380**示例:** 1381 1382完整示例请参考[示例4(设置键盘避让模式为压缩)](./arkui-ts/ts-universal-attributes-expand-safe-area.md#示例4设置键盘避让模式为压缩)、[示例5(设置键盘避让模式为上抬)](./arkui-ts/ts-universal-attributes-expand-safe-area.md#示例5设置键盘避让模式为上抬)以及[示例6(切换避让模式)](./arkui-ts/ts-universal-attributes-expand-safe-area.md#示例6切换避让模式)。 1383 1384<!--code_no_check--> 1385```ts 1386// EntryAbility.ets 1387import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI'; 1388import { hilog } from '@kit.PerformanceAnalysisKit'; 1389 1390export default class EntryAbility extends UIAbility{ 1391 onWindowStageCreate(windowStage: window.WindowStage) { 1392 // Main window is created, set main page for this ability 1393 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1394 1395 windowStage.loadContent('pages/Index', (err, data) => { 1396 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 1397 uiContext.setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE); 1398 if (err.code) { 1399 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1400 return; 1401 } 1402 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1403 }); 1404 } 1405} 1406``` 1407 1408## getKeyboardAvoidMode<sup>11+</sup> 1409 1410getKeyboardAvoidMode(): KeyboardAvoidMode 1411 1412获取虚拟键盘弹出时,页面的避让模式。 1413 1414**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1415 1416**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1417 1418**返回值:** 1419 1420| 类型 | 说明 | 1421| ---------- | ---- | 1422| [KeyboardAvoidMode](arkts-apis-uicontext-e.md#keyboardavoidmode11)| 返回当前的页面避让模式。| 1423 1424**示例:** 1425 1426完整示例请参考[示例4(设置键盘避让模式为压缩)](./arkui-ts/ts-universal-attributes-expand-safe-area.md#示例4设置键盘避让模式为压缩)、[示例5(设置键盘避让模式为上抬)](./arkui-ts/ts-universal-attributes-expand-safe-area.md#示例5设置键盘避让模式为上抬)以及[示例6(切换避让模式)](./arkui-ts/ts-universal-attributes-expand-safe-area.md#示例6切换避让模式)。 1427 1428<!--code_no_check--> 1429```ts 1430// EntryAbility.ets 1431import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI'; 1432import { hilog } from '@kit.PerformanceAnalysisKit'; 1433 1434export default class EntryAbility extends UIAbility{ 1435 onWindowStageCreate(windowStage: window.WindowStage) { 1436 // Main window is created, set main page for this ability 1437 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1438 1439 windowStage.loadContent('pages/Index', (err, data) => { 1440 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 1441 let KeyboardAvoidMode = uiContext.getKeyboardAvoidMode(); 1442 hilog.info(0x0000, "KeyboardAvoidMode:", JSON.stringify(KeyboardAvoidMode)); 1443 if (err.code) { 1444 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1445 return; 1446 } 1447 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1448 }); 1449 } 1450} 1451``` 1452 1453## getAtomicServiceBar<sup>11+</sup> 1454 1455getAtomicServiceBar(): Nullable\<AtomicServiceBar> 1456 1457获取AtomicServiceBar对象,通过该对象设置原子化服务menuBar的属性。 1458 1459**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1460 1461**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1462 1463**返回值:** 1464 1465| 类型 | 说明 | 1466| ------------------------------------------------- | ------------------------------------------------------------ | 1467| Nullable<[AtomicServiceBar](arkts-apis-uicontext-atomicservicebar.md)> | 如果是原子化服务则返回AtomicServerBar类型,否则返回undefined。 | 1468 1469**示例:** 1470 1471```ts 1472// EntryAbility.ets 1473import { UIAbility } from '@kit.AbilityKit'; 1474import { UIContext, AtomicServiceBar, window } from '@kit.ArkUI'; 1475 1476export default class EntryAbility extends UIAbility { 1477 onWindowStageCreate(windowStage: window.WindowStage) { 1478 // Main window is created, set main page for this ability 1479 console.info('Ability onWindowStageCreate'); 1480 windowStage.loadContent('pages/Index', (err, data) => { 1481 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 1482 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 1483 if (atomicServiceBar != undefined) { 1484 console.info('Get AtomServiceBar Successfully.'); 1485 } else { 1486 console.error('Get AtomicServiceBar failed.'); 1487 } 1488 }); 1489 } 1490} 1491``` 1492## getDragController<sup>11+</sup> 1493 1494getDragController(): DragController 1495 1496获取DragController对象,可通过该对象创建并发起拖拽。 1497 1498**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1499 1500**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1501 1502**返回值:** 1503 1504|类型|说明| 1505|----|----| 1506|[DragController](js-apis-arkui-dragController.md)| 获取DragController对象。| 1507 1508**示例:** 1509 1510完整示例请参考[DragController](./arkts-apis-uicontext-dragcontroller.md)中的示例。 1511 1512## keyframeAnimateTo<sup>11+</sup> 1513 1514keyframeAnimateTo(param: KeyframeAnimateParam, keyframes: Array<KeyframeState>): void 1515 1516产生关键帧动画。该接口的使用说明请参考[keyframeAnimateTo](arkui-ts/ts-keyframeAnimateTo.md)。 1517 1518**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1519 1520**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1521 1522**参数:** 1523 1524| 参数名 | 类型 | 必填 | 说明 | 1525| ------------ | ---------------------------------------------------- | ------- | ---------------------------- | 1526| param | [KeyframeAnimateParam](arkui-ts/ts-keyframeAnimateTo.md#keyframeanimateparam对象说明) | 是 | 关键帧动画的整体动画参数。 | 1527| keyframes | Array<[KeyframeState](arkui-ts/ts-keyframeAnimateTo.md#keyframestate对象说明)> | 是 | 所有的关键帧状态的列表。 | 1528 1529**示例:** 1530 1531```ts 1532// xxx.ets 1533import { UIContext } from '@kit.ArkUI'; 1534 1535@Entry 1536@Component 1537struct KeyframeDemo { 1538 @State myScale: number = 1.0; 1539 uiContext: UIContext | undefined = undefined; 1540 1541 aboutToAppear() { 1542 this.uiContext = this.getUIContext(); 1543 } 1544 1545 build() { 1546 Column() { 1547 Circle() 1548 .width(100) 1549 .height(100) 1550 .fill("#46B1E3") 1551 .margin(100) 1552 .scale({ x: this.myScale, y: this.myScale }) 1553 .onClick(() => { 1554 if (!this.uiContext) { 1555 console.error("no uiContext, keyframe failed"); 1556 return; 1557 } 1558 this.myScale = 1; 1559 // 设置关键帧动画整体播放3次 1560 this.uiContext.keyframeAnimateTo({ 1561 iterations: 3, 1562 expectedFrameRateRange: { 1563 min: 10, 1564 max: 120, 1565 expected: 60, 1566 } 1567 }, [ 1568 { 1569 // 第一段关键帧动画时长为800ms,scale属性做从1到1.5的动画 1570 duration: 800, 1571 event: () => { 1572 this.myScale = 1.5; 1573 } 1574 }, 1575 { 1576 // 第二段关键帧动画时长为500ms,scale属性做从1.5到1的动画 1577 duration: 500, 1578 event: () => { 1579 this.myScale = 1; 1580 } 1581 } 1582 ]); 1583 }) 1584 }.width('100%').margin({ top: 5 }) 1585 } 1586} 1587``` 1588 1589## getFocusController<sup>12+</sup> 1590 1591getFocusController(): FocusController 1592 1593获取[FocusController](arkts-apis-uicontext-focuscontroller.md)对象,可通过该对象控制焦点。 1594 1595**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1596 1597**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1598 1599**返回值:** 1600 1601|类型|说明| 1602|----|----| 1603|[FocusController](arkts-apis-uicontext-focuscontroller.md)| 获取FocusController对象。| 1604 1605**示例:** 1606 1607完整示例请参考[FocusController](arkts-apis-uicontext-focuscontroller.md)中的示例。 1608 1609## getFilteredInspectorTree<sup>12+</sup> 1610 1611getFilteredInspectorTree(filters?: Array\<string\>): string 1612 1613获取组件树及组件属性。此接口耗时较长,仅适用于测试场景。 1614 1615**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1616 1617**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1618 1619**参数:** 1620 1621| 参数名 | 类型 | 必填 | 说明 | 1622| ------- | --------------- | ---- | ------------------------------------------------------------ | 1623| filters | Array\<string\> | 否 | 需要获取的组件属性的过滤列表。目前仅支持过滤字段:<br/>"id":组件唯一标识。<br/>"src":资源来源。 <br/>"content":元素、组件或对象所包含的信息或数据。<br/>"editable":是否可编辑。<br/>"scrollable":是否可滚动。<br/>"selectable":是否可选择。<br/>"focusable":是否可聚焦。<br/>"focused":是否已聚焦。<br/>如果在filters参数中包含以上一个或者多个字段,则未包含的字段会在组件属性查询结果中被过滤掉。如果用户未传入filters参数或者filters参数为空数组,则以上字段全部不会在组件属性查询结果中被过滤掉。<br/>从API version 20开始,支持该过滤字段:<br/>"isLayoutInspector":返回组件树是否包含[自定义组件](../../ui/state-management/arkts-create-custom-components.md)。如果用户未传入filters参数或者filters数组不包含isLayoutInspector,返回的组件树将缺少自定义组件的信息。<br/>其余字段仅供测试场景使用。 | 1624 1625**返回值:** 1626 1627| 类型 | 说明 | 1628| ------ | ---------------------------------- | 1629| string | 获取组件树及组件属性的JSON字符串。组件中每个字段的含义请参考[getInspectorInfo](./js-apis-arkui-frameNode.md#getinspectorinfo12)的返回值说明。 | 1630 1631**错误码**: 1632 1633以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。 1634 1635| 错误码ID | 错误信息 | 1636| ------- | -------- | 1637| 401 | Parameter error. Possible causes: <br /> 1. Mandatory parameters are left unspecified. <br /> 2. Incorrect parameters types. <br /> 3. Parameter verification failed. | 1638 1639**示例:** 1640 1641<!--code_no_check--> 1642```ts 1643uiContext.getFilteredInspectorTree(['id', 'src', 'content']); 1644``` 1645 1646<!--code_no_check--> 1647```ts 1648// xxx.ets 1649import { UIContext } from '@kit.ArkUI'; 1650@Entry 1651@Component 1652struct ComponentPage { 1653 loopConsole(inspectorStr: string, i: string) { 1654 console.info(`InsTree ${i}| type: ${JSON.parse(inspectorStr).$type}, ID: ${JSON.parse(inspectorStr).$ID}`); 1655 if (JSON.parse(inspectorStr).$children) { 1656 i += '-'; 1657 for (let index = 0; index < JSON.parse(inspectorStr).$children.length; index++) { 1658 this.loopConsole(JSON.stringify(JSON.parse(inspectorStr).$children[index]), i); 1659 } 1660 } 1661 } 1662 1663 build() { 1664 Column() { 1665 Button('content').onClick(() => { 1666 const uiContext: UIContext = this.getUIContext(); 1667 let inspectorStr = uiContext.getFilteredInspectorTree(['content']); 1668 console.info(`InsTree : ${inspectorStr}`); 1669 inspectorStr = JSON.stringify(JSON.parse(inspectorStr)); 1670 this.loopConsole(inspectorStr, '-'); 1671 }) 1672 Button('isLayoutInspector').onClick(() => { 1673 const uiContext: UIContext = this.getUIContext(); 1674 let inspectorStr = uiContext.getFilteredInspectorTree(['isLayoutInspector']); 1675 console.info(`InsTree : ${inspectorStr}`); 1676 inspectorStr = JSON.stringify(JSON.parse(inspectorStr).content); 1677 this.loopConsole(inspectorStr, '-'); 1678 }) 1679 } 1680 .width('100%') 1681 .height('100%') 1682 } 1683} 1684``` 1685 1686当传入"content"过滤字段时,返回的JSON字符串结构如下: 1687 1688<!--code_no_check--> 1689```ts 1690InsTree : {"$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":{}}]}]}\ 1691InsTree -| type: root, ID: undefined 1692InsTree --| type: Column, ID: 15 1693InsTree ---| type: Button, ID: 16 1694InsTree ---| type: Button, ID: 18 1695``` 1696 1697从API version 20开始,当传入"isLayoutInspector"过滤字段时,返回的JSON字符串结构新增外层结构"type"与"content",其中"content"包含未增加该字段时的原有JSON字符串结构;同时,返回值结构中增添自定义组件。返回的JSON字符串结构如下: 1698 1699<!--code_no_check--> 1700```ts 1701InsTree : {"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":{ ... 1702InsTree -| type: root, ID: undefined 1703InsTree --| type: JsView, ID: 13 1704InsTree ---| type: Column, ID: 15 1705InsTree ----| type: Button, ID: 16 1706InsTree ----| type: Button, ID: 18 1707``` 1708 1709## getFilteredInspectorTreeById<sup>12+</sup> 1710 1711getFilteredInspectorTreeById(id: string, depth: number, filters?: Array\<string\>): string 1712 1713获取指定的组件及其子组件的属性。此接口耗时较长,仅适用于测试场景。 1714 1715**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1716 1717**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1718 1719**参数:** 1720 1721| 参数名 | 类型 | 必填 | 说明 | 1722| ------- | --------------- | ---- | ------------------------------------------------------------ | 1723| id | string | 是 | 指定的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)id。 | 1724| depth | number | 是 | 获取子组件的层数。当取值0时,获取指定的组件及其所有的子孙组件的属性。当取值1时,仅获取指定的组件的属性。当取值2时,指定的组件及其1层子组件的属性。以此类推。 | 1725| filters | Array\<string\> | 否 | 需要获取的组件属性的过滤列表。目前仅支持过滤字段:<br/>"id":组件唯一标识。<br/>"src":资源来源。 <br/>"content":元素、组件或对象所包含的信息或数据。<br/>"editable":是否可编辑。<br/>"scrollable":是否可滚动。<br/>"selectable":是否可选择。<br/>"focusable":是否可聚焦。<br/>"focused":是否已聚焦。<br/>如果在filters参数中包含以上一个或者多个字段,则未包含的字段会在组件属性查询结果中被过滤掉。如果用户未传入filters参数或者filters参数为空数组,则以上字段全部不会在组件属性查询结果中被过滤掉。<br/>其余字段仅供测试场景使用。 | 1726 1727**返回值:** 1728 1729| 类型 | 说明 | 1730| ------ | -------------------------------------------- | 1731| string | 获取指定的组件及其子组件的属性的JSON字符串。组件中每个字段的含义请参考[getInspectorInfo](./js-apis-arkui-frameNode.md#getinspectorinfo12)的返回值说明。 | 1732 1733 1734**错误码**: 1735 1736以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。 1737 1738| 错误码ID | 错误信息 | 1739| ------- | -------- | 1740| 401 | Parameter error. Possible causes: <br /> 1. Mandatory parameters are left unspecified. <br /> 2. Incorrect parameters types. <br /> 3. Parameter verification failed. | 1741 1742**示例:** 1743 1744<!--code_no_check--> 1745```ts 1746uiContext.getFilteredInspectorTreeById('testId', 0, ['id', 'src', 'content']); 1747``` 1748 1749<!--code_no_check--> 1750```ts 1751import { UIContext } from '@kit.ArkUI'; 1752@Entry 1753@Component 1754struct ComponentPage { 1755 build() { 1756 Column() { 1757 Text("Hello World") 1758 .fontSize(20) 1759 .id("TEXT") 1760 Button('getFilteredInspectorTreeById').onClick(() => { 1761 const uiContext: UIContext = this.getUIContext(); 1762 try { 1763 let inspectorStr = uiContext.getFilteredInspectorTreeById('TEXT', 1, ["id", "src"]); 1764 console.info(`result1: ${inspectorStr}`); 1765 inspectorStr = JSON.stringify(JSON.parse(inspectorStr)['$children'][0]); 1766 console.info(`result2: ${inspectorStr}`); 1767 inspectorStr = uiContext.getFilteredInspectorTreeById('TEXT', 1, ["src"]); 1768 inspectorStr = JSON.stringify(JSON.parse(inspectorStr)['$children'][0]); 1769 console.info(`result3: ${inspectorStr}`); 1770 } catch(e) { 1771 console.info(`getFilteredInspectorTreeById error: ${e}`); 1772 } 1773 }) 1774 } 1775 .width('100%') 1776 .height('100%') 1777 } 1778} 1779``` 1780返回的JSON字符串结构如下: 1781<!--code_no_check--> 1782```ts 1783result1: {"$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}}]} 1784result2: {"$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}} 1785result3: {"$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}} 1786``` 1787若需获取getFilteredInspectorTreeById方法中首个参数id指定的组件,须参照示例代码将getFilteredInspectorTreeById方法结果先转换为json对象,随后提取$children数组的首项。通过result2和result3的结果对比可知,如果filters参数由["id", "src"]改为["src"],获取到的\$attrs属性将缺少"id"这一key。 1788 1789## getCursorController<sup>12+</sup> 1790 1791getCursorController(): CursorController 1792 1793获取[CursorController](arkts-apis-uicontext-cursorcontroller.md)对象,可通过该对象控制光标。 1794 1795**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1796 1797**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1798 1799**返回值:** 1800 1801|类型|说明| 1802|----|----| 1803|[CursorController](arkts-apis-uicontext-cursorcontroller.md)| 获取CursorController对象。| 1804 1805**示例:** 1806 1807完整示例请参考[CursorController](arkts-apis-uicontext-contextmenucontroller.md)中的示例。 1808 1809## getContextMenuController<sup>12+</sup> 1810 1811getContextMenuController(): ContextMenuController 1812 1813获取[ContextMenuController](arkts-apis-uicontext-contextmenucontroller.md)对象,可通过该对象控制菜单。 1814 1815**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1816 1817**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1818 1819**返回值:** 1820 1821|类型|说明| 1822|----|----| 1823|[ContextMenuController](arkts-apis-uicontext-contextmenucontroller.md)| 获取ContextMenuController对象。| 1824 1825## getMeasureUtils<sup>12+</sup> 1826 1827getMeasureUtils(): MeasureUtils 1828 1829允许用户通过UIContext对象,获取MeasureUtils对象进行文本计算。 1830 1831**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1832 1833**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1834 1835**返回值:** 1836 1837| 类型 | 说明 | 1838| ------ | -------------------------------------------- | 1839| [MeasureUtils](arkts-apis-uicontext-measureutils.md) | 提供文本宽度、高度等相关计算。 | 1840 1841**示例:** 1842 1843完整示例请参考[MeasureUtils](arkts-apis-uicontext-measureutils.md)中的示例。 1844 1845## getComponentSnapshot<sup>12+</sup> 1846 1847getComponentSnapshot(): ComponentSnapshot 1848 1849获取ComponentSnapshot对象,可通过该对象获取组件截图的能力。 1850 1851典型使用场景(如长截图)及最佳实践请参考[使用组件截图](../../ui/arkts-uicontext-component-snapshot.md)。 1852 1853**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1854 1855**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1856 1857**返回值:** 1858 1859| 类型 | 说明 | 1860| ------------------------------------------------------------ | --------------------------- | 1861| [ComponentSnapshot](arkts-apis-uicontext-componentsnapshot.md) | 获取ComponentSnapshot对象。 | 1862 1863**示例:** 1864 1865完整示例请参考[ComponentSnapshot](arkts-apis-uicontext-componentsnapshot.md)中的示例。 1866 1867## vp2px<sup>12+</sup> 1868 1869vp2px(value : number) : number 1870 1871将vp单位的数值转换为以px为单位的数值。 1872 1873转换公式为:px值 = vp值 × 像素密度 1874 1875像素密度:当前窗口生效的像素密度值,即屏幕物理像素密度[VirtualScreenConfig.density](js-apis-display.md#virtualscreenconfig16)。 1876 1877> **说明:** 1878> 1879> getUIContext需在[windowStage.loadContent](./arkts-apis-window-WindowStage.md#loadcontent9)之后调用,确保UIContext初始化完成后调用此接口,否则无法返回准确结果。 1880 1881**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1882 1883**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1884 1885**参数:** 1886 1887| 参数名 | 类型 | 必填 | 说明 | 1888| ------ | ------ | ---- | -------------------------------------- | 1889| value | number | 是 | 将vp单位的数值转换为以px为单位的数值。<br/>取值范围:(-∞, +∞) | 1890 1891**返回值:** 1892 1893| 类型 | 说明 | 1894| ------ | -------------- | 1895| number | 转换后的数值。<br/>取值范围:(-∞, +∞) | 1896 1897**示例:** 1898 1899```ts 1900@Entry 1901@Component 1902struct MatrixExample { 1903 build() { 1904 Column({ space: 100 }) { 1905 Text('Hello1') 1906 .textAlign(TextAlign.Center) 1907 .width(100) 1908 .height(60) 1909 .backgroundColor(0xAFEEEE) 1910 .borderWidth(1) 1911 .rotate({ 1912 z: 1, 1913 angle: 90, 1914 centerX: this.getUIContext().vp2px(50), 1915 centerY: this.getUIContext().vp2px(30) 1916 }) 1917 }.width('100%') 1918 .height('100%') 1919 } 1920} 1921``` 1922 1923## px2vp<sup>12+</sup> 1924 1925px2vp(value : number) : number 1926 1927将px单位的数值转换为以vp为单位的数值。 1928 1929转换公式为:vp值 = px值 ÷ 像素密度 1930 1931像素密度:当前窗口生效的像素密度值,即屏幕物理像素密度[VirtualScreenConfig.density](js-apis-display.md#virtualscreenconfig16)。 1932 1933> **说明:** 1934> 1935> getUIContext需在[windowStage.loadContent](./arkts-apis-window-WindowStage.md#loadcontent9)之后调用,确保UIContext初始化完成后调用此接口,否则无法返回准确结果。 1936 1937**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1938 1939**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1940 1941**参数:** 1942 1943| 参数名 | 类型 | 必填 | 说明 | 1944| ------ | ------ | ---- | -------------------------------------- | 1945| value | number | 是 | 将px单位的数值转换为以vp为单位的数值。<br/>取值范围:(-∞, +∞) | 1946 1947**返回值:** 1948 1949| 类型 | 说明 | 1950| ------ | -------------- | 1951| number | 转换后的数值。<br/>取值范围:(-∞, +∞) | 1952 1953**示例:** 1954 1955```ts 1956@Entry 1957@Component 1958struct MatrixExample { 1959 build() { 1960 Column({ space: 100 }) { 1961 Text('Hello1') 1962 .textAlign(TextAlign.Center) 1963 .width(100) 1964 .height(60) 1965 .backgroundColor(0xAFEEEE) 1966 .borderWidth(1) 1967 .rotate({ 1968 z: 1, 1969 angle: 90, 1970 centerX: this.getUIContext().px2vp(50), 1971 centerY: this.getUIContext().px2vp(30) 1972 }) 1973 }.width('100%') 1974 .height('100%') 1975 } 1976} 1977``` 1978 1979## fp2px<sup>12+</sup> 1980 1981fp2px(value : number) : number 1982 1983将fp单位的数值转换为以px为单位的数值。 1984 1985转换公式为:px值 = fp值 × 像素密度 × 字体缩放比例 1986 1987像素密度:当前窗口生效的像素密度值,即屏幕物理像素密度[VirtualScreenConfig.density](js-apis-display.md#virtualscreenconfig16)。 1988 1989字体缩放比例:系统设置的字体缩放系数,对应 [Configuration.fontScale](arkui-ts/ts-types.md#configuration)。 1990 1991> **说明:** 1992> 1993> getUIContext需在[windowStage.loadContent](./arkts-apis-window-WindowStage.md#loadcontent9)之后调用,确保UIContext初始化完成后调用此接口,否则无法返回准确结果。 1994 1995**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1996 1997**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1998 1999**参数:** 2000 2001| 参数名 | 类型 | 必填 | 说明 | 2002| ------ | ------ | ---- | -------------------------------------- | 2003| value | number | 是 | 将fp单位的数值转换为以px为单位的数值。<br/>取值范围:(-∞, +∞) | 2004 2005**返回值:** 2006 2007| 类型 | 说明 | 2008| ------ | -------------- | 2009| number | 转换后的数值。<br/>取值范围:(-∞, +∞) | 2010 2011**示例:** 2012 2013```ts 2014@Entry 2015@Component 2016struct MatrixExample { 2017 build() { 2018 Column({ space: 100 }) { 2019 Text('Hello1') 2020 .textAlign(TextAlign.Center) 2021 .width(100) 2022 .height(60) 2023 .backgroundColor(0xAFEEEE) 2024 .borderWidth(1) 2025 .rotate({ 2026 z: 1, 2027 angle: 90, 2028 centerX: this.getUIContext().fp2px(50), 2029 centerY: this.getUIContext().fp2px(30) 2030 }) 2031 }.width('100%') 2032 .height('100%') 2033 } 2034} 2035``` 2036 2037## px2fp<sup>12+</sup> 2038 2039px2fp(value : number) : number 2040 2041将px单位的数值转换为以fp为单位的数值。 2042 2043转换公式为:fp值 = px值 ÷ 像素密度 ÷ 字体缩放比例 2044 2045像素密度:当前窗口生效的像素密度值,通常就是屏幕物理像素密度[VirtualScreenConfig.density](js-apis-display.md#virtualscreenconfig16)。 2046 2047字体缩放比例:系统设置的字体缩放系数,对应 [Configuration.fontScale](arkui-ts/ts-types.md#configuration)。 2048 2049> **说明:** 2050> 2051> getUIContext需在[windowStage.loadContent](./arkts-apis-window-WindowStage.md#loadcontent9)之后调用,确保UIContext初始化完成后调用此接口,否则无法返回准确结果。 2052 2053**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2054 2055**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2056 2057**参数:** 2058 2059| 参数名 | 类型 | 必填 | 说明 | 2060| ------ | ------ | ---- | -------------------------------------- | 2061| value | number | 是 | 将px单位的数值转换为以fp为单位的数值。<br/>取值范围:(-∞, +∞) | 2062 2063**返回值:** 2064 2065| 类型 | 说明 | 2066| ------ | -------------- | 2067| number | 转换后的数值。<br/>取值范围:(-∞, +∞) | 2068 2069**示例:** 2070 2071```ts 2072@Entry 2073@Component 2074struct MatrixExample { 2075 build() { 2076 Column({ space: 100 }) { 2077 Text('Hello1') 2078 .textAlign(TextAlign.Center) 2079 .width(100) 2080 .height(60) 2081 .backgroundColor(0xAFEEEE) 2082 .borderWidth(1) 2083 .rotate({ 2084 z: 1, 2085 angle: 90, 2086 centerX: this.getUIContext().px2fp(50), 2087 centerY: this.getUIContext().px2fp(30) 2088 }) 2089 }.width('100%') 2090 .height('100%') 2091 } 2092} 2093``` 2094 2095## lpx2px<sup>12+</sup> 2096 2097lpx2px(value : number) : number 2098 2099将lpx单位的数值转换为以px为单位的数值。 2100 2101转换公式为:px值 = lpx值 × 实际屏幕宽度与逻辑宽度(通过[designWidth](../../quick-start/module-configuration-file.md#pages标签)配置)的比值。 2102 2103> **说明:** 2104> 2105> getUIContext需在[windowStage.loadContent](./arkts-apis-window-WindowStage.md#loadcontent9)之后调用,确保UIContext初始化完成后调用此接口,否则无法返回准确结果。 2106 2107**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2108 2109**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2110 2111**参数:** 2112 2113| 参数名 | 类型 | 必填 | 说明 | 2114| ------ | ------ | ---- | --------------------------------------- | 2115| value | number | 是 | 将lpx单位的数值转换为以px为单位的数值。<br/>取值范围:(-∞, +∞) | 2116 2117**返回值:** 2118 2119| 类型 | 说明 | 2120| ------ | -------------- | 2121| number | 转换后的数值。<br/>取值范围:(-∞, +∞) | 2122 2123**示例:** 2124 2125```ts 2126@Entry 2127@Component 2128struct MatrixExample { 2129 build() { 2130 Column({ space: 100 }) { 2131 Text('Hello1') 2132 .textAlign(TextAlign.Center) 2133 .width(100) 2134 .height(60) 2135 .backgroundColor(0xAFEEEE) 2136 .borderWidth(1) 2137 .rotate({ 2138 z: 1, 2139 angle: 90, 2140 centerX: this.getUIContext().lpx2px(50), 2141 centerY: this.getUIContext().lpx2px(30) 2142 }) 2143 }.width('100%') 2144 .height('100%') 2145 } 2146} 2147``` 2148 2149## px2lpx<sup>12+</sup> 2150 2151px2lpx(value : number) : number 2152 2153将px单位的数值转换为以lpx为单位的数值。 2154 2155转换公式为:lpx值 = px值 ÷ 实际屏幕宽度与逻辑宽度(通过[designWidth](../../quick-start/module-configuration-file.md#pages标签)配置)的比值。 2156 2157> **说明:** 2158> 2159> getUIContext需在[windowStage.loadContent](./arkts-apis-window-WindowStage.md#loadcontent9)之后调用,确保UIContext初始化完成后调用此接口,否则无法返回准确结果。 2160 2161**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2162 2163**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2164 2165**参数:** 2166 2167| 参数名 | 类型 | 必填 | 说明 | 2168| ------ | ------ | ---- | --------------------------------------- | 2169| value | number | 是 | 将px单位的数值转换为以lpx为单位的数值。<br/>取值范围:(-∞, +∞) | 2170 2171**返回值:** 2172 2173| 类型 | 说明 | 2174| ------ | -------------- | 2175| number | 转换后的数值。<br/>取值范围:(-∞, +∞) | 2176 2177**示例:** 2178 2179```ts 2180@Entry 2181@Component 2182struct MatrixExample { 2183 build() { 2184 Column({ space: 100 }) { 2185 Text('Hello1') 2186 .textAlign(TextAlign.Center) 2187 .width(100) 2188 .height(60) 2189 .backgroundColor(0xAFEEEE) 2190 .borderWidth(1) 2191 .rotate({ 2192 z: 1, 2193 angle: 90, 2194 centerX: this.getUIContext().px2lpx(50), 2195 centerY: this.getUIContext().px2lpx(30) 2196 }) 2197 }.width('100%') 2198 .height('100%') 2199 } 2200} 2201``` 2202 2203## getWindowName<sup>12+</sup> 2204 2205getWindowName(): string | undefined 2206 2207获取当前实例所在窗口的名称。 2208 2209**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2210 2211**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2212 2213**返回值:** 2214 2215| 类型 | 说明 | 2216| ------ | -------------------------------------------- | 2217| string \| undefined | 当前实例所在窗口的名称。若窗口不存在,则返回undefined。 | 2218 2219**示例:** 2220 2221```ts 2222import { window } from '@kit.ArkUI'; 2223 2224@Entry 2225@Component 2226struct Index { 2227 @State message: string = 'Hello World'; 2228 2229 aboutToAppear() { 2230 const windowName = this.getUIContext().getWindowName(); 2231 console.info('WindowName ' + windowName); 2232 const currWindow = window.findWindow(windowName); 2233 const windowProperties = currWindow.getWindowProperties(); 2234 console.info(`Window width ${windowProperties.windowRect.width}, height ${windowProperties.windowRect.height}`); 2235 } 2236 2237 build() { 2238 Row() { 2239 Column() { 2240 Text(this.message) 2241 .fontSize(50) 2242 .fontWeight(FontWeight.Bold) 2243 } 2244 .width('100%') 2245 } 2246 .height('100%') 2247 } 2248} 2249``` 2250 2251## getWindowWidthBreakpoint<sup>13+</sup> 2252 2253getWindowWidthBreakpoint(): WidthBreakpoint 2254 2255获取当前实例所在窗口的宽度断点枚举值。具体枚举值根据窗口宽度vp值确定,详见 [WidthBreakpoint](./arkui-ts/ts-appendix-enums.md#widthbreakpoint13)。 2256 2257**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2258 2259**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2260 2261**返回值:** 2262 2263| 类型 | 说明 | 2264| ------ | -------------------------------------------- | 2265| [WidthBreakpoint](./arkui-ts/ts-appendix-enums.md#widthbreakpoint13) | 当前实例所在窗口的宽度断点枚举值。若窗口宽度为 0vp,则返回WIDTH_XS。 | 2266 2267**示例:** 2268 2269```ts 2270import { UIContext } from '@kit.ArkUI'; 2271 2272@Entry 2273@Component 2274struct Index { 2275 @State message: string = 'Hello World'; 2276 2277 build() { 2278 Row() { 2279 Column() { 2280 Text(this.message) 2281 .fontSize(30) 2282 .fontWeight(FontWeight.Bold) 2283 Button() { 2284 Text('test') 2285 .fontSize(30) 2286 } 2287 .onClick(() => { 2288 let uiContext: UIContext = this.getUIContext(); 2289 let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint(); 2290 console.info(`Window widthBp: ${widthBp}`); 2291 }) 2292 } 2293 .width('100%') 2294 } 2295 .height('100%') 2296 } 2297} 2298``` 2299 2300## getWindowHeightBreakpoint<sup>13+</sup> 2301 2302getWindowHeightBreakpoint(): HeightBreakpoint 2303 2304获取当前实例所在窗口的高度断点。具体枚举值根据窗口高宽比确定,详见 [HeightBreakpoint](./arkui-ts/ts-appendix-enums.md#heightbreakpoint13)。 2305 2306**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2307 2308**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2309 2310**返回值:** 2311 2312| 类型 | 说明 | 2313| ------ | -------------------------------------------- | 2314| [HeightBreakpoint](./arkui-ts/ts-appendix-enums.md#heightbreakpoint13) | 当前实例所在窗口的宽高比对应的高度断点枚举值。若窗口高宽比为0,则返回HEIGHT_SM。 | 2315 2316**示例:** 2317 2318```ts 2319import { UIContext } from '@kit.ArkUI'; 2320 2321@Entry 2322@Component 2323struct Index { 2324 @State message: string = 'Hello World'; 2325 2326 build() { 2327 Row() { 2328 Column() { 2329 Text(this.message) 2330 .fontSize(30) 2331 .fontWeight(FontWeight.Bold) 2332 Button() { 2333 Text('test') 2334 .fontSize(30) 2335 } 2336 .onClick(() => { 2337 let uiContext: UIContext = this.getUIContext(); 2338 let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint(); 2339 let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint(); 2340 console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`); 2341 }) 2342 } 2343 .width('100%') 2344 } 2345 .height('100%') 2346 } 2347} 2348``` 2349 2350## postFrameCallback<sup>12+</sup> 2351 2352postFrameCallback(frameCallback: FrameCallback): void 2353 2354注册一个回调,仅在下一帧渲染时调用。 2355 2356**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2357 2358**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2359 2360**参数:** 2361 2362| 参数名 | 类型 | 必填 | 说明 | 2363| ------ | ------ | ---- | --------------------------------------- | 2364| frameCallback | [FrameCallback](arkts-apis-uicontext-framecallback.md) | 是 | 下一帧需要执行的回调。 | 2365 2366**示例:** 2367 2368```ts 2369import {FrameCallback } from '@kit.ArkUI'; 2370 2371class MyFrameCallback extends FrameCallback { 2372 private tag: string; 2373 2374 constructor(tag: string) { 2375 super(); 2376 this.tag = tag; 2377 } 2378 2379 onFrame(frameTimeNanos: number) { 2380 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 2381 } 2382} 2383 2384@Entry 2385@Component 2386struct Index { 2387 build() { 2388 Row() { 2389 Button('点击触发postFrameCallback') 2390 .onClick(() => { 2391 this.getUIContext().postFrameCallback(new MyFrameCallback("normTask")); 2392 }) 2393 } 2394 } 2395} 2396``` 2397 2398## postDelayedFrameCallback<sup>12+</sup> 2399 2400postDelayedFrameCallback(frameCallback: FrameCallback, delayTime: number): void 2401 2402注册一个回调,在延迟一段时间后的下一帧进行渲染时执行。 2403 2404**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2405 2406**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2407 2408**参数:** 2409 2410| 参数名 | 类型 | 必填 | 说明 | 2411| ------ | ------ | ---- | --------------------------------------- | 2412| frameCallback | [FrameCallback](arkts-apis-uicontext-framecallback.md) | 是 | 下一帧需要执行的回调。 | 2413| delayTime | number | 是 | 延迟的时间,以毫秒为单位。传入null、undefined或小于0的值,会按0处理。 | 2414 2415**示例:** 2416 2417```ts 2418import {FrameCallback } from '@kit.ArkUI'; 2419 2420class MyFrameCallback extends FrameCallback { 2421 private tag: string; 2422 2423 constructor(tag: string) { 2424 super(); 2425 this.tag = tag; 2426 } 2427 2428 onFrame(frameTimeNanos: number) { 2429 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 2430 } 2431} 2432 2433@Entry 2434@Component 2435struct Index { 2436 build() { 2437 Row() { 2438 Button('点击触发postDelayedFrameCallback') 2439 .onClick(() => { 2440 this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5); 2441 }) 2442 } 2443 } 2444} 2445``` 2446 2447## requireDynamicSyncScene<sup>12+</sup> 2448 2449requireDynamicSyncScene(id: string): Array<DynamicSyncScene> 2450 2451请求组件的动态帧率场景,用于自定义场景相关帧率配置。 2452 2453**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2454 2455**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2456 2457**参数:** 2458 2459| 参数名 | 类型 | 必填 | 说明 | 2460| ------ | ------ | ---- | --------------------------------------- | 2461| id | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。| 2462 2463**返回值:** 2464 2465| 类型 | 说明 | 2466| ------ | -------------------------------------------- | 2467| Array<DynamicSyncScene> | 获取DynamicSyncScene对象数组。 | 2468 2469**示例:** 2470 2471```ts 2472import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI'; 2473 2474@Entry 2475@Component 2476struct Frame { 2477 @State ANIMATION: ExpectedFrameRateRange = { min: 0, max: 120, expected: 90 }; 2478 @State GESTURE: ExpectedFrameRateRange = { min: 0, max: 120, expected: 30}; 2479 private scenes: SwiperDynamicSyncScene[] = []; 2480 2481 build() { 2482 Column() { 2483 Text("动画"+ JSON.stringify(this.ANIMATION)) 2484 Text("跟手"+ JSON.stringify(this.GESTURE)) 2485 Row(){ 2486 Swiper() { 2487 Text("one") 2488 Text("two") 2489 Text("three") 2490 } 2491 .width('100%') 2492 .height('300vp') 2493 .id("dynamicSwiper") 2494 .backgroundColor(Color.Blue) 2495 .autoPlay(true) 2496 .onAppear(()=>{ 2497 this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[]; 2498 }) 2499 } 2500 2501 Button("set frame") 2502 .onClick(() => { 2503 this.scenes.forEach((scenes: SwiperDynamicSyncScene) => { 2504 2505 if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) { 2506 scenes.setFrameRateRange(this.ANIMATION); 2507 } 2508 2509 if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) { 2510 scenes.setFrameRateRange(this.GESTURE); 2511 } 2512 }); 2513 }) 2514 } 2515 } 2516} 2517``` 2518 2519## openBindSheet<sup>12+</sup> 2520 2521openBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions?: SheetOptions, targetId?: number): Promise<void> 2522 2523创建并弹出以bindSheetContent作为内容的半模态页面,使用Promise异步回调。通过该接口弹出的半模态页面样式完全按照bindSheetContent中设置的样式显示。 2524 2525> **说明:** 2526> 2527> 1. 使用该接口时,若未传入有效的targetId,则不支持设置SheetOptions.preferType为POPUP模式、不支持设置SheetOptions.mode为EMBEDDED模式。 2528> 2529> 2. 由于[updateBindSheet](#updatebindsheet12)和[closeBindSheet](#closebindsheet12)依赖bindSheetContent去更新或者关闭指定的半模态页面,开发者需自行维护传入的bindSheetContent。 2530> 2531> 3. 不支持设置SheetOptions.UIContext。 2532> 2533 2534**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2535 2536**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2537 2538**参数:** 2539 2540| 参数名 | 类型 | 必填 | 说明 | 2541| ------- | ---------------------------------------- | ---- | ------- | 2542| bindSheetContent | [ComponentContent\<T>](js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 | 2543| sheetOptions | [SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions) | 否 | 半模态页面样式。<br/>**说明:** <br/>1. 不支持设置SheetOptions.uiContext,该属性的值固定为当前实例的UIContext。<br/>2. 若不传递targetId,则不支持设置SheetOptions.preferType为POPUP样式,若设置了POPUP样式则使用CENTER样式替代。<br/>3. 若不传递targetId,则不支持设置SheetOptions.mode为EMBEDDED模式,默认为OVERLAY模式。<br/>4. 其余属性的默认值参考[SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions)文档。 | 2544| targetId | number | 否 | 需要绑定组件的ID,若不指定则不绑定任何组件。 | 2545 2546**返回值:** 2547 2548| 类型 | 说明 | 2549| ---------------------------------------- | ------- | 2550| Promise<void> | Promise对象,无返回结果。 | 2551 2552**错误码:** 2553 2554以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。 2555 2556| 错误码ID | 错误信息 | 2557| ------ | ---------------------------------- | 2558| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 2559| 120001 | The bindSheetContent is incorrect. | 2560| 120002 | The bindSheetContent already exists. | 2561| 120004 | The targetId does not exist. | 2562| 120005 | The node of targetId is not in the component tree. | 2563| 120006 | The node of targetId is not a child of the page node or NavDestination node. | 2564 2565**示例:** 2566 2567```ts 2568import { FrameNode, ComponentContent } from "@kit.ArkUI"; 2569import { BusinessError } from '@kit.BasicServicesKit'; 2570 2571class Params { 2572 text: string = ""; 2573 2574 constructor(text: string) { 2575 this.text = text; 2576 } 2577} 2578 2579let contentNode: ComponentContent<Params>; 2580let gUIContext: UIContext; 2581 2582@Builder 2583function buildText(params: Params) { 2584 Column() { 2585 Text(params.text) 2586 Button('Update BindSheet') 2587 .fontSize(20) 2588 .onClick(() => { 2589 gUIContext.updateBindSheet(contentNode, { 2590 backgroundColor: Color.Pink, 2591 }, true) 2592 .then(() => { 2593 console.info('updateBindSheet success'); 2594 }) 2595 .catch((err: BusinessError) => { 2596 console.error('updateBindSheet error: ' + err.code + ' ' + err.message); 2597 }) 2598 }) 2599 2600 Button('Close BindSheet') 2601 .fontSize(20) 2602 .onClick(() => { 2603 gUIContext.closeBindSheet(contentNode) 2604 .then(() => { 2605 console.info('closeBindSheet success'); 2606 }) 2607 .catch((err: BusinessError) => { 2608 console.error('closeBindSheet error: ' + err.code + ' ' + err.message); 2609 }) 2610 }) 2611 } 2612} 2613 2614@Entry 2615@Component 2616struct UIContextBindSheet { 2617 @State message: string = 'BindSheet'; 2618 2619 aboutToAppear() { 2620 gUIContext = this.getUIContext(); 2621 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 2622 } 2623 2624 build() { 2625 RelativeContainer() { 2626 Column() { 2627 Button('Open BindSheet') 2628 .fontSize(20) 2629 .onClick(() => { 2630 let uiContext = this.getUIContext(); 2631 let uniqueId = this.getUniqueId(); 2632 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 2633 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 2634 uiContext.openBindSheet(contentNode, { 2635 height: SheetSize.MEDIUM, 2636 backgroundColor: Color.Green, 2637 title: { title: "Title", subtitle: "subtitle" } 2638 }, targetId) 2639 .then(() => { 2640 console.info('openBindSheet success'); 2641 }) 2642 .catch((err: BusinessError) => { 2643 console.error('openBindSheet error: ' + err.code + ' ' + err.message); 2644 }) 2645 }) 2646 } 2647 } 2648 .height('100%') 2649 .width('100%') 2650 } 2651} 2652``` 2653 2654## updateBindSheet<sup>12+</sup> 2655 2656updateBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions: SheetOptions, partialUpdate?: boolean ): Promise<void> 2657 2658更新bindSheetContent对应的半模态页面的样式,使用Promise异步回调。 2659 2660> **说明:** 2661> 2662> 不支持更新SheetOptions.UIContext、SheetOptions.mode、回调函数。 2663> 2664 2665**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2666 2667**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2668 2669**参数:** 2670 2671| 参数名 | 类型 | 必填 | 说明 | 2672| ------- | ---------------------------------------- | ---- | ------- | 2673| bindSheetContent | [ComponentContent\<T>](js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 | 2674| sheetOptions | [SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions) | 是 | 半模态页面样式。<br/>**说明:** <br/>不支持更新SheetOptions.uiContext、SheetOptions.mode、回调函数。 | 2675| partialUpdate | boolean | 否 | 半模态页面更新方式, 默认值为false。<br/>**说明:** <br/>1. true为增量更新,保留当前值,更新SheetOptions中的指定属性。 <br/>2. false为全量更新,除SheetOptions中的指定属性,其他属性恢复默认值。 | 2676 2677**返回值:** 2678 2679| 类型 | 说明 | 2680| ---------------------------------------- | ------- | 2681| Promise<void> | Promise对象,无返回结果。 | 2682 2683**错误码:** 2684 2685以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。 2686 2687| 错误码ID | 错误信息 | 2688| ------ | ---------------------------------- | 2689| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 2690| 120001 | The bindSheetContent is incorrect. | 2691| 120003 | The bindSheetContent cannot be found. | 2692 2693**示例:** 2694 2695```ts 2696import { FrameNode, ComponentContent } from "@kit.ArkUI"; 2697import { BusinessError } from '@kit.BasicServicesKit'; 2698 2699class Params { 2700 text: string = ""; 2701 2702 constructor(text: string) { 2703 this.text = text; 2704 } 2705} 2706 2707let contentNode: ComponentContent<Params>; 2708let gUIContext: UIContext; 2709 2710@Builder 2711function buildText(params: Params) { 2712 Column() { 2713 Text(params.text) 2714 Button('Update BindSheet') 2715 .fontSize(20) 2716 .onClick(() => { 2717 gUIContext.updateBindSheet(contentNode, { 2718 backgroundColor: Color.Pink, 2719 }, true) 2720 .then(() => { 2721 console.info('updateBindSheet success'); 2722 }) 2723 .catch((err: BusinessError) => { 2724 console.error('updateBindSheet error: ' + err.code + ' ' + err.message); 2725 }) 2726 }) 2727 2728 Button('Close BindSheet') 2729 .fontSize(20) 2730 .onClick(() => { 2731 gUIContext.closeBindSheet(contentNode) 2732 .then(() => { 2733 console.info('closeBindSheet success'); 2734 }) 2735 .catch((err: BusinessError) => { 2736 console.error('closeBindSheet error: ' + err.code + ' ' + err.message); 2737 }) 2738 }) 2739 } 2740} 2741 2742@Entry 2743@Component 2744struct UIContextBindSheet { 2745 @State message: string = 'BindSheet'; 2746 2747 aboutToAppear() { 2748 gUIContext = this.getUIContext(); 2749 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 2750 } 2751 2752 build() { 2753 RelativeContainer() { 2754 Column() { 2755 Button('Open BindSheet') 2756 .fontSize(20) 2757 .onClick(() => { 2758 let uiContext = this.getUIContext(); 2759 let uniqueId = this.getUniqueId(); 2760 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 2761 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 2762 uiContext.openBindSheet(contentNode, { 2763 height: SheetSize.MEDIUM, 2764 backgroundColor: Color.Green, 2765 title: { title: "Title", subtitle: "subtitle" } 2766 }, targetId) 2767 .then(() => { 2768 console.info('openBindSheet success'); 2769 }) 2770 .catch((err: BusinessError) => { 2771 console.error('openBindSheet error: ' + err.code + ' ' + err.message); 2772 }) 2773 }) 2774 } 2775 } 2776 .height('100%') 2777 .width('100%') 2778 } 2779} 2780``` 2781 2782## closeBindSheet<sup>12+</sup> 2783 2784closeBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>): Promise<void> 2785 2786关闭bindSheetContent对应的半模态页面,使用Promise异步回调。 2787 2788> **说明:** 2789> 2790> 使用此接口关闭半模态页面时,不会触发shouldDismiss回调。 2791> 2792 2793**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2794 2795**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2796 2797**参数:** 2798 2799| 参数名 | 类型 | 必填 | 说明 | 2800| ------- | ---------------------------------------- | ---- | ------- | 2801| bindSheetContent | [ComponentContent\<T>](js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 | 2802 2803**返回值:** 2804 2805| 类型 | 说明 | 2806| ---------------------------------------- | ------- | 2807| Promise<void> | Promise对象,无返回结果。 | 2808 2809**错误码:** 2810 2811以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。 2812 2813| 错误码ID | 错误信息 | 2814| ------ | ---------------------------------- | 2815| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 2816| 120001 | The bindSheetContent is incorrect. | 2817| 120003 | The bindSheetContent cannot be found. | 2818 2819**示例:** 2820 2821```ts 2822import { FrameNode, ComponentContent } from "@kit.ArkUI"; 2823import { BusinessError } from '@kit.BasicServicesKit'; 2824 2825class Params { 2826 text: string = ""; 2827 2828 constructor(text: string) { 2829 this.text = text; 2830 } 2831} 2832 2833let contentNode: ComponentContent<Params>; 2834let gUIContext: UIContext; 2835 2836@Builder 2837function buildText(params: Params) { 2838 Column() { 2839 Text(params.text) 2840 Button('Update BindSheet') 2841 .fontSize(20) 2842 .onClick(() => { 2843 gUIContext.updateBindSheet(contentNode, { 2844 backgroundColor: Color.Pink, 2845 }, true) 2846 .then(() => { 2847 console.info('updateBindSheet success'); 2848 }) 2849 .catch((err: BusinessError) => { 2850 console.error('updateBindSheet error: ' + err.code + ' ' + err.message); 2851 }) 2852 }) 2853 2854 Button('Close BindSheet') 2855 .fontSize(20) 2856 .onClick(() => { 2857 gUIContext.closeBindSheet(contentNode) 2858 .then(() => { 2859 console.info('closeBindSheet success'); 2860 }) 2861 .catch((err: BusinessError) => { 2862 console.error('closeBindSheet error: ' + err.code + ' ' + err.message); 2863 }) 2864 }) 2865 } 2866} 2867 2868@Entry 2869@Component 2870struct UIContextBindSheet { 2871 @State message: string = 'BindSheet'; 2872 2873 aboutToAppear() { 2874 gUIContext = this.getUIContext(); 2875 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 2876 } 2877 2878 build() { 2879 RelativeContainer() { 2880 Column() { 2881 Button('Open BindSheet') 2882 .fontSize(20) 2883 .onClick(() => { 2884 let uiContext = this.getUIContext(); 2885 let uniqueId = this.getUniqueId(); 2886 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 2887 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 2888 uiContext.openBindSheet(contentNode, { 2889 height: SheetSize.MEDIUM, 2890 backgroundColor: Color.Green, 2891 title: { title: "Title", subtitle: "subtitle" } 2892 }, targetId) 2893 .then(() => { 2894 console.info('openBindSheet success'); 2895 }) 2896 .catch((err: BusinessError) => { 2897 console.error('openBindSheet error: ' + err.code + ' ' + err.message); 2898 }) 2899 }) 2900 } 2901 } 2902 .height('100%') 2903 .width('100%') 2904 } 2905} 2906``` 2907 2908## isFollowingSystemFontScale<sup>13+</sup> 2909 2910isFollowingSystemFontScale(): boolean 2911 2912获取当前UI上下文是否跟随系统字体倍率。 2913 2914**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2915 2916**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2917 2918**返回值:** 2919 2920| 类型 | 说明 | 2921|---------|---------------| 2922| boolean | 当前UI上下文是否跟随系统字体倍率。<br/> true表示UI上下文跟随系统倍率,false表示UI上下文不跟随系统倍率。 | 2923 2924**示例:** 2925 2926参考[configuration标签](../../quick-start/app-configuration-file.md#configuration标签),配置fontSizeScale的值为“followSystem”。 2927```ts 2928@Entry 2929@Component 2930struct Index { 2931 build() { 2932 Column() { 2933 Button('isFollowingSystemFontScale').onClick(() => { 2934 console.info('isFollowingSystemFontScale', this.getUIContext().isFollowingSystemFontScale()); 2935 }); 2936 } 2937 } 2938} 2939``` 2940 2941## getMaxFontScale<sup>13+</sup> 2942 2943getMaxFontScale(): number 2944 2945获取当前UI上下文最大字体倍率。 2946 2947**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2948 2949**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2950 2951**返回值:** 2952 2953| 类型 | 说明 | 2954|---------|-----------| 2955| number | 当前UI上下文最大字体倍率。 | 2956 2957**示例:** 2958 2959参考[configuration标签](../../quick-start/app-configuration-file.md#configuration标签),配置fontSizeMaxScale的值为“1.75”。 2960```ts 2961@Entry 2962@Component 2963struct Index { 2964 build() { 2965 Column() { 2966 Button('getMaxFontScale').onClick(() => { 2967 console.info('getMaxFontScale', this.getUIContext().getMaxFontScale().toFixed(2)); 2968 }); 2969 } 2970 } 2971} 2972``` 2973 2974## bindTabsToScrollable<sup>13+</sup> 2975 2976bindTabsToScrollable(tabsController: TabsController, scroller: Scroller): void 2977 2978绑定Tabs组件和可滚动容器组件(支持[List](./arkui-ts/ts-container-list.md)、[Scroll](./arkui-ts/ts-container-scroll.md)、[Grid](./arkui-ts/ts-container-grid.md)、[WaterFlow](./arkui-ts/ts-container-waterflow.md)),当滑动可滚动容器组件时,会触发所有与其绑定的Tabs组件的TabBar的显示和隐藏动效,上滑隐藏,下滑显示。一个TabsController可与多个Scroller绑定,一个Scroller也可与多个TabsController绑定。 2979 2980> **说明:** 2981> 2982> 当多个可滚动容器组件绑定了同一个Tabs组件时,只要滑动任意一个可滚动容器组件,就会触发TabBar的显示或隐藏。且当任意一个可滚动容器组件滑动到底部时,会立即触发TabBar的显示动效。因此不建议同时触发多个可滚动容器组件的滑动。 2983 2984**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2985 2986**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2987 2988**参数:** 2989 2990| 参数名 | 类型 | 必填 | 说明 | 2991| ------- | ---------------------------------------- | ---- | ------- | 2992| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 | 2993| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 | 2994 2995**示例:** 2996 2997```ts 2998@Entry 2999@Component 3000struct TabsExample { 3001 private arr: string[] = []; 3002 private parentTabsController: TabsController = new TabsController(); 3003 private childTabsController: TabsController = new TabsController(); 3004 private listScroller: Scroller = new Scroller(); 3005 private parentScroller: Scroller = new Scroller(); 3006 private childScroller: Scroller = new Scroller(); 3007 3008 aboutToAppear(): void { 3009 for (let i = 0; i < 20; i++) { 3010 this.arr.push(i.toString()); 3011 } 3012 let context = this.getUIContext(); 3013 context.bindTabsToScrollable(this.parentTabsController, this.listScroller); 3014 context.bindTabsToScrollable(this.childTabsController, this.listScroller); 3015 context.bindTabsToNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller); 3016 } 3017 3018 aboutToDisappear(): void { 3019 let context = this.getUIContext(); 3020 context.unbindTabsFromScrollable(this.parentTabsController, this.listScroller); 3021 context.unbindTabsFromScrollable(this.childTabsController, this.listScroller); 3022 context.unbindTabsFromNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller); 3023 } 3024 3025 build() { 3026 Tabs({ barPosition: BarPosition.End, controller: this.parentTabsController }) { 3027 TabContent() { 3028 Tabs({ controller: this.childTabsController }) { 3029 TabContent() { 3030 List({ space: 20, initialIndex: 0, scroller: this.listScroller }) { 3031 ForEach(this.arr, (item: string) => { 3032 ListItem() { 3033 Text(item) 3034 .width('100%') 3035 .height(100) 3036 .fontSize(16) 3037 .textAlign(TextAlign.Center) 3038 .borderRadius(10) 3039 .backgroundColor(Color.Gray) 3040 } 3041 }, (item: string) => item) 3042 } 3043 .scrollBar(BarState.Off) 3044 .width('90%') 3045 .height('100%') 3046 .contentStartOffset(56) 3047 .contentEndOffset(52) 3048 }.tabBar(SubTabBarStyle.of('顶部页签')) 3049 } 3050 .width('100%') 3051 .height('100%') 3052 .barOverlap(true) // 使TabBar叠加在TabContent上,当TabBar向上或向下隐藏后,原位置处不为空白 3053 .clip(true) // 对超出Tabs组件范围的子组件进行裁剪,防止TabBar向上或向下隐藏后误触TabBar 3054 }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), 'scroller联动多个TabsController')) 3055 3056 TabContent() { 3057 Scroll(this.parentScroller) { 3058 List({ space: 20, initialIndex: 0, scroller: this.childScroller }) { 3059 ForEach(this.arr, (item: string) => { 3060 ListItem() { 3061 Text(item) 3062 .width('100%') 3063 .height(100) 3064 .fontSize(16) 3065 .textAlign(TextAlign.Center) 3066 .borderRadius(10) 3067 .backgroundColor(Color.Gray) 3068 } 3069 }, (item: string) => item) 3070 } 3071 .scrollBar(BarState.Off) 3072 .width('90%') 3073 .height('100%') 3074 .contentEndOffset(52) 3075 .nestedScroll({ scrollForward: NestedScrollMode.SELF_FIRST, scrollBackward: NestedScrollMode.SELF_FIRST }) 3076 } 3077 .width('100%') 3078 .height('100%') 3079 .scrollBar(BarState.Off) 3080 .scrollable(ScrollDirection.Vertical) 3081 .edgeEffect(EdgeEffect.Spring) 3082 }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), '嵌套的scroller联动TabsController')) 3083 } 3084 .width('100%') 3085 .height('100%') 3086 .barOverlap(true) // 使TabBar叠加在TabContent上,当TabBar向上或向下隐藏后,原位置处不为空白 3087 .clip(true) // 对超出Tabs组件范围的子组件进行裁剪,防止TabBar向上或向下隐藏后误触TabBar 3088 } 3089} 3090``` 3091 3092 3093 3094## unbindTabsFromScrollable<sup>13+</sup> 3095 3096unbindTabsFromScrollable(tabsController: TabsController, scroller: Scroller): void 3097 3098解除Tabs组件和可滚动容器组件的绑定。 3099 3100**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 3101 3102**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3103 3104**参数:** 3105 3106| 参数名 | 类型 | 必填 | 说明 | 3107| ------- | ---------------------------------------- | ---- | ------- | 3108| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 | 3109| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 | 3110 3111**示例:** 3112 3113参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。 3114 3115## bindTabsToNestedScrollable<sup>13+</sup> 3116 3117bindTabsToNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void 3118 3119绑定Tabs组件和嵌套的可滚动容器组件(支持[List](./arkui-ts/ts-container-list.md)、[Scroll](./arkui-ts/ts-container-scroll.md)、[Grid](./arkui-ts/ts-container-grid.md)、[WaterFlow](./arkui-ts/ts-container-waterflow.md)),当滑动父组件或子组件时,会触发所有与其绑定的Tabs组件的TabBar的显示和隐藏动效,上滑隐藏,下滑显示。一个TabsController可与多个嵌套的Scroller绑定,嵌套的Scroller也可与多个TabsController绑定。 3120 3121**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 3122 3123**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3124 3125**参数:** 3126 3127| 参数名 | 类型 | 必填 | 说明 | 3128| ------- | ---------------------------------------- | ---- | ------- | 3129| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 | 3130| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 | 3131| childScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。其对应组件为parentScroller对应组件的子组件,且组件间存在嵌套滚动关系。 | 3132 3133**示例:** 3134 3135参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。 3136 3137## unbindTabsFromNestedScrollable<sup>13+</sup> 3138 3139unbindTabsFromNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void 3140 3141解除Tabs组件和嵌套的可滚动容器组件的绑定。 3142 3143**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 3144 3145**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3146 3147**参数:** 3148 3149| 参数名 | 类型 | 必填 | 说明 | 3150| ------- | ---------------------------------------- | ---- | ------- | 3151| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 | 3152| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 | 3153| childScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。其对应组件为parentScroller对应组件的子组件,且组件间存在嵌套滚动关系。 | 3154 3155**示例:** 3156 3157参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。 3158 3159## enableSwipeBack<sup>18+</sup> 3160 3161enableSwipeBack(enabled: Optional\<boolean\>): void 3162 3163设置是否支持应用内横向滑动返回上一级。 3164 3165**原子化服务API:** 从API version 18 开始,该接口支持在原子化服务中使用。 3166 3167**系统能力:** SystemCapability.ArkUI.ArkUI.Circle 3168 3169**参数:** 3170 3171| 参数名 | 类型 | 必填 | 说明 | 3172| --- | --- | --- | --- | 3173| enabled | Optional\<boolean> | 是 | 是否支持应用内横向滑动返回,默认值为true。<br>当值为true时,支持应用内横向滑动返回。<br>当值为false时,不支持应用内横向滑动返回。| 3174 3175**示例:** 3176 3177```js 3178@Entry 3179@Component 3180struct Index { 3181 @State isEnable: boolean = true; 3182 3183 build() { 3184 RelativeContainer() { 3185 Button(`enable swipe back: ${this.isEnable}`).onClick(() => { 3186 this.isEnable = !this.isEnable; 3187 this.getUIContext().enableSwipeBack(this.isEnable); 3188 }) 3189 } 3190 .height('100%') 3191 .width('100%') 3192 } 3193} 3194``` 3195 3196## getTextMenuController<sup>16+</sup> 3197 3198getTextMenuController(): TextMenuController 3199 3200获取[TextMenuController](arkts-apis-uicontext-textmenucontroller.md)对象,可通过该对象控制文本选择菜单。 3201 3202**原子化服务API:** 从API version 16 开始,该接口支持在原子化服务中使用。 3203 3204**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3205 3206**返回值:** 3207 3208|类型|说明| 3209|----|----| 3210|[TextMenuController](arkts-apis-uicontext-textmenucontroller.md)| 获取TextMenuController对象。| 3211 3212**示例:** 3213 3214参考[TextMenuController](arkts-apis-uicontext-textmenucontroller.md)接口示例。 3215 3216## createUIContextWithoutWindow<sup>17+</sup> 3217 3218static createUIContextWithoutWindow(context: common.UIAbilityContext | common.ExtensionContext) : UIContext | undefined 3219 3220创建一个不依赖窗口的UI实例,并返回其UI上下文。该接口所创建的UI实例是单例。 3221 3222> **说明:** 3223> 3224> 返回的UI上下文只可用于创建[自定义节点](../../ui/arkts-user-defined-node.md),不能执行其他UI操作。 3225 3226**原子化服务API:** 从API version 17 开始,该接口支持在原子化服务中使用。 3227 3228**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3229 3230**参数:** 3231 3232| 参数名 | 类型 | 必填 | 说明 | 3233| ------- | ---------------------------------------- | ---- | ----------- | 3234| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) \| common.[ExtensionContext](../apis-ability-kit/js-apis-inner-application-extensionContext.md) | 是 | [UIAbility](../apis-ability-kit/js-apis-app-ability-uiAbility.md)或[ExtensionAbility](../apis-ability-kit/js-apis-app-ability-extensionAbility.md)所对应的上下文环境。 | 3235 3236**返回值:** 3237 3238|类型|说明| 3239|----|----| 3240| UIContext \| undefined | 创建的UI实例的上下文,创建失败时返回undefined。 | 3241 3242**错误码:** 3243 3244以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[UI上下文](errorcode-uicontext.md)错误码。 3245 3246| 错误码ID | 错误信息 | 3247| ------ | ---------------------------------- | 3248| 401 | Parameter error. Possible causes: <br> 1. The number of parameters is incorrect.<br> 2. Invalid parameter type of context. | 3249| 100001 | Internal error. | 3250 3251 3252**示例:** 3253 3254```ts 3255// EntryAbility.ets 3256import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 3257import { hilog } from '@kit.PerformanceAnalysisKit'; 3258import { UIContext } from '@kit.ArkUI'; 3259 3260export default class EntryAbility extends UIAbility { 3261 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 3262 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 3263 let uiContext : UIContext | undefined = UIContext.createUIContextWithoutWindow(this.context); 3264 } 3265 3266 // ...... 3267} 3268``` 3269 3270## destroyUIContextWithoutWindow<sup>17+</sup> 3271 3272static destroyUIContextWithoutWindow(): void 3273 3274销毁[createUIContextWithoutWindow](#createuicontextwithoutwindow17)创建的UI实例。 3275 3276**原子化服务API:** 从API version 17 开始,该接口支持在原子化服务中使用。 3277 3278**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3279 3280**示例:** 3281 3282```ts 3283// EntryAbility.ets 3284import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 3285import { hilog } from '@kit.PerformanceAnalysisKit'; 3286import { UIContext } from '@kit.ArkUI'; 3287 3288export default class EntryAbility extends UIAbility { 3289 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 3290 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 3291 let uiContext : UIContext | undefined = UIContext.createUIContextWithoutWindow(this.context); 3292 UIContext.destroyUIContextWithoutWindow(); 3293 } 3294 3295 // ...... 3296} 3297``` 3298 3299## dispatchKeyEvent<sup>15+</sup> 3300 3301dispatchKeyEvent(node: number | string, event: KeyEvent): boolean 3302 3303按键事件应分发给指定的组件。为了确保行为的可预测性,目标组件必须位于分发组件的子树中。 3304 3305**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 3306 3307**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3308 3309**参数:** 3310 3311| 参数名 | 类型 | 必填 | 说明 | 3312| ------ | ----------------------------- | ---- | ------------------ | 3313| node | number \| string | 是 | 组件的id或者节点UniqueID。 | 3314| event |[KeyEvent](./arkui-ts/ts-universal-events-key.md#keyevent对象说明) | 是 | KeyEvent对象。 | 3315 3316**返回值:** 3317 3318| 类型 | 说明 | 3319|---------|---------------| 3320| boolean | 按键事件是否成功分发给指定的组件。<br/> true表示分发成功,false表示分发失败。 | 3321 3322**示例:** 3323 3324```ts 3325@Entry 3326@Component 3327struct Index { 3328 build() { 3329 Row() { 3330 Row() { 3331 Button('Button1').id('Button1').onKeyEvent((event) => { 3332 console.info("Button1"); 3333 return true; 3334 }) 3335 Button('Button2').id('Button2').onKeyEvent((event) => { 3336 console.info("Button2"); 3337 return true; 3338 }) 3339 } 3340 .width('100%') 3341 .height('100%') 3342 .id('Row1') 3343 .onKeyEventDispatch((event) => { 3344 let context = this.getUIContext(); 3345 context.getFocusController().requestFocus('Button1'); 3346 return context.dispatchKeyEvent('Button1', event); 3347 }) 3348 3349 } 3350 .height('100%') 3351 .width('100%') 3352 .onKeyEventDispatch((event) => { 3353 if (event.type == KeyType.Down) { 3354 let context = this.getUIContext(); 3355 context.getFocusController().requestFocus('Row1'); 3356 return context.dispatchKeyEvent('Row1', event); 3357 } 3358 return true; 3359 }) 3360 } 3361} 3362``` 3363## setPixelRoundMode<sup>18+</sup> 3364 3365setPixelRoundMode(mode: PixelRoundMode): void 3366 3367配置当前页面的像素取整模式。 3368 3369**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 3370 3371**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3372 3373**参数:** 3374 3375| 参数名 | 类型 | 必填 | 说明 | 3376| -------- | ---------- | ---- | ---- | 3377| mode | [PixelRoundMode](./arkui-ts/ts-appendix-enums.md#pixelroundmode18)| 是 | 像素取整模式。<br />默认值:PixelRoundMode.PIXEL_ROUND_ON_LAYOUT_FINISH | 3378 3379**示例:** 3380 3381<!--code_no_check--> 3382```ts 3383// EntryAbility.ets 3384import { UIContext } from '@kit.ArkUI'; 3385import { hilog } from '@kit.PerformanceAnalysisKit'; 3386 3387export default class EntryAbility extends UIAbility{ 3388 onWindowStageCreate(windowStage: window.WindowStage) { 3389 // Main window is created, set main page for this ability 3390 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 3391 3392 windowStage.loadContent('pages/Index', (err, data) => { 3393 let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext(); 3394 uiContext.setPixelRoundMode(PixelRoundMode.PIXEL_ROUND_ON_LAYOUT_FINISH); 3395 if (err.code) { 3396 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 3397 return; 3398 } 3399 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 3400 }); 3401 } 3402} 3403``` 3404 3405## getPixelRoundMode<sup>18+</sup> 3406 3407getPixelRoundMode(): PixelRoundMode 3408 3409获取当前页面的像素取整模式。 3410 3411**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 3412 3413**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3414 3415**返回值:** 3416 3417| 类型 | 说明 | 3418| ---------- | ---- | 3419| [PixelRoundMode](./arkui-ts/ts-appendix-enums.md#pixelroundmode18)| 当前页面的像素取整模式。| 3420 3421**示例:** 3422 3423<!--code_no_check--> 3424```ts 3425// EntryAbility.ets 3426import { UIContext } from '@kit.ArkUI'; 3427import { hilog } from '@kit.PerformanceAnalysisKit'; 3428 3429export default class EntryAbility extends UIAbility{ 3430 onWindowStageCreate(windowStage: window.WindowStage) { 3431 // Main window is created, set main page for this ability 3432 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 3433 3434 windowStage.loadContent('pages/Index', (err, data) => { 3435 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 3436 console.info("pixelRoundMode : " + uiContext.getPixelRoundMode().valueOf()); 3437 if (err.code) { 3438 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 3439 return; 3440 } 3441 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 3442 }); 3443 } 3444} 3445``` 3446 3447