1# @ohos.arkui.UIContext (UIContext) 2 3在Stage模型中,WindowStage/Window可以通过[loadContent](js-apis-window.md#loadcontent9)接口加载页面并创建UI的实例,并将页面内容渲染到关联的窗口中,所以UI实例和窗口是一一关联的。一些全局的UI接口是和具体UI实例的执行上下文相关的,在当前接口调用时,通过追溯调用链跟踪到UI的上下文,来确定具体的UI实例。若在非UI页面中或者一些异步回调中调用这类接口,可能无法跟踪到当前UI的上下文,导致接口执行失败。 4 5@ohos.window在API version 10 新增[getUIContext](js-apis-window.md#getuicontext10)接口,获取UI上下文实例UIContext对象,使用UIContext对象提供的替代方法,可以直接作用在对应的UI实例上。 6 7> **说明:** 8> 9> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 10> 11> 示例效果请以真机运行为准,当前DevEco Studio预览器不支持。 12 13## UIContext 14 15以下API需先使用ohos.window中的[getUIContext()](js-apis-window.md#getuicontext10)方法获取UIContext实例,再通过此实例调用对应方法。或者可以通过自定义组件内置方法[getUIContext()](arkui-ts/ts-custom-component-api.md#getuicontext)获取。本文中UIContext对象以uiContext表示。 16 17### getFont 18 19getFont(): Font 20 21获取Font对象。 22 23**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 24 25**系统能力:** SystemCapability.ArkUI.ArkUI.Full 26 27**返回值:** 28 29| 类型 | 说明 | 30| ------------- | ----------- | 31| [Font](#font) | 返回Font实例对象。 | 32 33**示例:** 34 35<!--code_no_check--> 36```ts 37uiContext.getFont(); 38``` 39### getComponentUtils 40 41getComponentUtils(): ComponentUtils 42 43获取ComponentUtils对象。 44 45**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 46 47**系统能力:** SystemCapability.ArkUI.ArkUI.Full 48 49**返回值:** 50 51| 类型 | 说明 | 52| --------------------------------- | --------------------- | 53| [ComponentUtils](#componentutils) | 返回ComponentUtils实例对象。 | 54 55**示例:** 56 57<!--code_no_check--> 58```ts 59uiContext.getComponentUtils(); 60``` 61 62### getUIInspector 63 64getUIInspector(): UIInspector 65 66获取UIInspector对象。 67 68**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 69 70**系统能力:** SystemCapability.ArkUI.ArkUI.Full 71 72**返回值:** 73 74| 类型 | 说明 | 75| --------------------------- | ------------------ | 76| [UIInspector](#uiinspector) | 返回UIInspector实例对象。 | 77 78**示例:** 79 80<!--code_no_check--> 81```ts 82uiContext.getUIInspector(); 83``` 84 85### getUIObserver<sup>11+</sup> 86 87getUIObserver(): UIObserver 88 89获取UIObserver对象。 90 91**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 92 93**系统能力:** SystemCapability.ArkUI.ArkUI.Full 94 95**返回值:** 96 97| 类型 | 说明 | 98| --------------------------- | ------------------ | 99| [UIObserver](#uiobserver11) | 返回UIObserver实例对象。 | 100 101**示例:** 102 103<!--code_no_check--> 104```ts 105uiContext.getUIObserver(); 106``` 107 108### getMediaQuery 109 110getMediaQuery(): MediaQuery 111 112获取MediaQuery对象。 113 114**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 115 116**系统能力:** SystemCapability.ArkUI.ArkUI.Full 117 118**返回值:** 119 120| 类型 | 说明 | 121| ------------------------- | ----------------- | 122| [MediaQuery](#mediaquery) | 返回MediaQuery实例对象。 | 123 124**示例:** 125 126<!--code_no_check--> 127```ts 128uiContext.getMediaQuery(); 129``` 130 131### getRouter 132 133getRouter(): Router 134 135获取Router对象。 136 137**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 138 139**系统能力:** SystemCapability.ArkUI.ArkUI.Full 140 141**返回值:** 142 143| 类型 | 说明 | 144| ----------------- | ------------- | 145| [Router](#router) | 返回Router实例对象。 | 146 147**示例:** 148 149<!--code_no_check--> 150```ts 151uiContext.getRouter(); 152``` 153 154### getPromptAction 155 156getPromptAction(): PromptAction 157 158获取PromptAction对象。 159 160**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 161 162**系统能力:** SystemCapability.ArkUI.ArkUI.Full 163 164**返回值:** 165 166| 类型 | 说明 | 167| ----------------------------- | ------------------- | 168| [PromptAction](#promptaction) | 返回PromptAction实例对象。 | 169 170**示例:** 171 172<!--code_no_check--> 173```ts 174uiContext.getPromptAction(); 175``` 176 177### getOverlayManager<sup>12+</sup> 178 179getOverlayManager(): OverlayManager 180 181获取OverlayManager对象。 182 183**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 184 185**系统能力:**: SystemCapability.ArkUI.ArkUI.Full 186 187**返回值:** 188 189| 类型 | 说明 | 190| ----------------------------- | ------------------- | 191| [OverlayManager](#overlaymanager12) | 返回OverlayManager实例对象。 | 192 193**示例:** 194 195<!--code_no_check--> 196```ts 197uiContext.getOverlayManager(); 198``` 199 200### setOverlayManagerOptions<sup>15+</sup> 201 202setOverlayManagerOptions(options: OverlayManagerOptions): boolean 203 204设置[OverlayManager](#overlaymanager12)参数。用于在使用OverlayManager能力之前先初始化overlayManager的参数,包括是否需要渲染overlay根节点等属性。该方法需要在执行getOverlayManager方法之前执行生效,且该方法只生效一次。 205 206**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 207 208**系统能力:**: SystemCapability.ArkUI.ArkUI.Full 209 210**参数:** 211 212| 参数名 | 类型 | 必填 | 说明 | 213| ----- | ---------------------------------------- | ---- | ------------------------------------- | 214| options | [OverlayManagerOptions](#overlaymanageroptions15) | 是 | OverlayManager参数。| 215 216**返回值:** 217 218| 类型 | 说明 | 219| ------- | -------------- | 220| boolean | 是否设置成功。<br/>返回true时,设置成功。返回false时,设置失败。 | 221 222**示例:** 223 224<!--code_no_check--> 225```ts 226uiContext.setOverlayManagerOptions({ renderRootOverlay: true }); 227``` 228 229### getOverlayManagerOptions<sup>15+</sup> 230 231getOverlayManagerOptions(): OverlayManagerOptions 232 233用于获取当前[OverlayManager](#overlaymanager12)参数。 234 235**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 236 237**系统能力:**: SystemCapability.ArkUI.ArkUI.Full 238 239**返回值:** 240 241| 类型 | 说明 | 242| ----------------------------- | ------------------- | 243| [OverlayManagerOptions](#overlaymanageroptions15) | 返回当前OverlayManagerOptions。 | 244 245**示例:** 246 247<!--code_no_check--> 248```ts 249uiContext.getOverlayManagerOptions(); 250``` 251 252### animateTo 253 254animateTo(value: AnimateParam, event: () => void): void 255 256提供animateTo接口来指定由于闭包代码导致的状态变化插入过渡动效。 257 258**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 259 260**系统能力:** SystemCapability.ArkUI.ArkUI.Full 261 262**参数:** 263 264| 参数名 | 类型 | 必填 | 说明 | 265| ----- | ---------------------------------------- | ---- | ------------------------------------- | 266| value | [AnimateParam](arkui-ts/ts-explicit-animation.md#animateparam对象说明) | 是 | 设置动画效果相关参数。 | 267| event | () => void | 是 | 指定显示动效的闭包函数,在闭包函数中导致的状态变化系统会自动插入过渡动画。 | 268 269**示例:** 270 271```ts 272// xxx.ets 273@Entry 274@Component 275struct AnimateToExample { 276 @State widthSize: number = 250 277 @State heightSize: number = 100 278 @State rotateAngle: number = 0 279 private flag: boolean = true 280 uiContext: UIContext | undefined = undefined; 281 282 aboutToAppear() { 283 this.uiContext = this.getUIContext(); 284 if (!this.uiContext) { 285 console.warn("no uiContext"); 286 return; 287 } 288 } 289 290 build() { 291 Column() { 292 Button('change size') 293 .width(this.widthSize) 294 .height(this.heightSize) 295 .margin(30) 296 .onClick(() => { 297 if (this.flag) { 298 this.uiContext?.animateTo({ 299 duration: 2000, 300 curve: Curve.EaseOut, 301 iterations: 3, 302 playMode: PlayMode.Normal, 303 onFinish: () => { 304 console.info('play end') 305 } 306 }, () => { 307 this.widthSize = 150 308 this.heightSize = 60 309 }) 310 } else { 311 this.uiContext?.animateTo({}, () => { 312 this.widthSize = 250 313 this.heightSize = 100 314 }) 315 } 316 this.flag = !this.flag 317 }) 318 Button('stop rotating') 319 .margin(50) 320 .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle }) 321 .onAppear(() => { 322 // 组件出现时开始做动画 323 this.uiContext?.animateTo({ 324 duration: 1200, 325 curve: Curve.Friction, 326 delay: 500, 327 iterations: -1, // 设置-1表示动画无限循环 328 playMode: PlayMode.Alternate, 329 expectedFrameRateRange: { 330 min: 10, 331 max: 120, 332 expected: 60, 333 } 334 }, () => { 335 this.rotateAngle = 90 336 }) 337 }) 338 .onClick(() => { 339 this.uiContext?.animateTo({ duration: 0 }, () => { 340 // this.rotateAngle之前为90,在duration为0的动画中修改属性,可以停止该属性之前的动画,按新设置的属性显示 341 this.rotateAngle = 0 342 }) 343 }) 344 }.width('100%').margin({ top: 5 }) 345 } 346} 347``` 348 349### getSharedLocalStorage<sup>12+</sup> 350 351getSharedLocalStorage(): LocalStorage | undefined 352 353获取当前stage共享的LocalStorage实例。 354 355**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 356 357**系统能力:** SystemCapability.ArkUI.ArkUI.Full 358 359**模型约束:** 此接口仅可在Stage模型下使用。 360 361**返回值:** 362 363| 类型 | 描述 | 364| ------------------------------ | ----------------- | 365| [LocalStorage](arkui-ts/ts-state-management.md#localstorage9) \| undefined | 返回LocalStorage实例。共享的LocalStorage实例不存在时返回undefined。 | 366 367**示例:** 368 369```ts 370// EntryAbility.ets 371import { UIAbility } from '@kit.AbilityKit'; 372import { window } from '@kit.ArkUI'; 373 374export default class EntryAbility extends UIAbility { 375 storage: LocalStorage = new LocalStorage(); 376 377 onWindowStageCreate(windowStage: window.WindowStage) { 378 windowStage.loadContent('pages/Index', this.storage); 379 } 380} 381``` 382 383```ts 384// Index.ets 385 386@Entry 387@Component 388struct SharedLocalStorage { 389 localStorage = this.getUIContext().getSharedLocalStorage(); 390 391 build() { 392 Row() { 393 Column() { 394 Button("Change Local Storage to 47") 395 .onClick(() => { 396 this.localStorage?.setOrCreate("propA", 47); 397 }) 398 Button("Get Local Storage") 399 .onClick(() => { 400 console.info(`localStorage: ${this.localStorage?.get("propA")}`); 401 }) 402 } 403 .width('100%') 404 } 405 .height('100%') 406 } 407} 408``` 409 410### getHostContext<sup>12+</sup> 411 412getHostContext(): Context | undefined 413 414获得当前元能力的Context。 415 416**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 417 418**系统能力:** SystemCapability.ArkUI.ArkUI.Full 419 420**模型约束:** 此接口仅可在Stage模型下使用。 421 422**返回值:** 423 424| 类型 | 说明 | 425| ------ | ------------------------------- | 426| [Context](#context12) \| undefined | 返回当前组件所在Ability的Context,Context的具体类型为当前Ability关联的Context对象。例如:在UIAbility窗口中的页面调用该接口,返回类型为UIAbilityContext。在ExtensionAbility窗口中的页面调用该接口,返回类型为ExtensionContext。ability上下文不存在时返回undefined。 | 427 428**示例:** 429 430```ts 431@Entry 432@Component 433struct Index { 434 uiContext = this.getUIContext(); 435 436 build() { 437 Row() { 438 Column() { 439 Text("cacheDir='"+this.uiContext?.getHostContext()?.cacheDir+"'").fontSize(25) 440 Text("bundleCodeDir='"+this.uiContext?.getHostContext()?.bundleCodeDir+"'").fontSize(25) 441 } 442 .width('100%') 443 } 444 .height('100%') 445 } 446} 447``` 448 449### getFrameNodeById<sup>12+</sup> 450 451getFrameNodeById(id: string): FrameNode | null 452 453通过组件的id获取组件树的实体节点。 454 455**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 456 457**系统能力:** SystemCapability.ArkUI.ArkUI.Full 458 459**参数:** 460 461| 参数名 | 类型 | 必填 | 说明 | 462| ----- | ---------------------------------------- | ---- | ------------------------------------- | 463| id | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。 | 464 465**返回值:** 466 467| 类型 | 说明 | 468| ---------------------------------------- | ------------- | 469| [FrameNode](js-apis-arkui-frameNode.md) \| null | 返回的组件树的实体节点或者空节点。 | 470 471> **说明:** 472> 473> getFrameNodeById通过遍历查询对应id的节点,性能较差。推荐使用[getAttachedFrameNodeById](#getattachedframenodebyid12)。 474 475**示例:** 476 477<!--code_no_check--> 478```ts 479uiContext.getFrameNodeById("TestNode") 480``` 481 482### getAttachedFrameNodeById<sup>12+</sup> 483 484getAttachedFrameNodeById(id: string): FrameNode | null 485 486通过组件的id获取当前窗口上的实体节点。 487 488**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 489 490**系统能力:** SystemCapability.ArkUI.ArkUI.Full 491 492**参数:** 493 494| 参数名 | 类型 | 必填 | 说明 | 495| ----- | ---------------------------------------- | ---- | ------------------------------------- | 496| id | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。 | 497 498**返回值:** 499 500| 类型 | 说明 | 501| ---------------------------------------- | ------------- | 502| [FrameNode](js-apis-arkui-frameNode.md) \| null | 返回的组件树的实体节点或者空节点。 | 503 504> **说明:** 505> 506> getAttachedFrameNodeById仅能查询上屏节点。 507 508**示例:** 509 510<!--code_no_check--> 511```ts 512uiContext.getAttachedFrameNodeById("TestNode") 513``` 514 515### getFrameNodeByUniqueId<sup>12+</sup> 516 517getFrameNodeByUniqueId(id: number): FrameNode | null 518 519提供getFrameNodeByUniqueId接口通过组件的uniqueId获取组件树的实体节点。 5201. 当uniqueId对应的是内置组件时,返回组件所对应的FrameNode; 5212. 当uniqueId对应的是自定义组件时,若其有渲染内容,则返回该自定义组件的根节点,类型为__Common__;若其无渲染内容,则返回其第一个子组件的FrameNode。 5223. 当uniqueId无对应的组件时,返回null。 523 524**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 525 526**系统能力:** SystemCapability.ArkUI.ArkUI.Full 527 528**参数:** 529 530| 参数名 | 类型 | 必填 | 说明 | 531| ----- | ---------------------------------------- | ---- | ------------------------------------- | 532| id | number | 是 | 节点对应的UniqueId | 533 534**返回值:** 535 536| 类型 | 说明 | 537| ---------------------------------------- | ------------- | 538| [FrameNode](js-apis-arkui-frameNode.md) \| null | 返回的组件树的实体节点或者空节点。 | 539 540**示例:** 541 542```ts 543import { UIContext, FrameNode } from '@kit.ArkUI'; 544 545@Entry 546@Component 547struct MyComponent { 548 aboutToAppear() { 549 let uniqueId: number = this.getUniqueId(); 550 let uiContext: UIContext = this.getUIContext(); 551 if (uiContext) { 552 let node: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 553 } 554 } 555 556 build() { 557 // ... 558 } 559} 560``` 561 562### getPageInfoByUniqueId<sup>12+</sup> 563 564getPageInfoByUniqueId(id: number): PageInfo 565 566提供getPageInfoByUniqueId接口通过组件的uniqueId获取该节点对应的Router和NavDestination页面信息。 5671. 当uniqueId对应的节点在Page节点中,routerPageInfo属性为其对应的Router信息; 5682. 当uniqueId对应的节点在NavDestination节点中,navDestinationInfo属性为其对应的NavDestination信息; 5693. 当uniqueId对应的节点无对应的Router或NavDestination信息时,对应的属性为undefined; 5704. 模态弹窗并不在任何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。 571 572**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 573 574**系统能力:** SystemCapability.ArkUI.ArkUI.Full 575 576**参数:** 577 578| 参数名 | 类型 | 必填 | 说明 | 579| ----- | ---------------------------------------- | ---- | ------------------------------------- | 580| id | number | 是 | 节点对应的UniqueId | 581 582**返回值:** 583 584| 类型 | 说明 | 585| ---------------------------------------- | ------------- | 586| [PageInfo](#pageinfo12) | 返回节点对应的Router和NavDestination信息。 | 587 588**示例:** 589 590```ts 591import { UIContext, PageInfo } from '@kit.ArkUI'; 592 593@Entry 594@Component 595struct PageInfoExample { 596 @Provide('pageInfos') pageInfos: NavPathStack = new NavPathStack(); 597 598 build() { 599 Column() { 600 Navigation(this.pageInfos) { 601 NavDestination() { 602 MyComponent() 603 } 604 }.id('navigation') 605 } 606 } 607} 608 609@Component 610struct MyComponent { 611 @State content: string = ''; 612 613 build() { 614 Column() { 615 Text('PageInfoExample') 616 Button('click').onClick(() => { 617 const uiContext: UIContext = this.getUIContext(); 618 const uniqueId: number = this.getUniqueId(); 619 const pageInfo: PageInfo = uiContext.getPageInfoByUniqueId(uniqueId); 620 console.info('pageInfo: ' + JSON.stringify(pageInfo)); 621 console.info('navigationInfo: ' + JSON.stringify(uiContext.getNavigationInfoByUniqueId(uniqueId))); 622 }) 623 TextArea({ 624 text: this.content 625 }) 626 .width('100%') 627 .height(100) 628 } 629 .width('100%') 630 .alignItems(HorizontalAlign.Center) 631 } 632} 633``` 634 635### getNavigationInfoByUniqueId<sup>12+</sup> 636 637getNavigationInfoByUniqueId(id: number): observer.NavigationInfo | undefined 638 639提供getNavigationInfoByUniqueId接口通过组件的uniqueId获取该节点对应的Navigation页面信息。 6401. 当uniqueId对应的节点在Navigation节点中,返回其对应的Navigation信息; 6412. 当uniqueId对应的节点无对应的Navigation信息时,返回undefined。 642 643**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 644 645**系统能力:** SystemCapability.ArkUI.ArkUI.Full 646 647**参数:** 648 649| 参数名 | 类型 | 必填 | 说明 | 650| ----- | ---------------------------------------- | ---- | ------------------------------------- | 651| id | number | 是 | 节点对应的UniqueId | 652 653**返回值:** 654 655| 类型 | 说明 | 656| ---------------------------------------- | ------------- | 657| observer.[NavigationInfo](js-apis-arkui-observer.md#navigationinfo12) \| undefined | 返回节点对应的Navigation信息。 | 658 659**示例:** 660 661请参考[getPageInfoByUniqueId](#getpageinfobyuniqueid12)的示例。 662 663### showAlertDialog 664 665showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions): void 666 667显示警告弹窗组件,可设置文本内容与响应回调。 668 669**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 670 671**系统能力:** SystemCapability.ArkUI.ArkUI.Full 672 673**参数:** 674 675| 参数名 | 类型 | 必填 | 说明 | 676| ------- | ---------------------------------------- | ---- | ------------------- | 677| options | [AlertDialogParamWithConfirm](arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm对象说明) \| [AlertDialogParamWithButtons](arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons对象说明) \| [AlertDialogParamWithOptions](arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithoptions10对象说明) | 是 | 定义并显示AlertDialog组件。 | 678 679 680**示例:** 681 682<!--code_no_check--> 683```ts 684uiContext.showAlertDialog( 685 { 686 title: 'title', 687 message: 'text', 688 autoCancel: true, 689 alignment: DialogAlignment.Bottom, 690 offset: { dx: 0, dy: -20 }, 691 gridCount: 3, 692 confirm: { 693 value: 'button', 694 action: () => { 695 console.info('Button-clicking callback') 696 } 697 }, 698 cancel: () => { 699 console.info('Closed callbacks') 700 } 701 } 702) 703``` 704 705### showActionSheet 706 707showActionSheet(value: ActionSheetOptions): void 708 709定义列表弹窗并弹出。 710 711**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 712 713**系统能力:** SystemCapability.ArkUI.ArkUI.Full 714 715**参数:** 716 717| 参数名 | 类型 | 必填 | 说明 | 718| ------ | ------------------------------------------------------------ | ---- | -------------------- | 719| value | [ActionSheetOptions](arkui-ts/ts-methods-action-sheet.md#actionsheetoptions对象说明) | 是 | 配置列表弹窗的参数。 | 720 721**示例:** 722 723<!--code_no_check--> 724```ts 725uiContext.showActionSheet({ 726 title: 'ActionSheet title', 727 message: 'message', 728 autoCancel: true, 729 confirm: { 730 value: 'Confirm button', 731 action: () => { 732 console.info('Get Alert Dialog handled') 733 } 734 }, 735 cancel: () => { 736 console.info('actionSheet canceled') 737 }, 738 alignment: DialogAlignment.Bottom, 739 offset: { dx: 0, dy: -10 }, 740 sheets: [ 741 { 742 title: 'apples', 743 action: () => { 744 console.info('apples') 745 } 746 }, 747 { 748 title: 'bananas', 749 action: () => { 750 console.info('bananas') 751 } 752 }, 753 { 754 title: 'pears', 755 action: () => { 756 console.info('pears') 757 } 758 } 759 ] 760}) 761``` 762 763### showDatePickerDialog 764 765showDatePickerDialog(options: DatePickerDialogOptions): void 766 767定义日期滑动选择器弹窗并弹出。 768 769**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 770 771**系统能力:** SystemCapability.ArkUI.ArkUI.Full 772 773**参数:** 774 775| 参数名 | 类型 | 必填 | 说明 | 776| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 777| options | [DatePickerDialogOptions](arkui-ts/ts-methods-datepicker-dialog.md#datepickerdialogoptions对象说明) | 是 | 配置日期滑动选择器弹窗的参数。 | 778 779**示例:** 780 781<!--code_no_check--> 782```ts 783let selectedDate: Date = new Date("2010-1-1") 784uiContext.showDatePickerDialog({ 785 start: new Date("2000-1-1"), 786 end: new Date("2100-12-31"), 787 selected: selectedDate, 788 onAccept: (value: DatePickerResult) => { 789 // 通过Date的setFullYear方法设置按下确定按钮时的日期,这样当弹窗再次弹出时显示选中的是上一次确定的日期 790 selectedDate.setFullYear(Number(value.year), Number(value.month), Number(value.day)) 791 console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) 792 }, 793 onCancel: () => { 794 console.info("DatePickerDialog:onCancel()") 795 }, 796 onChange: (value: DatePickerResult) => { 797 console.info("DatePickerDialog:onChange()" + JSON.stringify(value)) 798 } 799}) 800``` 801 802### showTimePickerDialog 803 804showTimePickerDialog(options: TimePickerDialogOptions): void 805 806定义时间滑动选择器弹窗并弹出。 807 808**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 809 810**系统能力:** SystemCapability.ArkUI.ArkUI.Full 811 812**参数:** 813 814| 参数名 | 类型 | 必填 | 说明 | 815| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 816| options | [TimePickerDialogOptions](arkui-ts/ts-methods-timepicker-dialog.md#timepickerdialogoptions对象说明) | 是 | 配置时间滑动选择器弹窗的参数。 | 817 818**示例:** 819 820```ts 821// xxx.ets 822 823class SelectTime{ 824 selectTime: Date = new Date('2020-12-25T08:30:00') 825 hours(h:number,m:number){ 826 this.selectTime.setHours(h,m) 827 } 828} 829 830@Entry 831@Component 832struct TimePickerDialogExample { 833 @State selectTime: Date = new Date('2023-12-25T08:30:00'); 834 835 build() { 836 Column() { 837 Button('showTimePickerDialog') 838 .margin(30) 839 .onClick(() => { 840 this.getUIContext().showTimePickerDialog({ 841 selected: this.selectTime, 842 onAccept: (value: TimePickerResult) => { 843 // 设置selectTime为按下确定按钮时的时间,这样当弹窗再次弹出时显示选中的为上一次确定的时间 844 let time = new SelectTime() 845 if(value.hour&&value.minute){ 846 time.hours(value.hour, value.minute) 847 } 848 console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) 849 }, 850 onCancel: () => { 851 console.info("TimePickerDialog:onCancel()") 852 }, 853 onChange: (value: TimePickerResult) => { 854 console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) 855 } 856 }) 857 }) 858 }.width('100%').margin({ top: 5 }) 859 } 860} 861``` 862 863### showTextPickerDialog 864 865showTextPickerDialog(options: TextPickerDialogOptions): void 866 867定义文本滑动选择器弹窗并弹出。 868 869**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 870 871**系统能力:** SystemCapability.ArkUI.ArkUI.Full 872 873**参数:** 874 875| 参数名 | 类型 | 必填 | 说明 | 876| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 877| options | [TextPickerDialogOptions](arkui-ts/ts-methods-textpicker-dialog.md#textpickerdialogoptions对象说明) | 是 | 配置文本滑动选择器弹窗的参数。 | 878 879**示例:** 880 881```ts 882// xxx.ets 883 884class SelectedValue{ 885 select: number = 2 886 set(val:number){ 887 this.select = val 888 } 889} 890class SelectedArray{ 891 select: number[] = [] 892 set(val:number[]){ 893 this.select = val 894 } 895} 896@Entry 897@Component 898struct TextPickerDialogExample { 899 @State selectTime: Date = new Date('2023-12-25T08:30:00'); 900 private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5'] 901 private select : number = 0; 902 build() { 903 Column() { 904 Button('showTextPickerDialog') 905 .margin(30) 906 .onClick(() => { 907 this.getUIContext().showTextPickerDialog({ 908 range: this.fruits, 909 selected: this.select, 910 onAccept: (value: TextPickerResult) => { 911 // 设置select为按下确定按钮时候的选中项index,这样当弹窗再次弹出时显示选中的是上一次确定的选项 912 let selectedVal = new SelectedValue() 913 let selectedArr = new SelectedArray() 914 if(value.index){ 915 value.index instanceof Array?selectedArr.set(value.index) : selectedVal.set(value.index) 916 } 917 console.info("TextPickerDialog:onAccept()" + JSON.stringify(value)) 918 }, 919 onCancel: () => { 920 console.info("TextPickerDialog:onCancel()") 921 }, 922 onChange: (value: TextPickerResult) => { 923 console.info("TextPickerDialog:onChange()" + JSON.stringify(value)) 924 } 925 }) 926 }) 927 }.width('100%').margin({ top: 5 }) 928 } 929} 930``` 931 932### createAnimator 933 934createAnimator(options: AnimatorOptions): AnimatorResult 935 936定义Animator类。 937 938**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 939 940**系统能力:** SystemCapability.ArkUI.ArkUI.Full 941 942**参数:** 943 944| 参数名 | 类型 | 必填 | 说明 | 945| ------- | ---------------------------------------- | ---- | ------- | 946| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) | 是 | 定义动画选项。 | 947 948**返回值:** 949 950| 类型 | 说明 | 951| ---------------------------------------- | ------------- | 952| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator结果接口。 | 953 954 955**错误码**: 956 957以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。 958 959| 错误码ID | 错误信息 | 960| ------- | -------- | 961| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 962 963**示例:** 964 965```ts 966// EntryAbility.ets 967import { AnimatorOptions, window } from '@kit.ArkUI'; 968import { hilog } from '@kit.PerformanceAnalysisKit'; 969 970// used in UIAbility 971onWindowStageCreate(windowStage: window.WindowStage) { 972 // Main window is created, set main page for this ability 973 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 974 windowStage.loadContent('pages/Index', (err, data) => { 975 if (err.code) { 976 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 977 return; 978 } 979 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 980 let uiContext = windowStage.getMainWindowSync().getUIContext(); 981 let options:AnimatorOptions = { 982 duration: 1500, 983 easing: "friction", 984 delay: 0, 985 fill: "forwards", 986 direction: "normal", 987 iterations: 3, 988 begin: 200.0, 989 end: 400.0 990 }; 991 uiContext.createAnimator(options); 992 }); 993} 994``` 995 996### runScopedTask 997 998runScopedTask(callback: () => void): void 999 1000在当前UI上下文执行传入的回调函数。 1001 1002**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1003 1004**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1005 1006**参数:** 1007 1008| 参数名 | 类型 | 必填 | 说明 | 1009| -------- | ---------- | ---- | ---- | 1010| callback | () => void | 是 | 回调函数 | 1011 1012**示例:** 1013 1014<!--code_no_check--> 1015```ts 1016uiContext.runScopedTask( 1017 () => { 1018 console.info('Succeeded in runScopedTask'); 1019 } 1020); 1021``` 1022 1023### setKeyboardAvoidMode<sup>11+</sup> 1024 1025setKeyboardAvoidMode(value: KeyboardAvoidMode): void 1026 1027配置虚拟键盘弹出时,页面的避让模式。 1028 1029**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1030 1031**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1032 1033**参数:** 1034 1035| 参数名 | 类型 | 必填 | 说明 | 1036| -------- | ---------- | ---- | ---- | 1037| value | [KeyboardAvoidMode](#keyboardavoidmode11)| 是 | 键盘避让时的页面避让模式。<br />默认值:KeyboardAvoidMode.OFFSET | 1038 1039**示例:** 1040 1041```ts 1042// EntryAbility.ets 1043import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI'; 1044import { hilog } from '@kit.PerformanceAnalysisKit'; 1045 1046onWindowStageCreate(windowStage: window.WindowStage) { 1047 // Main window is created, set main page for this ability 1048 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1049 1050 windowStage.loadContent('pages/Index', (err, data) => { 1051 let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext(); 1052 uiContext.setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE); 1053 if (err.code) { 1054 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1055 return; 1056 } 1057 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1058 }); 1059 } 1060``` 1061 1062### getKeyboardAvoidMode<sup>11+</sup> 1063 1064getKeyboardAvoidMode(): KeyboardAvoidMode 1065 1066获取虚拟键盘弹出时,页面的避让模式。 1067 1068**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1069 1070**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1071 1072**返回值:** 1073 1074| 类型 | 说明 | 1075| ---------- | ---- | 1076| [KeyboardAvoidMode](#keyboardavoidmode11)| 返回当前的页面避让模式。| 1077 1078**示例:** 1079 1080```ts 1081// EntryAbility.ets 1082import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI'; 1083import { hilog } from '@kit.PerformanceAnalysisKit'; 1084 1085onWindowStageCreate(windowStage: window.WindowStage) { 1086 // Main window is created, set main page for this ability 1087 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1088 1089 windowStage.loadContent('pages/Index', (err, data) => { 1090 let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext(); 1091 let KeyboardAvoidMode = uiContext.getKeyboardAvoidMode(); 1092 hilog.info(0x0000, "KeyboardAvoidMode:", JSON.stringify(KeyboardAvoidMode)); 1093 if (err.code) { 1094 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1095 return; 1096 } 1097 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1098 }); 1099 } 1100 1101``` 1102 1103### getAtomicServiceBar<sup>11+</sup> 1104 1105getAtomicServiceBar(): Nullable\<AtomicServiceBar> 1106 1107获取AtomicServiceBar对象,通过该对象设置原子化服务menuBar的属性。 1108 1109**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1110 1111**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1112 1113**返回值:** 1114 1115| 类型 | 说明 | 1116| ------------------------------------------------- | ------------------------------------------------------------ | 1117| Nullable<[AtomicServiceBar](#atomicservicebar11)> | 如果是原子化服务则返回AtomicServerBar类型,否则返回undefined。 | 1118 1119**示例:** 1120 1121```ts 1122// EntryAbility.ets 1123import { UIContext, AtomicServiceBar, window } from '@kit.ArkUI'; 1124import { hilog } from '@kit.PerformanceAnalysisKit'; 1125onWindowStageCreate(windowStage: window.WindowStage) { 1126 // Main window is created, set main page for this ability 1127 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 1128 windowStage.loadContent('pages/Index', (err, data) => { 1129 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 1130 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 1131 if (atomicServiceBar != undefined) { 1132 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 1133 } else { 1134 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 1135 } 1136 }); 1137} 1138``` 1139### getDragController<sup>11+</sup> 1140 1141getDragController(): DragController 1142 1143获取DragController对象,可通过该对象创建并发起拖拽。 1144 1145**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1146 1147**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1148 1149**返回值:** 1150 1151|类型|说明| 1152|----|----| 1153|[DragController](js-apis-arkui-dragController.md#dragController)| 获取DragController对象。| 1154 1155**示例:** 1156 1157<!--code_no_check--> 1158```ts 1159uiContext.getDragController(); 1160``` 1161 1162### keyframeAnimateTo<sup>11+</sup> 1163 1164keyframeAnimateTo(param: KeyframeAnimateParam, keyframes: Array<KeyframeState>): void 1165 1166产生关键帧动画。该接口的使用说明请参考[keyframeAnimateTo](arkui-ts/ts-keyframeAnimateTo.md)。 1167 1168**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1169 1170**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1171 1172**参数:** 1173 1174| 参数名 | 类型 | 必填 | 说明 | 1175| ------------ | ---------------------------------------------------- | ------- | ---------------------------- | 1176| param | [KeyframeAnimateParam](arkui-ts/ts-keyframeAnimateTo.md#keyframeanimateparam对象说明) | 是 | 关键帧动画的整体动画参数。 | 1177| keyframes | Array<[KeyframeState](arkui-ts/ts-keyframeAnimateTo.md#keyframestate对象说明)> | 是 | 所有的关键帧状态。 | 1178 1179### getFocusController<sup>12+</sup> 1180 1181getFocusController(): FocusController 1182 1183获取[FocusController](js-apis-arkui-UIContext.md#focuscontroller12)对象,可通过该对象控制焦点。 1184 1185**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1186 1187**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1188 1189**返回值:** 1190 1191|类型|说明| 1192|----|----| 1193|[FocusController](js-apis-arkui-UIContext.md#focuscontroller12)| 获取FocusController对象。| 1194 1195**示例:** 1196 1197<!--code_no_check--> 1198```ts 1199uiContext.getFocusController(); 1200``` 1201 1202### getFilteredInspectorTree<sup>12+</sup> 1203 1204getFilteredInspectorTree(filters?: Array\<string\>): string 1205 1206获取组件树及组件属性。 1207 1208**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1209 1210**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1211 1212**参数:** 1213 1214| 参数名 | 类型 | 必填 | 说明 | 1215| ------- | --------------- | ---- | ------------------------------------------------------------ | 1216| filters | Array\<string\> | 否 | 需要获取的组件属性的过滤列表。目前仅支持过滤字段:<br/>"id":组件唯一标识。<br/>"src":资源来源。 <br/>"content":元素、组件或对象所包含的信息或数据。<br/>"editable":是否可编辑。<br/>"scrollable":是否可滚动。<br/>"selectable":是否可选择。<br/>"focusable":是否可聚焦。<br/>"focused":是否已聚焦。<br/>其余字段仅供测试场景使用。 | 1217 1218**返回值:** 1219 1220| 类型 | 说明 | 1221| ------ | ---------------------------------- | 1222| string | 获取组件树及组件属性的JSON字符串。 | 1223 1224**错误码**: 1225 1226以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。 1227 1228| 错误码ID | 错误信息 | 1229| ------- | -------- | 1230| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1231 1232**示例:** 1233 1234<!--code_no_check--> 1235```ts 1236uiContext.getFilteredInspectorTree(['id', 'src', 'content']); 1237``` 1238 1239### getFilteredInspectorTreeById<sup>12+</sup> 1240 1241getFilteredInspectorTreeById(id: string, depth: number, filters?: Array\<string\>): string 1242 1243获取指定的组件及其子组件的属性。 1244 1245**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1246 1247**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1248 1249**参数:** 1250 1251| 参数名 | 类型 | 必填 | 说明 | 1252| ------- | --------------- | ---- | ------------------------------------------------------------ | 1253| id | string | 是 | 指定的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)id。 | 1254| depth | number | 是 | 获取子组件的层数。当取值0时,获取指定的组件及其所有的子孙组件的属性。当取值1时,仅获取指定的组件的属性。当取值2时,指定的组件及其1层子组件的属性。以此类推。 | 1255| filters | Array\<string\> | 否 | 需要获取的组件属性的过滤列表。目前仅支持过滤字段:<br/>"id":组件唯一标识。<br/>"src":资源来源。 <br/>"content":元素、组件或对象所包含的信息或数据。<br/>"editable":是否可编辑。<br/>"scrollable":是否可滚动。<br/>"selectable":是否可选择。<br/>"focusable":是否可聚焦。<br/>"focused":是否已聚焦。<br/>其余字段仅供测试场景使用。 | 1256 1257**返回值:** 1258 1259| 类型 | 说明 | 1260| ------ | -------------------------------------------- | 1261| string | 获取指定的组件及其子组件的属性的JSON字符串。 | 1262 1263 1264**错误码**: 1265 1266以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。 1267 1268| 错误码ID | 错误信息 | 1269| ------- | -------- | 1270| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1271 1272**示例:** 1273 1274<!--code_no_check--> 1275```ts 1276uiContext.getFilteredInspectorTreeById('testId', 0, ['id', 'src', 'content']); 1277``` 1278 1279### getCursorController<sup>12+</sup> 1280 1281getCursorController(): CursorController 1282 1283获取[CursorController](js-apis-arkui-UIContext.md#cursorcontroller12)对象,可通过该对象控制光标。 1284 1285**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1286 1287**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1288 1289**返回值:** 1290 1291|类型|说明| 1292|----|----| 1293|[CursorController](js-apis-arkui-UIContext.md#cursorcontroller12)| 获取CursorController对象。| 1294 1295**示例:** 1296 1297<!--code_no_check--> 1298```ts 1299uiContext.CursorController(); 1300``` 1301 1302### getContextMenuController<sup>12+</sup> 1303 1304getContextMenuController(): ContextMenuController 1305 1306获取[ContextMenuController](#contextmenucontroller12)对象,可通过该对象控制菜单。 1307 1308**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1309 1310**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1311 1312**返回值:** 1313 1314|类型|说明| 1315|----|----| 1316|[ContextMenuController](#contextmenucontroller12)| 获取ContextMenuController对象。| 1317 1318**示例:** 1319 1320<!--code_no_check--> 1321```ts 1322uiContext.getContextMenuController(); 1323``` 1324 1325### getMeasureUtils<sup>12+</sup> 1326 1327getMeasureUtils(): MeasureUtils 1328 1329允许用户通过UIContext对象,获取MeasureUtils对象进行文本计算。 1330 1331**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1332 1333**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1334 1335**返回值:** 1336 1337| 类型 | 说明 | 1338| ------ | -------------------------------------------- | 1339| [MeasureUtils](js-apis-arkui-UIContext.md#measureutils12) | 提供文本宽度、高度等相关计算。 | 1340 1341**示例:** 1342 1343<!--code_no_check--> 1344```ts 1345uiContext.getMeasureUtils(); 1346``` 1347 1348### getComponentSnapshot<sup>12+</sup> 1349 1350getComponentSnapshot(): ComponentSnapshot 1351 1352获取ComponentSnapshot对象,可通过该对象获取组件截图的能力。 1353 1354**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1355 1356**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1357 1358**返回值:** 1359 1360| 类型 | 说明 | 1361| ------------------------------------------------------------ | --------------------------- | 1362| [ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12) | 获取ComponentSnapshot对象。 | 1363 1364**示例:** 1365 1366<!--code_no_check--> 1367```ts 1368uiContext.getComponentSnapshot(); 1369``` 1370 1371### vp2px<sup>12+</sup> 1372 1373vp2px(value : number) : number 1374 1375将vp单位的数值转换为以px为单位的数值。 1376 1377**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1378 1379**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1380 1381**参数:** 1382 1383| 参数名 | 类型 | 必填 | 说明 | 1384| ------ | ------ | ---- | -------------------------------------- | 1385| value | number | 是 | 将vp单位的数值转换为以px为单位的数值。 | 1386 1387**返回值:** 1388 1389| 类型 | 说明 | 1390| ------ | -------------- | 1391| number | 转换后的数值。 | 1392 1393**示例:** 1394 1395<!--code_no_check--> 1396```ts 1397uiContext.vp2px(200); 1398``` 1399 1400### px2vp<sup>12+</sup> 1401 1402px2vp(value : number) : number 1403 1404将px单位的数值转换为以vp为单位的数值。 1405 1406**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1407 1408**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1409 1410**参数:** 1411 1412| 参数名 | 类型 | 必填 | 说明 | 1413| ------ | ------ | ---- | -------------------------------------- | 1414| value | number | 是 | 将px单位的数值转换为以vp为单位的数值。 | 1415 1416**返回值:** 1417 1418| 类型 | 说明 | 1419| ------ | -------------- | 1420| number | 转换后的数值。 | 1421 1422**示例:** 1423 1424<!--code_no_check--> 1425```ts 1426uiContext.px2vp(200); 1427``` 1428 1429### fp2px<sup>12+</sup> 1430 1431fp2px(value : number) : number 1432 1433将fp单位的数值转换为以px为单位的数值。 1434 1435**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1436 1437**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1438 1439**参数:** 1440 1441| 参数名 | 类型 | 必填 | 说明 | 1442| ------ | ------ | ---- | -------------------------------------- | 1443| value | number | 是 | 将fp单位的数值转换为以px为单位的数值。 | 1444 1445**返回值:** 1446 1447| 类型 | 说明 | 1448| ------ | -------------- | 1449| number | 转换后的数值。 | 1450 1451**示例:** 1452 1453<!--code_no_check--> 1454```ts 1455uiContext.fp2px(200); 1456``` 1457 1458### px2fp<sup>12+</sup> 1459 1460px2fp(value : number) : number 1461 1462将px单位的数值转换为以fp为单位的数值。 1463 1464**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1465 1466**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1467 1468**参数:** 1469 1470| 参数名 | 类型 | 必填 | 说明 | 1471| ------ | ------ | ---- | -------------------------------------- | 1472| value | number | 是 | 将px单位的数值转换为以fp为单位的数值。 | 1473 1474**返回值:** 1475 1476| 类型 | 说明 | 1477| ------ | -------------- | 1478| number | 转换后的数值。 | 1479 1480**示例:** 1481 1482<!--code_no_check--> 1483```ts 1484uiContext.px2fp(200); 1485``` 1486 1487### lpx2px<sup>12+</sup> 1488 1489lpx2px(value : number) : number 1490 1491将lpx单位的数值转换为以px为单位的数值。 1492 1493**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1494 1495**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1496 1497**参数:** 1498 1499| 参数名 | 类型 | 必填 | 说明 | 1500| ------ | ------ | ---- | --------------------------------------- | 1501| value | number | 是 | 将lpx单位的数值转换为以px为单位的数值。 | 1502 1503**返回值:** 1504 1505| 类型 | 说明 | 1506| ------ | -------------- | 1507| number | 转换后的数值。 | 1508 1509**示例:** 1510 1511<!--code_no_check--> 1512```ts 1513uiContext.lpx2px(200); 1514``` 1515 1516### px2lpx<sup>12+</sup> 1517 1518px2lpx(value : number) : number 1519 1520将px单位的数值转换为以lpx为单位的数值。 1521 1522**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1523 1524**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1525 1526**参数:** 1527 1528| 参数名 | 类型 | 必填 | 说明 | 1529| ------ | ------ | ---- | --------------------------------------- | 1530| value | number | 是 | 将px单位的数值转换为以lpx为单位的数值。 | 1531 1532**返回值:** 1533 1534| 类型 | 说明 | 1535| ------ | -------------- | 1536| number | 转换后的数值。 | 1537 1538**示例:** 1539 1540<!--code_no_check--> 1541```ts 1542uiContext.px2lpx(200); 1543``` 1544 1545### getWindowName<sup>12+</sup> 1546 1547getWindowName(): string | undefined 1548 1549获取当前实例所在窗口的名称。 1550 1551**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1552 1553**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1554 1555**返回值:** 1556 1557| 类型 | 说明 | 1558| ------ | -------------------------------------------- | 1559| string \| undefined | 当前实例所在窗口的名称。若窗口不存在,则返回undefined。 | 1560 1561**示例:** 1562 1563```ts 1564import { window } from '@kit.ArkUI'; 1565 1566@Entry 1567@Component 1568struct Index { 1569 @State message: string = 'Hello World' 1570 1571 aboutToAppear() { 1572 const windowName = this.getUIContext().getWindowName(); 1573 console.info('WindowName ' + windowName); 1574 const currWindow = window.findWindow(windowName); 1575 const windowProperties = currWindow.getWindowProperties(); 1576 console.info(`Window width ${windowProperties.windowRect.width}, height ${windowProperties.windowRect.height}`); 1577 } 1578 1579 build() { 1580 Row() { 1581 Column() { 1582 Text(this.message) 1583 .fontSize(50) 1584 .fontWeight(FontWeight.Bold) 1585 } 1586 .width('100%') 1587 } 1588 .height('100%') 1589 } 1590} 1591``` 1592 1593### getWindowWidthBreakpoint<sup>13+</sup> 1594 1595getWindowWidthBreakpoint(): WidthBreakpoint 1596 1597获取当前实例所在窗口的宽度断点枚举值。具体枚举值根据窗口宽度vp值确定,详见 [WidthBreakpoint](./arkui-ts/ts-appendix-enums.md#widthbreakpoint13)。 1598 1599**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 1600 1601**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1602 1603**返回值:** 1604 1605| 类型 | 说明 | 1606| ------ | -------------------------------------------- | 1607| [WidthBreakpoint](./arkui-ts/ts-appendix-enums.md#widthbreakpoint13) | 当前实例所在窗口的宽度断点枚举值。若窗口宽度为 0vp,则返回WIDTH_XS。 | 1608 1609**示例:** 1610 1611```ts 1612import { UIContext } from '@kit.ArkUI'; 1613 1614@Entry 1615@Component 1616struct Index { 1617 @State message: string = 'Hello World'; 1618 1619 build() { 1620 Row() { 1621 Column() { 1622 Text(this.message) 1623 .fontSize(30) 1624 .fontWeight(FontWeight.Bold) 1625 Button() { 1626 Text('test') 1627 .fontSize(30) 1628 } 1629 .onClick(() => { 1630 let uiContext: UIContext = this.getUIContext(); 1631 let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint(); 1632 let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint(); 1633 console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`) 1634 }) 1635 } 1636 .width('100%') 1637 } 1638 .height('100%') 1639 } 1640} 1641``` 1642 1643### getWindowHeightBreakpoint<sup>13+</sup> 1644 1645getWindowHeightBreakpoint(): HeightBreakpoint 1646 1647获取当前实例所在窗口的高度断点。具体枚举值根据窗口高宽比确定,详见 [HeightBreakpoint](./arkui-ts/ts-appendix-enums.md#heightbreakpoint13)。 1648 1649**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 1650 1651**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1652 1653**返回值:** 1654 1655| 类型 | 说明 | 1656| ------ | -------------------------------------------- | 1657| [HeightBreakpoint](./arkui-ts/ts-appendix-enums.md#heightbreakpoint13) | 当前实例所在窗口的宽高比对应的高度断点枚举值。若窗口高宽比为0,则返回HEIGHT_SM。 | 1658 1659**示例:** 1660 1661```ts 1662import { UIContext } from '@kit.ArkUI'; 1663 1664@Entry 1665@Component 1666struct Index { 1667 @State message: string = 'Hello World'; 1668 1669 build() { 1670 Row() { 1671 Column() { 1672 Text(this.message) 1673 .fontSize(30) 1674 .fontWeight(FontWeight.Bold) 1675 Button() { 1676 Text('test') 1677 .fontSize(30) 1678 } 1679 .onClick(() => { 1680 let uiContext: UIContext = this.getUIContext(); 1681 let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint(); 1682 let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint(); 1683 console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`) 1684 }) 1685 } 1686 .width('100%') 1687 } 1688 .height('100%') 1689 } 1690} 1691``` 1692 1693### postFrameCallback<sup>12+</sup> 1694 1695postFrameCallback(frameCallback: FrameCallback): void 1696 1697注册一个回调,仅在下一帧渲染时调用。 1698 1699**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1700 1701**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1702 1703**参数:** 1704 1705| 参数名 | 类型 | 必填 | 说明 | 1706| ------ | ------ | ---- | --------------------------------------- | 1707| frameCallback | [FrameCallback](#framecallback12) | 是 | 下一帧需要执行的回调。 | 1708 1709**示例:** 1710 1711```ts 1712import {FrameCallback } from '@kit.ArkUI'; 1713 1714class MyFrameCallback extends FrameCallback { 1715 private tag: string; 1716 1717 constructor(tag: string) { 1718 super() 1719 this.tag = tag; 1720 } 1721 1722 onFrame(frameTimeNanos: number) { 1723 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 1724 } 1725} 1726 1727@Entry 1728@Component 1729struct Index { 1730 build() { 1731 Row() { 1732 Button('点击触发postFrameCallback') 1733 .onClick(() => { 1734 this.getUIContext().postFrameCallback(new MyFrameCallback("normTask")); 1735 }) 1736 } 1737 } 1738} 1739``` 1740 1741### postDelayedFrameCallback<sup>12+</sup> 1742 1743postDelayedFrameCallback(frameCallback: FrameCallback, delayTime: number): void 1744 1745注册一个回调,在延迟一段时间后的下一帧进行渲染时执行。 1746 1747**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1748 1749**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1750 1751**参数:** 1752 1753| 参数名 | 类型 | 必填 | 说明 | 1754| ------ | ------ | ---- | --------------------------------------- | 1755| frameCallback | [FrameCallback](#framecallback12) | 是 | 下一帧需要执行的回调。 | 1756| delayTime | number | 是 | 延迟的时间,以毫秒为单位。传入null、undefined或小于0的值,会按0处理。 | 1757 1758**示例:** 1759 1760```ts 1761import {FrameCallback } from '@kit.ArkUI'; 1762 1763class MyFrameCallback extends FrameCallback { 1764 private tag: string; 1765 1766 constructor(tag: string) { 1767 super() 1768 this.tag = tag; 1769 } 1770 1771 onFrame(frameTimeNanos: number) { 1772 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 1773 } 1774} 1775 1776@Entry 1777@Component 1778struct Index { 1779 build() { 1780 Row() { 1781 Button('点击触发postDelayedFrameCallback') 1782 .onClick(() => { 1783 this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5); 1784 }) 1785 } 1786 } 1787} 1788``` 1789 1790### requireDynamicSyncScene<sup>12+</sup> 1791 1792requireDynamicSyncScene(id: string): Array<DynamicSyncScene> 1793 1794请求组件的动态帧率场景,用于自定义场景相关帧率配置。 1795 1796**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1797 1798**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1799 1800**参数:** 1801 1802| 参数名 | 类型 | 必填 | 说明 | 1803| ------ | ------ | ---- | --------------------------------------- | 1804| id | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。| 1805 1806**返回值:** 1807 1808| 类型 | 说明 | 1809| ------ | -------------------------------------------- | 1810| Array<DynamicSyncScene> | 获取DynamicSyncScene对象数组。 | 1811 1812**示例:** 1813 1814<!--code_no_check--> 1815```ts 1816uiContext.DynamicSyncScene("dynamicSyncScene") 1817``` 1818 1819### openBindSheet<sup>12+</sup> 1820 1821openBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions?: SheetOptions, targetId?: number): Promise<void> 1822 1823创建并弹出以bindSheetContent作为内容的半模态页面,使用Promise异步回调。通过该接口弹出的半模态页面样式完全按照bindSheetContent中设置的样式显示。 1824 1825> **说明:** 1826> 1827> 1. 使用该接口时,若未传入有效的targetId,则不支持设置SheetOptions.preferType为POPUP模式、不支持设置SheetOptions.mode为EMBEDDED模式。 1828> 1829> 2. 由于[updateBindSheet](#updatebindsheet12)和[closeBindSheet](#closebindsheet12)依赖bindSheetContent去更新或者关闭指定的半模态页面,开发者需自行维护传入的bindSheetContent。 1830> 1831> 3. 不支持设置SheetOptions.UIContext。 1832> 1833 1834**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1835 1836**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1837 1838**参数:** 1839 1840| 参数名 | 类型 | 必填 | 说明 | 1841| ------- | ---------------------------------------- | ---- | ------- | 1842| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 | 1843| 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)文档。 | 1844| targetId | number | 否 | 需要绑定组件的ID,若不指定则不绑定任何组件。 | 1845 1846**返回值:** 1847 1848| 类型 | 说明 | 1849| ---------------------------------------- | ------- | 1850| Promise<void> | 异常返回Promise对象。 | 1851 1852**错误码:** 1853 1854以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。 1855 1856| 错误码ID | 错误信息 | 1857| ------ | ---------------------------------- | 1858| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1859| 120001 | The bindSheetContent is incorrect. | 1860| 120002 | The bindSheetContent already exists. | 1861| 120004 | The targetId does not exist. | 1862| 120005 | The node of targetId is not in the component tree. | 1863| 120006 | The node of targetId is not a child of the page node or NavDestination node. | 1864 1865**示例:** 1866 1867```ts 1868import { FrameNode, ComponentContent } from "@kit.ArkUI"; 1869import { BusinessError } from '@kit.BasicServicesKit'; 1870 1871class Params { 1872 text: string = "" 1873 1874 constructor(text: string) { 1875 this.text = text; 1876 } 1877} 1878 1879let contentNode: ComponentContent<Params>; 1880let gUIContext: UIContext; 1881 1882@Builder 1883function buildText(params: Params) { 1884 Column() { 1885 Text(params.text) 1886 Button('Update BindSheet') 1887 .fontSize(20) 1888 .onClick(() => { 1889 gUIContext.updateBindSheet(contentNode, { 1890 backgroundColor: Color.Pink, 1891 }, true) 1892 .then(() => { 1893 console.info('updateBindSheet success'); 1894 }) 1895 .catch((err: BusinessError) => { 1896 console.info('updateBindSheet error: ' + err.code + ' ' + err.message); 1897 }) 1898 }) 1899 1900 Button('Close BindSheet') 1901 .fontSize(20) 1902 .onClick(() => { 1903 gUIContext.closeBindSheet(contentNode) 1904 .then(() => { 1905 console.info('closeBindSheet success'); 1906 }) 1907 .catch((err: BusinessError) => { 1908 console.info('closeBindSheet error: ' + err.code + ' ' + err.message); 1909 }) 1910 }) 1911 } 1912} 1913 1914@Entry 1915@Component 1916struct UIContextBindSheet { 1917 @State message: string = 'BindSheet'; 1918 1919 aboutToAppear() { 1920 gUIContext = this.getUIContext(); 1921 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 1922 } 1923 1924 build() { 1925 RelativeContainer() { 1926 Column() { 1927 Button('Open BindSheet') 1928 .fontSize(20) 1929 .onClick(() => { 1930 let uiContext = this.getUIContext(); 1931 let uniqueId = this.getUniqueId(); 1932 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 1933 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 1934 uiContext.openBindSheet(contentNode, { 1935 height: SheetSize.MEDIUM, 1936 backgroundColor: Color.Green, 1937 title: { title: "Title", subtitle: "subtitle" } 1938 }, targetId) 1939 .then(() => { 1940 console.info('openBindSheet success'); 1941 }) 1942 .catch((err: BusinessError) => { 1943 console.info('openBindSheet error: ' + err.code + ' ' + err.message); 1944 }) 1945 }) 1946 } 1947 } 1948 .height('100%') 1949 .width('100%') 1950 } 1951} 1952``` 1953 1954### updateBindSheet<sup>12+</sup> 1955 1956updateBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions: SheetOptions, partialUpdate?: boolean ): Promise<void> 1957 1958更新bindSheetContent对应的半模态页面的样式,使用Promise异步回调。 1959 1960> **说明:** 1961> 1962> 不支持更新SheetOptions.UIContext、SheetOptions.mode、回调函数。 1963> 1964 1965**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1966 1967**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1968 1969**参数:** 1970 1971| 参数名 | 类型 | 必填 | 说明 | 1972| ------- | ---------------------------------------- | ---- | ------- | 1973| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 | 1974| sheetOptions | [SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions) | 是 | 半模态页面样式。<br/>**说明:** <br/>不支持更新SheetOptions.uiContext、SheetOptions.mode、回调函数。 | 1975| partialUpdate | boolean | 否 | 半模态页面更新方式, 默认值为false。<br/>**说明:** <br/>1. true为增量更新,保留当前值,更新SheetOptions中的指定属性。 <br/>2. false为全量更新,除SheetOptions中的指定属性,其他属性恢复默认值。 | 1976 1977**返回值:** 1978 1979| 类型 | 说明 | 1980| ---------------------------------------- | ------- | 1981| Promise<void> | 异常返回Promise对象。 | 1982 1983**错误码:** 1984 1985以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。 1986 1987| 错误码ID | 错误信息 | 1988| ------ | ---------------------------------- | 1989| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1990| 120001 | The bindSheetContent is incorrect. | 1991| 120003 | The bindSheetContent cannot be found. | 1992 1993**示例:** 1994 1995```ts 1996import { FrameNode, ComponentContent } from "@kit.ArkUI"; 1997import { BusinessError } from '@kit.BasicServicesKit'; 1998 1999class Params { 2000 text: string = "" 2001 2002 constructor(text: string) { 2003 this.text = text; 2004 } 2005} 2006 2007let contentNode: ComponentContent<Params>; 2008let gUIContext: UIContext; 2009 2010@Builder 2011function buildText(params: Params) { 2012 Column() { 2013 Text(params.text) 2014 Button('Update BindSheet') 2015 .fontSize(20) 2016 .onClick(() => { 2017 gUIContext.updateBindSheet(contentNode, { 2018 backgroundColor: Color.Pink, 2019 }, true) 2020 .then(() => { 2021 console.info('updateBindSheet success'); 2022 }) 2023 .catch((err: BusinessError) => { 2024 console.info('updateBindSheet error: ' + err.code + ' ' + err.message); 2025 }) 2026 }) 2027 2028 Button('Close BindSheet') 2029 .fontSize(20) 2030 .onClick(() => { 2031 gUIContext.closeBindSheet(contentNode) 2032 .then(() => { 2033 console.info('closeBindSheet success'); 2034 }) 2035 .catch((err: BusinessError) => { 2036 console.info('closeBindSheet error: ' + err.code + ' ' + err.message); 2037 }) 2038 }) 2039 } 2040} 2041 2042@Entry 2043@Component 2044struct UIContextBindSheet { 2045 @State message: string = 'BindSheet'; 2046 2047 aboutToAppear() { 2048 gUIContext = this.getUIContext(); 2049 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 2050 } 2051 2052 build() { 2053 RelativeContainer() { 2054 Column() { 2055 Button('Open BindSheet') 2056 .fontSize(20) 2057 .onClick(() => { 2058 let uiContext = this.getUIContext(); 2059 let uniqueId = this.getUniqueId(); 2060 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 2061 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 2062 uiContext.openBindSheet(contentNode, { 2063 height: SheetSize.MEDIUM, 2064 backgroundColor: Color.Green, 2065 title: { title: "Title", subtitle: "subtitle" } 2066 }, targetId) 2067 .then(() => { 2068 console.info('openBindSheet success'); 2069 }) 2070 .catch((err: BusinessError) => { 2071 console.info('openBindSheet error: ' + err.code + ' ' + err.message); 2072 }) 2073 }) 2074 } 2075 } 2076 .height('100%') 2077 .width('100%') 2078 } 2079} 2080``` 2081 2082### closeBindSheet<sup>12+</sup> 2083 2084closeBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>): Promise<void> 2085 2086关闭bindSheetContent对应的半模态页面,使用Promise异步回调。 2087 2088> **说明:** 2089> 2090> 使用此接口关闭半模态页面时,不会触发shouldDismiss回调。 2091> 2092 2093**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2094 2095**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2096 2097**参数:** 2098 2099| 参数名 | 类型 | 必填 | 说明 | 2100| ------- | ---------------------------------------- | ---- | ------- | 2101| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 | 2102 2103**返回值:** 2104 2105| 类型 | 说明 | 2106| ---------------------------------------- | ------- | 2107| Promise<void> | 异常返回Promise对象。 | 2108 2109**错误码:** 2110 2111以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。 2112 2113| 错误码ID | 错误信息 | 2114| ------ | ---------------------------------- | 2115| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 2116| 120001 | The bindSheetContent is incorrect. | 2117| 120003 | The bindSheetContent cannot be found. | 2118 2119**示例:** 2120 2121```ts 2122import { FrameNode, ComponentContent } from "@kit.ArkUI"; 2123import { BusinessError } from '@kit.BasicServicesKit'; 2124 2125class Params { 2126 text: string = "" 2127 2128 constructor(text: string) { 2129 this.text = text; 2130 } 2131} 2132 2133let contentNode: ComponentContent<Params>; 2134let gUIContext: UIContext; 2135 2136@Builder 2137function buildText(params: Params) { 2138 Column() { 2139 Text(params.text) 2140 Button('Update BindSheet') 2141 .fontSize(20) 2142 .onClick(() => { 2143 gUIContext.updateBindSheet(contentNode, { 2144 backgroundColor: Color.Pink, 2145 }, true) 2146 .then(() => { 2147 console.info('updateBindSheet success'); 2148 }) 2149 .catch((err: BusinessError) => { 2150 console.info('updateBindSheet error: ' + err.code + ' ' + err.message); 2151 }) 2152 }) 2153 2154 Button('Close BindSheet') 2155 .fontSize(20) 2156 .onClick(() => { 2157 gUIContext.closeBindSheet(contentNode) 2158 .then(() => { 2159 console.info('closeBindSheet success'); 2160 }) 2161 .catch((err: BusinessError) => { 2162 console.info('closeBindSheet error: ' + err.code + ' ' + err.message); 2163 }) 2164 }) 2165 } 2166} 2167 2168@Entry 2169@Component 2170struct UIContextBindSheet { 2171 @State message: string = 'BindSheet'; 2172 2173 aboutToAppear() { 2174 gUIContext = this.getUIContext(); 2175 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 2176 } 2177 2178 build() { 2179 RelativeContainer() { 2180 Column() { 2181 Button('Open BindSheet') 2182 .fontSize(20) 2183 .onClick(() => { 2184 let uiContext = this.getUIContext(); 2185 let uniqueId = this.getUniqueId(); 2186 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 2187 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 2188 uiContext.openBindSheet(contentNode, { 2189 height: SheetSize.MEDIUM, 2190 backgroundColor: Color.Green, 2191 title: { title: "Title", subtitle: "subtitle" } 2192 }, targetId) 2193 .then(() => { 2194 console.info('openBindSheet success'); 2195 }) 2196 .catch((err: BusinessError) => { 2197 console.info('openBindSheet error: ' + err.code + ' ' + err.message); 2198 }) 2199 }) 2200 } 2201 } 2202 .height('100%') 2203 .width('100%') 2204 } 2205} 2206``` 2207 2208### isFollowingSystemFontScale<sup>13+</sup> 2209 2210isFollowingSystemFontScale(): boolean 2211 2212获取当前UI上下文是否跟随系统字体倍率。 2213 2214**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2215 2216**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2217 2218**返回值:** 2219 2220| 类型 | 说明 | 2221|---------|---------------| 2222| boolean | 当前UI上下文是否跟随系统字体倍率。 | 2223 2224**示例:** 2225 2226<!--code_no_check--> 2227```ts 2228uiContext.isFollowingSystemFontScale() 2229``` 2230 2231### getMaxFontScale<sup>13+</sup> 2232 2233getMaxFontScale(): number 2234 2235获取当前UI上下文最大字体倍率。 2236 2237**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2238 2239**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2240 2241**返回值:** 2242 2243| 类型 | 说明 | 2244|---------|-----------| 2245| number | 当前UI上下文最大字体倍率。 | 2246 2247**示例:** 2248 2249<!--code_no_check--> 2250```ts 2251uiContext.getMaxFontScale() 2252``` 2253 2254### bindTabsToScrollable<sup>13+</sup> 2255 2256bindTabsToScrollable(tabsController: TabsController, scroller: Scroller): void; 2257 2258绑定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绑定。 2259 2260> **说明:** 2261> 2262> 当多个可滚动容器组件绑定了同一个Tabs组件时,只要滑动任意一个可滚动容器组件,就会触发TabBar的显示或隐藏。且当任意一个可滚动容器组件滑动到底部时,会立即触发TabBar的显示动效。因此不建议同时触发多个可滚动容器组件的滑动。 2263 2264**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2265 2266**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2267 2268**参数:** 2269 2270| 参数名 | 类型 | 必填 | 说明 | 2271| ------- | ---------------------------------------- | ---- | ------- | 2272| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 | 2273| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 | 2274 2275**示例:** 2276 2277```ts 2278@Entry 2279@Component 2280struct TabsExample { 2281 private arr: string[] = [] 2282 private parentTabsController: TabsController = new TabsController() 2283 private childTabsController: TabsController = new TabsController() 2284 private listScroller: Scroller = new Scroller() 2285 private parentScroller: Scroller = new Scroller() 2286 private childScroller: Scroller = new Scroller() 2287 2288 aboutToAppear(): void { 2289 for (let i = 0; i < 20; i++) { 2290 this.arr.push(i.toString()) 2291 } 2292 let context = this.getUIContext() 2293 context.bindTabsToScrollable(this.parentTabsController, this.listScroller) 2294 context.bindTabsToScrollable(this.childTabsController, this.listScroller) 2295 context.bindTabsToNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller) 2296 } 2297 2298 aboutToDisappear(): void { 2299 let context = this.getUIContext() 2300 context.unbindTabsFromScrollable(this.parentTabsController, this.listScroller) 2301 context.unbindTabsFromScrollable(this.childTabsController, this.listScroller) 2302 context.unbindTabsFromNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller) 2303 } 2304 2305 build() { 2306 Tabs({ barPosition: BarPosition.End, controller: this.parentTabsController }) { 2307 TabContent() { 2308 Tabs({ controller: this.childTabsController }) { 2309 TabContent() { 2310 List({ space: 20, initialIndex: 0, scroller: this.listScroller }) { 2311 ForEach(this.arr, (item: string) => { 2312 ListItem() { 2313 Text(item) 2314 .width('100%') 2315 .height(100) 2316 .fontSize(16) 2317 .textAlign(TextAlign.Center) 2318 .borderRadius(10) 2319 .backgroundColor(Color.Gray) 2320 } 2321 }, (item: string) => item) 2322 } 2323 .scrollBar(BarState.Off) 2324 .width('90%') 2325 .height('100%') 2326 .contentStartOffset(56) 2327 .contentEndOffset(52) 2328 }.tabBar(SubTabBarStyle.of('顶部页签')) 2329 } 2330 .width('100%') 2331 .height('100%') 2332 .barOverlap(true) // 使TabBar叠加在TabContent上,当TabBar向上或向下隐藏后,原位置处不为空白 2333 .clip(true) // 对超出Tabs组件范围的子组件进行裁剪,防止TabBar向上或向下隐藏后误触TabBar 2334 }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), 'scroller联动多个TabsController')) 2335 2336 TabContent() { 2337 Scroll(this.parentScroller) { 2338 List({ space: 20, initialIndex: 0, scroller: this.childScroller }) { 2339 ForEach(this.arr, (item: string) => { 2340 ListItem() { 2341 Text(item) 2342 .width('100%') 2343 .height(100) 2344 .fontSize(16) 2345 .textAlign(TextAlign.Center) 2346 .borderRadius(10) 2347 .backgroundColor(Color.Gray) 2348 } 2349 }, (item: string) => item) 2350 } 2351 .scrollBar(BarState.Off) 2352 .width('90%') 2353 .height('100%') 2354 .contentEndOffset(52) 2355 .nestedScroll({ scrollForward: NestedScrollMode.SELF_FIRST, scrollBackward: NestedScrollMode.SELF_FIRST }) 2356 } 2357 .width('100%') 2358 .height('100%') 2359 .scrollBar(BarState.Off) 2360 .scrollable(ScrollDirection.Vertical) 2361 .edgeEffect(EdgeEffect.Spring) 2362 }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), '嵌套的scroller联动TabsController')) 2363 } 2364 .width('100%') 2365 .height('100%') 2366 .barOverlap(true) // 使TabBar叠加在TabContent上,当TabBar向上或向下隐藏后,原位置处不为空白 2367 .clip(true) // 对超出Tabs组件范围的子组件进行裁剪,防止TabBar向上或向下隐藏后误触TabBar 2368 } 2369} 2370``` 2371 2372 2373 2374### unbindTabsFromScrollable<sup>13+</sup> 2375 2376unbindTabsFromScrollable(tabsController: TabsController, scroller: Scroller): void; 2377 2378解除Tabs组件和可滚动容器组件的绑定。 2379 2380**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2381 2382**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2383 2384**参数:** 2385 2386| 参数名 | 类型 | 必填 | 说明 | 2387| ------- | ---------------------------------------- | ---- | ------- | 2388| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 | 2389| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 | 2390 2391**示例:** 2392 2393参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。 2394 2395### bindTabsToNestedScrollable<sup>13+</sup> 2396 2397bindTabsToNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void; 2398 2399绑定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绑定。 2400 2401**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2402 2403**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2404 2405**参数:** 2406 2407| 参数名 | 类型 | 必填 | 说明 | 2408| ------- | ---------------------------------------- | ---- | ------- | 2409| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 | 2410| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 | 2411| childScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。其对应组件为parentScroller对应组件的子组件,且组件间存在嵌套滚动关系。 | 2412 2413**示例:** 2414 2415参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。 2416 2417### unbindTabsFromNestedScrollable<sup>13+</sup> 2418 2419unbindTabsFromNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void; 2420 2421解除Tabs组件和嵌套的可滚动容器组件的绑定。 2422 2423**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2424 2425**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2426 2427**参数:** 2428 2429| 参数名 | 类型 | 必填 | 说明 | 2430| ------- | ---------------------------------------- | ---- | ------- | 2431| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 | 2432| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 | 2433| childScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。其对应组件为parentScroller对应组件的子组件,且组件间存在嵌套滚动关系。 | 2434 2435**示例:** 2436 2437参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。 2438 2439### dispatchKeyEvent<sup>15+</sup> 2440 2441dispatchKeyEvent(node: number | string, event: KeyEvent): boolean 2442 2443按键事件应分发给指定的组件。为了确保行为的可预测性,目标组件必须位于分发组件的子树中。 2444 2445**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 2446 2447**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2448 2449| 参数名 | 类型 | 必填 | 说明 | 2450| ------ | ----------------------------- | ---- | ------------------ | 2451| node | number \| string | 是 | 组件的id或者节点UniqueID。 | 2452| event |[KeyEvent](./arkui-ts/ts-universal-events-key.md#keyevent对象说明) | 是 | KeyEvent对象。 | 2453 2454**示例:** 2455 2456```ts 2457@Entry 2458@Component 2459struct Index { 2460 build() { 2461 Row() { 2462 Row() { 2463 Button('Button1').id('Button1').onKeyEvent((event) => { 2464 console.log("Button1"); 2465 return true 2466 }) 2467 Button('Button2').id('Button2').onKeyEvent((event) => { 2468 console.log("Button2"); 2469 return true 2470 }) 2471 } 2472 .width('100%') 2473 .height('100%') 2474 .id('Row1') 2475 .onKeyEventDispatch((event) => { 2476 let context = this.getUIContext(); 2477 context.getFocusController().requestFocus('Button1'); 2478 return context.dispatchKeyEvent('Button1', event); 2479 }) 2480 2481 } 2482 .height('100%') 2483 .width('100%') 2484 .onKeyEventDispatch((event) => { 2485 if (event.type == KeyType.Down) { 2486 let context = this.getUIContext(); 2487 context.getFocusController().requestFocus('Row1'); 2488 return context.dispatchKeyEvent('Row1', event); 2489 } 2490 return true; 2491 }) 2492 } 2493} 2494``` 2495 2496## Font 2497 2498以下API需先使用UIContext中的[getFont()](#getfont)方法获取到Font对象,再通过该对象调用对应方法。 2499 2500### registerFont 2501 2502registerFont(options: font.FontOptions): void 2503 2504在字体管理中注册自定义字体。 2505 2506**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 2507 2508**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2509 2510**参数:** 2511 2512| 参数名 | 类型 | 必填 | 说明 | 2513| ------- | ---------------------------------------- | ---- | ----------- | 2514| options | [font.FontOptions](js-apis-font.md#fontoptions) | 是 | 注册的自定义字体信息。 | 2515 2516**示例:** 2517 2518<!--code_no_check--> 2519```ts 2520import { Font } from '@kit.ArkUI'; 2521 2522let font:Font = uiContext.getFont(); 2523font.registerFont({ 2524 familyName: 'medium', 2525 familySrc: '/font/medium.ttf' 2526}); 2527``` 2528### getSystemFontList 2529 2530getSystemFontList(): Array\<string> 2531 2532获取系统支持的字体名称列表。 2533 2534**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 2535 2536**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2537 2538**返回值:** 2539 2540| 类型 | 说明 | 2541| -------------- | --------- | 2542| Array\<string> | 系统的字体名列表。 | 2543 2544> **说明:** 2545> 2546> 该接口仅在2in1设备上生效。 2547 2548**示例:** 2549 2550<!--code_no_check--> 2551```ts 2552import { Font } from '@kit.ArkUI'; 2553 2554let font:Font|undefined = uiContext.getFont(); 2555if(font){ 2556 font.getSystemFontList() 2557} 2558``` 2559 2560### getFontByName 2561 2562getFontByName(fontName: string): font.FontInfo 2563 2564根据传入的系统字体名称获取系统字体的相关信息。 2565 2566**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 2567 2568**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2569 2570**参数:** 2571 2572| 参数名 | 类型 | 必填 | 说明 | 2573| -------- | ------ | ---- | ------- | 2574| fontName | string | 是 | 系统的字体名。 | 2575 2576**返回值:** 2577 2578| 类型 | 说明 | 2579| ----------------------------------------- | -------------- | 2580| [font.FontInfo](js-apis-font.md#fontinfo) | 字体的详细信息 | 2581 2582**示例:** 2583 2584<!--code_no_check--> 2585```ts 2586import { Font } from '@kit.ArkUI'; 2587 2588let font:Font|undefined = uiContext.getFont(); 2589if(font){ 2590 font.getFontByName('Sans Italic') 2591} 2592``` 2593 2594## Context<sup>12+</sup> 2595 2596type Context = common.Context 2597 2598当前组件所在Ability的上下文。 2599 2600**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2601 2602**系统能力:** SystemCapability.Ability.AbilityRuntime.Core 2603 2604**模型约束:** 此接口仅可在Stage模型下使用。 2605 2606| 类型 |说明 | 2607| ------ | ------------------- | 2608| [common.Context](../apis-ability-kit/js-apis-app-ability-common.md#context) |Context的具体类型为当前Ability关联的Context对象。| 2609 2610## ComponentUtils 2611 2612以下API需先使用UIContext中的[getComponentUtils()](#getcomponentutils)方法获取到ComponentUtils对象,再通过该对象调用对应方法。 2613 2614### getRectangleById 2615 2616getRectangleById(id: string): componentUtils.ComponentInfo 2617 2618获取组件大小、位置、平移缩放旋转及仿射矩阵属性信息。 2619 2620**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 2621 2622**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2623 2624**参数:** 2625 2626| 参数名 | 类型 | 必填 | 说明 | 2627| ---- | ------ | ---- | --------- | 2628| id | string | 是 | 组件唯一标识id。 | 2629 2630**返回值:** 2631 2632| 类型 | 说明 | 2633| ------------------------------------------------------------ | ------------------------------------------------ | 2634| [componentUtils.ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | 组件大小、位置、平移缩放旋转及仿射矩阵属性信息。 | 2635 2636**错误码:** 2637 2638以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 2639 2640| 错误码ID | 错误信息 | 2641| ------ | ------------------- | 2642| 100001 | UI execution context not found. | 2643 2644**示例:** 2645 2646<!--code_no_check--> 2647```ts 2648import { ComponentUtils } from '@kit.ArkUI'; 2649 2650let componentUtils:ComponentUtils = uiContext.getComponentUtils(); 2651let modePosition = componentUtils.getRectangleById("onClick"); 2652let localOffsetWidth = modePosition.size.width; 2653let localOffsetHeight = modePosition.size.height; 2654``` 2655 2656## UIInspector 2657 2658以下API需先使用UIContext中的[getUIInspector()](#getuiinspector)方法获取到UIInspector对象,再通过该对象调用对应方法。 2659 2660### createComponentObserver 2661 2662createComponentObserver(id: string): inspector.ComponentObserver 2663 2664注册组件布局和组件绘制送显完成回调通知。 2665 2666**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 2667 2668**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2669 2670**参数:** 2671 2672| 参数名 | 类型 | 必填 | 说明 | 2673| ---- | ------ | ---- | ------- | 2674| id | string | 是 | 指定组件id,该id通过通用属性[id](./arkui-ts/ts-universal-attributes-component-id.md#id)或者[key](./arkui-ts/ts-universal-attributes-component-id.md#key12)设置。 | 2675 2676**返回值:** 2677 2678| 类型 | 说明 | 2679| ------------------------------------------------------------ | -------------------------------------------------- | 2680| [inspector.ComponentObserver](js-apis-arkui-inspector.md#componentobserver) | 组件回调事件监听句柄,用于注册和取消注册监听回调。 | 2681 2682**示例:** 2683 2684<!--code_no_check--> 2685```ts 2686import { UIInspector } from '@kit.ArkUI'; 2687 2688let inspector: UIInspector = uiContext.getUIInspector(); 2689let listener = inspector.createComponentObserver('COMPONENT_ID'); 2690``` 2691 2692## PageInfo<sup>12+</sup> 2693Router和NavDestination等页面信息,若无对应的Router或NavDestination页面信息,则对应属性为undefined。 2694 2695**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2696 2697**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2698 2699| 名称 | 类型 | 必填 | 说明 | 2700| -------- | -------- | -------- | -------- | 2701| routerPageInfo | observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo) | 否 | Router信息。 | 2702| navDestinationInfo | observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo) | 否 | NavDestination信息。 | 2703 2704## UIObserver<sup>11+</sup> 2705 2706以下API需先使用UIContext中的[getUIObserver()](#getuiobserver11)方法获取到UIObserver对象,再通过该对象调用对应方法。 2707 2708### on('navDestinationUpdate')<sup>11+</sup> 2709 2710on(type: 'navDestinationUpdate', callback: Callback\<observer.NavDestinationInfo\>): void 2711 2712监听NavDestination组件的状态变化。 2713 2714**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2715 2716**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2717 2718**参数:** 2719 2720| 参数名 | 类型 | 必填 | 说明 | 2721| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 2722| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 | 2723| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 是 | 回调函数。返回当前的NavDestination组件状态。 | 2724 2725**示例:** 2726 2727<!--code_no_check--> 2728```ts 2729// Index.ets 2730// 演示 uiObserver.on('navDestinationUpdate', callback) 2731// uiObserver.off('navDestinationUpdate', callback) 2732 2733@Component 2734struct PageOne { 2735 build() { 2736 NavDestination() { 2737 Text("pageOne") 2738 }.title("pageOne") 2739 } 2740} 2741 2742@Entry 2743@Component 2744struct Index { 2745 private stack: NavPathStack = new NavPathStack(); 2746 2747 @Builder 2748 PageBuilder(name: string) { 2749 PageOne() 2750 } 2751 2752 aboutToAppear() { 2753 this.getUIContext().getUIObserver().on('navDestinationUpdate', (info) => { 2754 console.info('NavDestination state update', JSON.stringify(info)); 2755 }); 2756 } 2757 2758 aboutToDisappear() { 2759 this.getUIContext().getUIObserver().off('navDestinationUpdate'); 2760 } 2761 2762 build() { 2763 Column() { 2764 Navigation(this.stack) { 2765 Button("push").onClick(() => { 2766 this.stack.pushPath({ name: "pageOne" }); 2767 }) 2768 } 2769 .title("Navigation") 2770 .navDestination(this.PageBuilder) 2771 } 2772 .width('100%') 2773 .height('100%') 2774 } 2775} 2776``` 2777 2778### off('navDestinationUpdate')<sup>11+</sup> 2779 2780off(type: 'navDestinationUpdate', callback?: Callback\<observer.NavDestinationInfo\>): void 2781 2782取消监听NavDestination组件的状态变化。 2783 2784**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2785 2786**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2787 2788**参数:** 2789 2790| 参数名 | 类型 | 必填 | 说明 | 2791| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 2792| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 | 2793| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 否 | 回调函数。返回当前的NavDestination组件状态。 | 2794 2795**示例:** 2796 2797参考[uiObserver.on('navDestinationUpdate')](#onnavdestinationupdate11)示例。 2798 2799### on('navDestinationUpdate')<sup>11+</sup> 2800 2801on(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback: Callback\<observer.NavDestinationInfo\>): void 2802 2803监听NavDestination组件的状态变化。 2804 2805**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2806 2807**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2808 2809**参数:** 2810 2811| 参数名 | 类型 | 必填 | 说明 | 2812| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2813| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 | 2814| options | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | 是 | 指定监听的Navigation的id。 | 2815| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 是 | 回调函数。返回当前的NavDestination组件状态。 | 2816 2817**示例:** 2818 2819<!--code_no_check--> 2820```ts 2821// Index.ets 2822// 演示 uiObserver.on('navDestinationUpdate', navigationId, callback) 2823// uiObserver.off('navDestinationUpdate', navigationId, callback) 2824@Component 2825struct PageOne { 2826 build() { 2827 NavDestination() { 2828 Text("pageOne") 2829 }.title("pageOne") 2830 } 2831} 2832 2833@Entry 2834@Component 2835struct Index { 2836 private stack: NavPathStack = new NavPathStack(); 2837 2838 @Builder 2839 PageBuilder(name: string) { 2840 PageOne() 2841 } 2842 2843 aboutToAppear() { 2844 this.getUIContext().getUIObserver().on('navDestinationUpdate', { navigationId: "testId" }, (info) => { 2845 console.info('NavDestination state update', JSON.stringify(info)); 2846 }); 2847 } 2848 2849 aboutToDisappear() { 2850 this.getUIContext().getUIObserver().off('navDestinationUpdate', { navigationId: "testId" }); 2851 } 2852 2853 build() { 2854 Column() { 2855 Navigation(this.stack) { 2856 Button("push").onClick(() => { 2857 this.stack.pushPath({ name: "pageOne" }); 2858 }) 2859 } 2860 .id("testId") 2861 .title("Navigation") 2862 .navDestination(this.PageBuilder) 2863 } 2864 .width('100%') 2865 .height('100%') 2866 } 2867} 2868``` 2869 2870### off('navDestinationUpdate')<sup>11+</sup> 2871 2872off(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback?: Callback\<observer.NavDestinationInfo\>): void 2873 2874取消监听NavDestination组件的状态变化。 2875 2876**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2877 2878**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2879 2880**参数:** 2881 2882| 参数名 | 类型 | 必填 | 说明 | 2883| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2884| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 | 2885| options | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | 是 | 指定监听的Navigation的id。 | 2886| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 否 | 回调函数。返回当前的NavDestination组件状态。 | 2887 2888**示例:** 2889 2890参考[uiObserver.on('navDestinationUpdate')](#onnavdestinationupdate11-1)示例。 2891 2892### on('scrollEvent')<sup>12+</sup> 2893 2894on(type: 'scrollEvent', callback: Callback\<observer.ScrollEventInfo\>): void 2895 2896监听滚动事件的开始和结束。 2897 2898**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2899 2900**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2901 2902**参数:** 2903 2904| 参数名 | 类型 | 必填 | 说明 | 2905| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 2906| type | string | 是 | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 | 2907| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\> | 是 | 回调函数。返回滚动事件的信息。 | 2908 2909**示例:** 2910 2911请参考[offscrollevent示例](#offscrollevent12-1) 2912 2913### off('scrollEvent')<sup>12+</sup> 2914 2915off(type: 'scrollEvent', callback?: Callback\<observer.ScrollEventInfo\>): void 2916 2917取消监听滚动事件的开始和结束。 2918 2919**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2920 2921**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2922 2923**参数:** 2924 2925| 参数名 | 类型 | 必填 | 说明 | 2926| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 2927| type | string | 是 | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 | 2928| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\> | 否 | 回调函数。返回滚动事件的信息。 | 2929 2930**示例:** 2931 2932请参考[offscrollevent示例](#offscrollevent12-1) 2933 2934### on('scrollEvent')<sup>12+</sup> 2935 2936on(type: 'scrollEvent', options: observer.ObserverOptions, callback: Callback\<observer.ScrollEventInfo\>): void 2937 2938监听滚动事件的开始和结束。 2939 2940**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2941 2942**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2943 2944**参数:** 2945 2946| 参数名 | 类型 | 必填 | 说明 | 2947| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2948| type | string | 是 | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 | 2949| options | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是 | Observer选项,包含指定监听的滚动组件的id。 | 2950| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\> | 是 | 回调函数。返回滚动事件的信息。 | 2951 2952**示例:** 2953 2954请参考[offscrollevent示例](#offscrollevent12-1) 2955 2956### off('scrollEvent')<sup>12+</sup> 2957 2958off(type: 'scrollEvent', options: observer.ObserverOptions, callback?: Callback\<observer.ScrollEventInfo\>): void 2959 2960取消监听滚动事件的开始和结束。 2961 2962**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2963 2964**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2965 2966**参数:** 2967 2968| 参数名 | 类型 | 必填 | 说明 | 2969| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2970| type | string | 是 | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 | 2971| options | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是 | Observer选项,包含指定监听的滚动组件的id。 | 2972| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\> | 否 | 回调函数。返回滚动事件的信息。 | 2973 2974**示例:** 2975 2976```ts 2977import { UIObserver } from '@kit.ArkUI' 2978 2979@Entry 2980@Component 2981struct Index { 2982 scroller: Scroller = new Scroller() 2983 observer: UIObserver = new UIObserver() 2984 private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7] 2985 2986 build() { 2987 Row() { 2988 Column() { 2989 Scroll(this.scroller) { 2990 Column() { 2991 ForEach(this.arr, (item: number) => { 2992 Text(item.toString()) 2993 .width('90%') 2994 .height(150) 2995 .backgroundColor(0xFFFFFF) 2996 .borderRadius(15) 2997 .fontSize(16) 2998 .textAlign(TextAlign.Center) 2999 .margin({ top: 10 }) 3000 }, (item: string) => item) 3001 }.width('100%') 3002 } 3003 .id("testId") 3004 .height('80%') 3005 } 3006 .width('100%') 3007 3008 Row() { 3009 Button('UIObserver on') 3010 .onClick(() => { 3011 this.observer.on('scrollEvent', (info) => { 3012 console.info('scrollEventInfo', JSON.stringify(info)); 3013 }); 3014 }) 3015 Button('UIObserver off') 3016 .onClick(() => { 3017 this.observer.off('scrollEvent'); 3018 }) 3019 } 3020 3021 Row() { 3022 Button('UIObserverWithId on') 3023 .onClick(() => { 3024 this.observer.on('scrollEvent', { id:"testId" }, (info) => { 3025 console.info('scrollEventInfo', JSON.stringify(info)); 3026 }); 3027 }) 3028 Button('UIObserverWithId off') 3029 .onClick(() => { 3030 this.observer.off('scrollEvent', { id:"testId" }); 3031 }) 3032 } 3033 } 3034 .height('100%') 3035 } 3036} 3037``` 3038 3039### on('routerPageUpdate')<sup>11+</sup> 3040 3041on(type: 'routerPageUpdate', callback: Callback\<observer.RouterPageInfo\>): void 3042 3043监听router中page页面的状态变化。 3044 3045**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3046 3047**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3048 3049**参数:** 3050 3051| 参数名 | 类型 | 必填 | 说明 | 3052| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3053| type | string | 是 | 监听事件,固定为'routerPageUpdate',即router中page页面的状态变化。 | 3054| callback | Callback\<observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo)\> | 是 | 回调函数。携带pageInfo,返回当前的page页面状态。 | 3055 3056**示例:** 3057 3058```ts 3059import { UIContext, UIObserver } from '@kit.ArkUI'; 3060 3061let observer:UIObserver = this.getUIContext().getUIObserver(); 3062observer.on('routerPageUpdate', (info) => { 3063 console.info('RouterPage state updated, called by ' + `${info.name}`); 3064}); 3065``` 3066 3067### off('routerPageUpdate')<sup>11+</sup> 3068 3069off(type: 'routerPageUpdate', callback?: Callback\<observer.RouterPageInfo\>): void 3070 3071取消监听router中page页面的状态变化。 3072 3073**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3074 3075**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3076 3077**参数:** 3078 3079| 参数名 | 类型 | 必填 | 说明 | 3080| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3081| type | string | 是 | 监听事件,固定为'routerPageUpdate',即router中page页面的状态变化。 | 3082| callback | Callback\<observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo)\> | 否 | 需要被注销的回调函数。 | 3083 3084**示例:** 3085 3086```ts 3087import { UIContext, UIObserver } from '@kit.ArkUI'; 3088 3089let observer:UIObserver = this.getUIContext().getUIObserver(); 3090function callBackFunc(info:observer.RouterPageInfo) {}; 3091// callBackFunc is defined and used before 3092observer.off('routerPageUpdate', callBackFunc); 3093``` 3094 3095### on('densityUpdate')<sup>12+</sup> 3096 3097on(type: 'densityUpdate', callback: Callback\<observer.DensityInfo\>): void 3098 3099监听屏幕像素密度变化。 3100 3101**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3102 3103**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3104 3105**参数:** 3106 3107| 参数名 | 类型 | 必填 | 说明 | 3108| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3109| type | string | 是 | 监听事件,固定为'densityUpdate',即屏幕像素密度变化。 | 3110| callback | Callback\<observer.[DensityInfo](./js-apis-arkui-observer.md#densityinfo12)\> | 是 | 回调函数。携带densityInfo,返回变化后的屏幕像素密度。 | 3111 3112```ts 3113import { uiObserver } from '@kit.ArkUI'; 3114 3115@Entry 3116@Component 3117struct Index { 3118 @State density: number = 0; 3119 @State message: string = '未注册监听' 3120 3121 densityUpdateCallback = (info: uiObserver.DensityInfo) => { 3122 this.density = info.density; 3123 this.message = '变化后的DPI:' + this.density.toString(); 3124 } 3125 3126 build() { 3127 Column() { 3128 Text(this.message) 3129 .fontSize(24) 3130 .fontWeight(FontWeight.Bold) 3131 Button('注册屏幕像素密度变化监听') 3132 .onClick(() => { 3133 this.message = '已注册监听' 3134 this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback); 3135 }) 3136 } 3137 } 3138} 3139``` 3140 3141### off('densityUpdate')<sup>12+</sup> 3142 3143off(type: 'densityUpdate', callback?: Callback\<observer.DensityInfo\>): void 3144 3145取消监听屏幕像素密度的变化。 3146 3147**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3148 3149**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3150 3151**参数:** 3152 3153| 参数名 | 类型 | 必填 | 说明 | 3154| -------- | -------------------------------------------------------------------- | ---- | -------------------------------------------------------------------------------------------- | 3155| type | string | 是 | 监听事件,固定为'densityUpdate',即屏幕像素密度变化。 | 3156| callback | Callback\<observer.[DensityInfo](./js-apis-arkui-observer.md#densityinfo12)\> | 否 | 需要被注销的回调函数。若不指定具体的回调函数,则注销该UIContext下所有densityUpdate事件监听。 | 3157 3158```ts 3159import { uiObserver } from '@kit.ArkUI'; 3160 3161@Entry 3162@Component 3163struct Index { 3164 @State density: number = 0; 3165 @State message: string = '未注册监听' 3166 3167 densityUpdateCallback = (info: uiObserver.DensityInfo) => { 3168 this.density = info.density; 3169 this.message = '变化后的DPI:' + this.density.toString(); 3170 } 3171 3172 build() { 3173 Column() { 3174 Text(this.message) 3175 .fontSize(24) 3176 .fontWeight(FontWeight.Bold) 3177 Button('注册屏幕像素密度变化监听') 3178 .margin({ bottom: 10 }) 3179 .onClick(() => { 3180 this.message = '已注册监听' 3181 this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback); 3182 }) 3183 Button('解除注册屏幕像素密度变化监听') 3184 .onClick(() => { 3185 this.message = '未注册监听' 3186 this.getUIContext().getUIObserver().off('densityUpdate', this.densityUpdateCallback); 3187 }) 3188 } 3189 } 3190} 3191``` 3192 3193### on('willDraw')<sup>12+</sup> 3194 3195on(type: 'willDraw', callback: Callback\<void\>): void 3196 3197监听每一帧绘制指令下发情况。 3198 3199**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3200 3201**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3202 3203**参数:** 3204 3205| 参数名 | 类型 | 必填 | 说明 | 3206| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3207| type | string | 是 | 监听事件,固定为'willDraw',即是否将要绘制。 | 3208| callback | Callback\<void\> | 是 | 回调函数。 | 3209 3210```ts 3211import { uiObserver } from '@kit.ArkUI'; 3212 3213@Entry 3214@Component 3215struct Index { 3216 willDrawCallback = () => { 3217 console.info("willDraw指令下发"); 3218 } 3219 build() { 3220 Column() { 3221 Button('注册绘制指令下发监听') 3222 .onClick(() => { 3223 this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback); 3224 }) 3225 } 3226 } 3227} 3228``` 3229 3230### off('willDraw')<sup>12+</sup> 3231 3232off(type: 'willDraw', callback?: Callback\<void\>): void 3233 3234取消监听每一帧绘制指令下发情况。 3235 3236**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3237 3238**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3239 3240**参数:** 3241 3242| 参数名 | 类型 | 必填 | 说明 | 3243| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3244| type | string | 是 | 监听事件,固定为'willDraw',即是否将要绘制。 | 3245| callback | Callback\<void\> | 否 | 需要被注销的回调函数。 | 3246 3247```ts 3248import { uiObserver } from '@kit.ArkUI'; 3249 3250@Entry 3251@Component 3252struct Index { 3253 willDrawCallback = () => { 3254 console.info("willDraw指令下发") 3255 } 3256 3257 build() { 3258 Column() { 3259 Button('注册绘制指令下发监听') 3260 .margin({ bottom: 10 }) 3261 .onClick(() => { 3262 this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback); 3263 }) 3264 Button('解除注册绘制指令下发监听') 3265 .onClick(() => { 3266 this.getUIContext().getUIObserver().off('willDraw', this.willDrawCallback); 3267 }) 3268 } 3269 } 3270} 3271``` 3272 3273### on('didLayout')<sup>12+</sup> 3274 3275on(type: 'didLayout', callback: Callback\<void\>): void 3276 3277监听每一帧布局完成情况。 3278 3279**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3280 3281**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3282 3283**参数:** 3284 3285| 参数名 | 类型 | 必填 | 说明 | 3286| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3287| type | string | 是 | 监听事件,固定为'didLayout',即是否布局完成。 | 3288| callback | Callback\<void\> | 是 | 回调函数。 | 3289 3290```ts 3291import { uiObserver } from '@kit.ArkUI'; 3292 3293@Entry 3294@Component 3295struct Index { 3296 didLayoutCallback = () => { 3297 console.info("layout布局完成"); 3298 } 3299 build() { 3300 Column() { 3301 Button('注册布局完成监听') 3302 .onClick(() => { 3303 this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback); 3304 }) 3305 } 3306 } 3307} 3308``` 3309 3310### off('didLayout')<sup>12+</sup> 3311 3312off(type: 'didLayout', callback?: Callback\<void\>): void 3313 3314取消监听每一帧布局完成情况。 3315 3316**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3317 3318**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3319 3320**参数:** 3321 3322| 参数名 | 类型 | 必填 | 说明 | 3323| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3324| type | string | 是 | 监听事件,固定为'didLayout',即是否将要绘制。 | 3325| callback | Callback\<void\> | 否 | 需要被注销的回调函数。 | 3326 3327```ts 3328import { uiObserver } from '@kit.ArkUI'; 3329 3330@Entry 3331@Component 3332struct Index { 3333 didLayoutCallback = () => { 3334 console.info("layout布局完成") 3335 } 3336 3337 build() { 3338 Column() { 3339 Button('注册布局完成监听') 3340 .margin({ bottom: 10 }) 3341 .onClick(() => { 3342 this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback); 3343 }) 3344 Button('解除注册注册布局完成监听') 3345 .onClick(() => { 3346 this.getUIContext().getUIObserver().off('didLayout', this.didLayoutCallback); 3347 }) 3348 } 3349 } 3350} 3351``` 3352 3353### on('navDestinationSwitch')<sup>12+</sup> 3354 3355on(type: 'navDestinationSwitch', callback: Callback\<observer.NavDestinationSwitchInfo\>): void 3356 3357监听Navigation的页面切换事件。 3358 3359**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3360 3361**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3362 3363**参数:** 3364 3365| 参数名 | 类型 | 必填 | 说明 | 3366| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3367| type | string | 是 | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 | 3368| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\> | 是 | 回调函数。携带NavDestinationSwitchInfo,返回页面切换事件的信息。 | 3369 3370**示例:** 3371 3372```ts 3373// Index.ets 3374// 演示 UIObserver.on('navDestinationSwitch', callback) 3375// UIObserver.off('navDestinationSwitch', callback) 3376import { uiObserver } from '@kit.ArkUI'; 3377 3378@Component 3379struct PageOne { 3380 build() { 3381 NavDestination() { 3382 Text("pageOne") 3383 }.title("pageOne") 3384 } 3385} 3386 3387function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) { 3388 console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`) 3389} 3390 3391@Entry 3392@Component 3393struct Index { 3394 private stack: NavPathStack = new NavPathStack(); 3395 3396 @Builder 3397 PageBuilder(name: string) { 3398 PageOne() 3399 } 3400 3401 aboutToAppear() { 3402 let obs = this.getUIContext().getUIObserver(); 3403 obs.on('navDestinationSwitch', callBackFunc); 3404 } 3405 3406 aboutToDisappear() { 3407 let obs = this.getUIContext().getUIObserver(); 3408 obs.off('navDestinationSwitch', callBackFunc); 3409 } 3410 3411 build() { 3412 Column() { 3413 Navigation(this.stack) { 3414 Button("push").onClick(() => { 3415 this.stack.pushPath({name: "pageOne"}); 3416 }) 3417 } 3418 .title("Navigation") 3419 .navDestination(this.PageBuilder) 3420 } 3421 .width('100%') 3422 .height('100%') 3423 } 3424} 3425``` 3426 3427### off('navDestinationSwitch')<sup>12+</sup> 3428 3429off(type: 'navDestinationSwitch', callback?: Callback\<observer.NavDestinationSwitchInfo\>): void 3430 3431取消监听Navigation的页面切换事件。 3432 3433**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3434 3435**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3436 3437**参数:** 3438 3439| 参数名 | 类型 | 必填 | 说明 | 3440| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3441| type | string | 是 | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 | 3442| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\> | 否 | 需要被注销的回调函数。 | 3443 3444**示例代码参考上述UIObserver.on('navDestinationSwitch')接口的示例代码** 3445 3446### on('navDestinationSwitch')<sup>12+</sup> 3447 3448on(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback: Callback\<observer.NavDestinationSwitchInfo\>): void 3449 3450监听Navigation的页面切换事件。 3451 3452**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3453 3454**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3455 3456**参数:** 3457 3458| 参数名 | 类型 | 必填 | 说明 | 3459| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3460| type | string | 是 | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 | 3461| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12) | 是 | 监听选项。 | 3462| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\> | 是 | 回调函数。携带NavDestinationSwitchInfo,返回页面切换事件的信息。 | 3463 3464**示例:** 3465 3466```ts 3467// Index.ets 3468// 演示 UIObserver.on('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback) 3469// UIObserver.off('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback) 3470import { uiObserver } from '@kit.ArkUI'; 3471 3472@Component 3473struct PageOne { 3474 build() { 3475 NavDestination() { 3476 Text("pageOne") 3477 }.title("pageOne") 3478 } 3479} 3480 3481function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) { 3482 console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`) 3483} 3484 3485@Entry 3486@Component 3487struct Index { 3488 private stack: NavPathStack = new NavPathStack(); 3489 3490 @Builder 3491 PageBuilder(name: string) { 3492 PageOne() 3493 } 3494 3495 aboutToAppear() { 3496 let obs = this.getUIContext().getUIObserver(); 3497 obs.on('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc) 3498 } 3499 3500 aboutToDisappear() { 3501 let obs = this.getUIContext().getUIObserver(); 3502 obs.off('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc) 3503 } 3504 3505 build() { 3506 Column() { 3507 Navigation(this.stack) { 3508 Button("push").onClick(() => { 3509 this.stack.pushPath({name: "pageOne"}); 3510 }) 3511 } 3512 .id("myNavId") 3513 .title("Navigation") 3514 .navDestination(this.PageBuilder) 3515 } 3516 .width('100%') 3517 .height('100%') 3518 } 3519} 3520``` 3521 3522### off('navDestinationSwitch')<sup>12+</sup> 3523 3524off(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback?: Callback\<observer.NavDestinationSwitchInfo\>): void 3525 3526取消监听Navigation的页面切换事件。 3527 3528**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3529 3530**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3531 3532**参数:** 3533 3534| 参数名 | 类型 | 必填 | 说明 | 3535| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3536| type | string | 是 | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 | 3537| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12) | 是 | 监听选项。 | 3538| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\> | 否 | 需要被注销的回调函数。 | 3539 3540**示例代码参考上述UIObserver.on('navDestinationSwitch')接口的示例代码** 3541 3542### on('willClick')<sup>12+</sup> 3543 3544on(type: 'willClick', callback: GestureEventListenerCallback): void 3545 3546监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3547 3548**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3549 3550**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3551 3552**参数:** 3553 3554| 参数名 | 类型 | 必填 | 说明 | 3555| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3556| type | string | 是 | 监听事件,固定为'willClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发前触发。 | 3557| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 是 | 回调函数。可以获得点击事件的GestureEvent和组件的FrameNode。 | 3558 3559**示例:** 3560 3561```ts 3562// 在页面Component中使用 3563import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3564 3565// callback是开发者定义的监听回调函数 3566let callback = (event: GestureEvent, frameNode?: FrameNode) => {}; 3567let observer: UIObserver = this.getUIContext().getUIObserver(); 3568observer.on('willClick', callback); 3569``` 3570 3571### off('willClick')<sup>12+</sup> 3572 3573off(type: 'willClick', callback?: GestureEventListenerCallback): void 3574 3575取消监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3576 3577**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3578 3579**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3580 3581**参数:** 3582 3583| 参数名 | 类型 | 必填 | 说明 | 3584| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | 3585| type | string | 是 | 监听事件,固定为'willClick',即点击事件指令下发情况。 | 3586| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 否 | 需要被注销的回调函数。 | 3587 3588**示例:** 3589 3590```ts 3591// 在页面Component中使用 3592import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3593 3594// callback是开发者定义的监听回调函数 3595let callback = (event: GestureEvent, frameNode?: FrameNode) => {}; 3596let observer: UIObserver = this.getUIContext().getUIObserver(); 3597observer.off('willClick', callback); 3598``` 3599 3600### on('didClick')<sup>12+</sup> 3601 3602on(type: 'didClick', callback: GestureEventListenerCallback): void 3603 3604监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3605 3606**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3607 3608**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3609 3610**参数:** 3611 3612| 参数名 | 类型 | 必填 | 说明 | 3613| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3614| type | string | 是 | 监听事件,固定为'didClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发后触发。 | 3615| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 是 | 回调函数。可以获得点击事件的GestureEvent和组件的FrameNode。 | 3616 3617**示例:** 3618 3619```ts 3620// 在页面Component中使用 3621import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3622 3623// callback是开发者定义的监听回调函数 3624let callback = (event: GestureEvent, frameNode?: FrameNode) => {}; 3625let observer: UIObserver = this.getUIContext().getUIObserver(); 3626observer.on('didClick', callback); 3627``` 3628 3629### off('didClick')<sup>12+</sup> 3630 3631off(type: 'didClick', callback?: GestureEventListenerCallback): void 3632 3633取消监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3634 3635**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3636 3637**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3638 3639**参数:** 3640 3641| 参数名 | 类型 | 必填 | 说明 | 3642| -------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------- | 3643| type | string | 是 | 监听事件,固定为'didClick',即点击事件指令下发情况。 | 3644| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 否 | 需要被注销的回调函数。 | 3645 3646**示例:** 3647 3648```ts 3649// 在页面Component中使用 3650import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3651 3652// callback是开发者定义的监听回调函数 3653let callback = (event: GestureEvent, frameNode?: FrameNode) => {}; 3654let observer: UIObserver = this.getUIContext().getUIObserver(); 3655observer.off('didClick', callback); 3656``` 3657 3658### on('willClick')<sup>12+</sup> 3659 3660on(type: 'willClick', callback: ClickEventListenerCallback): void 3661 3662监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3663 3664**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3665 3666**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3667 3668**参数:** 3669 3670| 参数名 | 类型 | 必填 | 说明 | 3671| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | 3672| type | string | 是 | 监听事件,固定为'willClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发前触发。 | 3673| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 是 | 回调函数。可以获得点击事件的ClickEvent和组件的FrameNode。 | 3674 3675**示例:** 3676 3677```ts 3678// 在页面Component中使用 3679import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3680 3681// callback是开发者定义的监听回调函数 3682let callback = (event: ClickEvent, frameNode?: FrameNode) => {}; 3683let observer: UIObserver = this.getUIContext().getUIObserver(); 3684observer.on('willClick', callback); 3685``` 3686 3687### off('willClick')<sup>12+</sup> 3688 3689off(type: 'willClick', callback?: ClickEventListenerCallback): void 3690 3691取消监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3692 3693**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3694 3695**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3696 3697**参数:** 3698 3699| 参数名 | 类型 | 必填 | 说明 | 3700| -------- | ----------------------------------------------------------- | ---- | ----------------------------------------------------- | 3701| type | string | 是 | 监听事件,固定为'willClick',即点击事件指令下发情况。 | 3702| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 否 | 需要被注销的回调函数。 | 3703 3704**示例:** 3705 3706```ts 3707// 在页面Component中使用 3708import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3709 3710// callback是开发者定义的监听回调函数 3711let callback = (event: ClickEvent, frameNode?: FrameNode) => {}; 3712let observer: UIObserver = this.getUIContext().getUIObserver(); 3713observer.off('willClick', callback); 3714``` 3715 3716### on('didClick')<sup>12+</sup> 3717 3718on(type: 'didClick', callback: ClickEventListenerCallback): void 3719 3720监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3721 3722**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3723 3724**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3725 3726**参数:** 3727 3728| 参数名 | 类型 | 必填 | 说明 | 3729| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | 3730| type | string | 是 | 监听事件,固定为'didClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发后触发。 | 3731| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 是 | 回调函数。可以获得点击事件的ClickEvent和组件的FrameNode。 | 3732 3733**示例:** 3734 3735```ts 3736// 在页面Component中使用 3737import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3738 3739// callback是开发者定义的监听回调函数 3740let callback = (event: ClickEvent, frameNode?: FrameNode) => {}; 3741let observer: UIObserver = this.getUIContext().getUIObserver(); 3742observer.on('didClick', callback); 3743``` 3744 3745### off('didClick')<sup>12+</sup> 3746 3747off(type: 'didClick', callback?: ClickEventListenerCallback): void 3748 3749取消监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3750 3751**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3752 3753**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3754 3755**参数:** 3756 3757| 参数名 | 类型 | 必填 | 说明 | 3758| -------- | ----------------------------------------------------------- | ---- | ---------------------------------------------------- | 3759| type | string | 是 | 监听事件,固定为'didClick',即点击事件指令下发情况。 | 3760| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 否 | 需要被注销的回调函数。 | 3761 3762**示例:** 3763 3764```ts 3765// 在页面Component中使用 3766import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3767 3768// callback是开发者定义的监听回调函数 3769let callback = (event: ClickEvent, frameNode?: FrameNode) => {}; 3770let observer: UIObserver = this.getUIContext().getUIObserver(); 3771observer.off('didClick', callback); 3772``` 3773 3774### on('tabContentUpdate')<sup>12+</sup> 3775 3776on(type: 'tabContentUpdate', callback: Callback\<observer.TabContentInfo\>): void 3777 3778监听TabContent页面的切换事件。 3779 3780**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3781 3782**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3783 3784**参数:** 3785 3786| 参数名 | 类型 | 必填 | 说明 | 3787| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3788| type | string | 是 | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 | 3789| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | 是 | 回调函数。携带TabContentInfo,返回TabContent页面切换事件的信息。 | 3790 3791**示例:** 3792 3793```ts 3794import { uiObserver } from '@kit.ArkUI'; 3795 3796function callbackFunc(info: uiObserver.TabContentInfo) { 3797 console.info('tabContentUpdate', JSON.stringify(info)); 3798} 3799 3800@Entry 3801@Component 3802struct TabsExample { 3803 3804 aboutToAppear(): void { 3805 let observer = this.getUIContext().getUIObserver(); 3806 observer.on('tabContentUpdate', callbackFunc); 3807 } 3808 3809 aboutToDisappear(): void { 3810 let observer = this.getUIContext().getUIObserver(); 3811 observer.off('tabContentUpdate', callbackFunc); 3812 } 3813 3814 build() { 3815 Column() { 3816 Tabs() { 3817 TabContent() { 3818 Column().width('100%').height('100%').backgroundColor('#00CB87') 3819 }.tabBar('green').id('tabContentId0') 3820 3821 TabContent() { 3822 Column().width('100%').height('100%').backgroundColor('#007DFF') 3823 }.tabBar('blue').id('tabContentId1') 3824 3825 TabContent() { 3826 Column().width('100%').height('100%').backgroundColor('#FFBF00') 3827 }.tabBar('yellow').id('tabContentId2') 3828 3829 TabContent() { 3830 Column().width('100%').height('100%').backgroundColor('#E67C92') 3831 }.tabBar('pink').id('tabContentId3') 3832 } 3833 .width(360) 3834 .height(296) 3835 .backgroundColor('#F1F3F5') 3836 .id('tabsId') 3837 }.width('100%') 3838 } 3839} 3840``` 3841 3842### off('tabContentUpdate')<sup>12+</sup> 3843 3844off(type: 'tabContentUpdate', callback?: Callback\<observer.TabContentInfo\>): void 3845 3846取消监听TabContent页面的切换事件。 3847 3848**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3849 3850**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3851 3852**参数:** 3853 3854| 参数名 | 类型 | 必填 | 说明 | 3855| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3856| type | string | 是 | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 | 3857| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | 否 | 需要被注销的回调函数。 | 3858 3859**示例:** 3860 3861参考[on('tabContentUpdate')](#ontabcontentupdate12)接口示例。 3862 3863### on('tabContentUpdate')<sup>12+</sup> 3864 3865on(type: 'tabContentUpdate', options: observer.ObserverOptions, callback: Callback\<observer.TabContentInfo\>): void 3866 3867监听TabContent页面的切换事件。 3868 3869**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3870 3871**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3872 3873**参数:** 3874 3875| 参数名 | 类型 | 必填 | 说明 | 3876| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3877| type | string | 是 | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 | 3878| options | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是 | 指定监听的Tabs组件的id。 | 3879| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | 是 | 回调函数。携带TabContentInfo,返回TabContent页面切换事件的信息。 | 3880 3881**示例:** 3882 3883```ts 3884import { uiObserver } from '@kit.ArkUI'; 3885 3886function callbackFunc(info: uiObserver.TabContentInfo) { 3887 console.info('tabContentUpdate', JSON.stringify(info)); 3888} 3889 3890@Entry 3891@Component 3892struct TabsExample { 3893 3894 aboutToAppear(): void { 3895 let observer = this.getUIContext().getUIObserver(); 3896 observer.on('tabContentUpdate', { id: 'tabsId' }, callbackFunc); 3897 } 3898 3899 aboutToDisappear(): void { 3900 let observer = this.getUIContext().getUIObserver(); 3901 observer.off('tabContentUpdate', { id: 'tabsId' }, callbackFunc); 3902 } 3903 3904 build() { 3905 Column() { 3906 Tabs() { 3907 TabContent() { 3908 Column().width('100%').height('100%').backgroundColor('#00CB87') 3909 }.tabBar('green').id('tabContentId0') 3910 3911 TabContent() { 3912 Column().width('100%').height('100%').backgroundColor('#007DFF') 3913 }.tabBar('blue').id('tabContentId1') 3914 3915 TabContent() { 3916 Column().width('100%').height('100%').backgroundColor('#FFBF00') 3917 }.tabBar('yellow').id('tabContentId2') 3918 3919 TabContent() { 3920 Column().width('100%').height('100%').backgroundColor('#E67C92') 3921 }.tabBar('pink').id('tabContentId3') 3922 } 3923 .width(360) 3924 .height(296) 3925 .backgroundColor('#F1F3F5') 3926 .id('tabsId') 3927 }.width('100%') 3928 } 3929} 3930``` 3931 3932### off('tabContentUpdate')<sup>12+</sup> 3933 3934off(type: 'tabContentUpdate', options: observer.ObserverOptions, callback?: Callback\<observer.TabContentInfo\>): void 3935 3936取消监听TabContent页面的切换事件。 3937 3938**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3939 3940**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3941 3942**参数:** 3943 3944| 参数名 | 类型 | 必填 | 说明 | 3945| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3946| type | string | 是 | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 | 3947| options | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是 | 指定监听的Tabs组件的id。 | 3948| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | 否 | 需要被注销的回调函数。 | 3949 3950**示例:** 3951 3952参考[on('tabContentUpdate')](#ontabcontentupdate12-1)接口示例。 3953 3954## GestureEventListenerCallback<sup>12+</sup> 3955type GestureEventListenerCallback = (event: GestureEvent, node?: FrameNode) => void 3956 3957ArkTS GestureEvent事件监听函数类型。 3958 3959**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3960 3961**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3962 3963**参数:** 3964 3965| 参数名 | 类型 | 必填 | 说明 | 3966| ------- | ------ | ---- | --------------------------- | 3967| event | [GestureEvent](../apis-arkui/arkui-ts/ts-gesture-settings.md#gestureevent对象说明) | 是 | 触发事件监听的手势事件的相关信息。 | 3968| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | 否 | 触发事件监听的手势事件所绑定的组件。 | 3969 3970## ClickEventListenerCallback<sup>12+</sup> 3971type ClickEventListenerCallback = (event: ClickEvent, node?: FrameNode) => void 3972 3973ArkTS GestureEvent事件监听函数类型。 3974 3975**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3976 3977**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3978 3979**参数:** 3980 3981| 参数名 | 类型 | 必填 | 说明 | 3982| ------- | ------ | ---- | --------------------------- | 3983| event | [ClickEvent](../apis-arkui/arkui-ts/ts-universal-events-click.md#clickevent对象说明) | 是 | 触发事件监听的点击事件的相关信息。 | 3984| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | 否 | 触发事件监听的点击事件所绑定的组件。 | 3985 3986## MediaQuery 3987 3988以下API需先使用UIContext中的[getMediaQuery()](#getmediaquery)方法获取到MediaQuery对象,再通过该对象调用对应方法。 3989 3990### matchMediaSync 3991 3992matchMediaSync(condition: string): mediaQuery.MediaQueryListener 3993 3994设置媒体查询的查询条件,并返回对应的监听句柄。 3995 3996**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 3997 3998**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3999 4000**参数:** 4001 4002| 参数名 | 类型 | 必填 | 说明 | 4003| --------- | ------ | ---- | ---------------------------------------- | 4004| condition | string | 是 | 媒体事件的匹配条件,具体可参考[媒体查询语法规则](../../ui/arkts-layout-development-media-query.md#语法规则)。 | 4005 4006**返回值:** 4007 4008| 类型 | 说明 | 4009| ------------------------------------------------------------ | -------------------------------------------- | 4010| [mediaQuery.MediaQueryListener](js-apis-mediaquery.md#mediaquerylistener) | 媒体事件监听句柄,用于注册和去注册监听回调。 | 4011 4012**示例:** 4013 4014<!--code_no_check--> 4015```ts 4016import { MediaQuery } from '@kit.ArkUI'; 4017 4018let mediaquery: MediaQuery = uiContext.getMediaQuery(); 4019let listener = mediaquery.matchMediaSync('(orientation: landscape)'); //监听横屏事件 4020``` 4021 4022## Router 4023 4024以下API需先使用UIContext中的[getRouter()](#getrouter)方法获取到Router对象,再通过该对象调用对应方法。 4025 4026### pushUrl 4027 4028pushUrl(options: router.RouterOptions): Promise<void> 4029 4030跳转到应用内的指定页面,通过Promise获取跳转异常的返回结果。 4031 4032**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4033 4034**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4035 4036**参数:** 4037 4038| 参数名 | 类型 | 必填 | 说明 | 4039| ------- | ---------------------------------------- | ---- | --------- | 4040| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 | 4041 4042**返回值:** 4043 4044| 类型 | 说明 | 4045| ------------------- | ------- | 4046| Promise<void> | 异常返回结果。 | 4047 4048**错误码:** 4049 4050以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4051 4052| 错误码ID | 错误信息 | 4053| ------ | ---------------------------------- | 4054| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4055| 100001 | Internal error. | 4056| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. | 4057| 100003 | Page stack error. Too many pages are pushed. | 4058 4059**示例:** 4060 4061```ts 4062import { BusinessError } from '@kit.BasicServicesKit' 4063 4064@Entry 4065@Component 4066struct Index { 4067 async routePage() { 4068 this.getUIContext().getRouter().pushUrl({ 4069 url: 'pages/routerpage2', 4070 params: { 4071 data1: 'message', 4072 data2: { 4073 data3: [123, 456, 789] 4074 } 4075 } 4076 }) 4077 .then(() => { 4078 console.info('succeeded') 4079 }) 4080 .catch((error: BusinessError) => { 4081 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4082 }) 4083 } 4084 4085 build() { 4086 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4087 Button() { 4088 Text('next page') 4089 .fontSize(25) 4090 .fontWeight(FontWeight.Bold) 4091 }.type(ButtonType.Capsule) 4092 .margin({ top: 20 }) 4093 .backgroundColor('#ccc') 4094 .onClick(() => { 4095 this.routePage() 4096 }) 4097 } 4098 .width('100%') 4099 .height('100%') 4100 } 4101} 4102``` 4103 4104### pushUrl 4105 4106pushUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void 4107 4108跳转到应用内的指定页面。 4109 4110**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4111 4112**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4113 4114**参数:** 4115 4116| 参数名 | 类型 | 必填 | 说明 | 4117| -------- | ---------------------------------------- | ---- | --------- | 4118| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 | 4119| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 4120 4121**错误码:** 4122 4123以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4124 4125| 错误码ID | 错误信息 | 4126| ------ | ---------------------------------- | 4127| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4128| 100001 | Internal error. | 4129| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. | 4130| 100003 | Page stack error. Too many pages are pushed. | 4131 4132**示例:** 4133 4134```ts 4135import { BusinessError } from '@kit.BasicServicesKit' 4136 4137@Entry 4138@Component 4139struct Index { 4140 async routePage() { 4141 this.getUIContext().getRouter().pushUrl({ 4142 url: 'pages/routerpage2', 4143 params: { 4144 data1: 'message', 4145 data2: { 4146 data3: [123, 456, 789] 4147 } 4148 } 4149 }, (err: Error) => { 4150 if (err) { 4151 let message = (err as BusinessError).message; 4152 let code = (err as BusinessError).code; 4153 console.error(`pushUrl failed, code is ${code}, message is ${message}`); 4154 return; 4155 } 4156 console.info('pushUrl success'); 4157 }) 4158 } 4159 4160 build() { 4161 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4162 Button() { 4163 Text('next page') 4164 .fontSize(25) 4165 .fontWeight(FontWeight.Bold) 4166 }.type(ButtonType.Capsule) 4167 .margin({ top: 20 }) 4168 .backgroundColor('#ccc') 4169 .onClick(() => { 4170 this.routePage() 4171 }) 4172 } 4173 .width('100%') 4174 .height('100%') 4175 } 4176} 4177``` 4178 4179### pushUrl 4180 4181pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void> 4182 4183跳转到应用内的指定页面,通过Promise获取跳转异常的返回结果。 4184 4185**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4186 4187**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4188 4189**参数:** 4190 4191| 参数名 | 类型 | 必填 | 说明 | 4192| ------- | ---------------------------------------- | ---- | ---------- | 4193| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 | 4194| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 4195 4196**返回值:** 4197 4198| 类型 | 说明 | 4199| ------------------- | ------- | 4200| Promise<void> | 异常返回结果。 | 4201 4202**错误码:** 4203 4204以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4205 4206| 错误码ID | 错误信息 | 4207| ------ | ---------------------------------- | 4208| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4209| 100001 | Internal error. | 4210| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. | 4211| 100003 | Page stack error. Too many pages are pushed. | 4212 4213**示例:** 4214 4215```ts 4216import { router } from '@kit.ArkUI'; 4217import { BusinessError } from '@kit.BasicServicesKit' 4218 4219class RouterTmp { 4220 Standard: router.RouterMode = router.RouterMode.Standard 4221} 4222 4223let rtm: RouterTmp = new RouterTmp() 4224 4225@Entry 4226@Component 4227struct Index { 4228 async routePage() { 4229 this.getUIContext().getRouter().pushUrl({ 4230 url: 'pages/routerpage2', 4231 params: { 4232 data1: 'message', 4233 data2: { 4234 data3: [123, 456, 789] 4235 } 4236 } 4237 }, rtm.Standard) 4238 .then(() => { 4239 console.info('succeeded') 4240 }) 4241 .catch((error: BusinessError) => { 4242 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4243 }) 4244 } 4245 4246 build() { 4247 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4248 Button() { 4249 Text('next page') 4250 .fontSize(25) 4251 .fontWeight(FontWeight.Bold) 4252 }.type(ButtonType.Capsule) 4253 .margin({ top: 20 }) 4254 .backgroundColor('#ccc') 4255 .onClick(() => { 4256 this.routePage() 4257 }) 4258 } 4259 .width('100%') 4260 .height('100%') 4261 } 4262} 4263``` 4264 4265### pushUrl 4266 4267pushUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 4268 4269跳转到应用内的指定页面。 4270 4271**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4272 4273**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4274 4275**参数:** 4276 4277| 参数名 | 类型 | 必填 | 说明 | 4278| -------- | ---------------------------------------- | ---- | ---------- | 4279| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 | 4280| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 4281| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 4282 4283**错误码:** 4284 4285以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4286 4287| 错误码ID | 错误信息 | 4288| ------ | ---------------------------------- | 4289| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4290| 100001 | Internal error. | 4291| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. | 4292| 100003 | Page stack error. Too many pages are pushed. | 4293 4294**示例:** 4295 4296```ts 4297import { router } from '@kit.ArkUI'; 4298import { BusinessError } from '@kit.BasicServicesKit' 4299 4300class RouterTmp { 4301 Standard: router.RouterMode = router.RouterMode.Standard 4302} 4303 4304let rtm: RouterTmp = new RouterTmp() 4305 4306@Entry 4307@Component 4308struct Index { 4309 async routePage() { 4310 this.getUIContext().getRouter().pushUrl({ 4311 url: 'pages/routerpage2', 4312 params: { 4313 data1: 'message', 4314 data2: { 4315 data3: [123, 456, 789] 4316 } 4317 } 4318 }, rtm.Standard, (err) => { 4319 if (err) { 4320 let message = (err as BusinessError).message; 4321 let code = (err as BusinessError).code; 4322 console.error(`pushUrl failed, code is ${code}, message is ${message}`); 4323 return; 4324 } 4325 console.info('pushUrl success'); 4326 }) 4327 } 4328 4329 build() { 4330 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4331 Button() { 4332 Text('next page') 4333 .fontSize(25) 4334 .fontWeight(FontWeight.Bold) 4335 }.type(ButtonType.Capsule) 4336 .margin({ top: 20 }) 4337 .backgroundColor('#ccc') 4338 .onClick(() => { 4339 this.routePage() 4340 }) 4341 } 4342 .width('100%') 4343 .height('100%') 4344 } 4345} 4346``` 4347 4348### replaceUrl 4349 4350replaceUrl(options: router.RouterOptions): Promise<void> 4351 4352用应用内的某个页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回的结果。 4353 4354**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4355 4356**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4357 4358**参数:** 4359 4360| 参数名 | 类型 | 必填 | 说明 | 4361| ------- | ---------------------------------------- | ---- | --------- | 4362| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 | 4363 4364**返回值:** 4365 4366| 类型 | 说明 | 4367| ------------------- | ------- | 4368| Promise<void> | 异常返回结果。 | 4369 4370**错误码:** 4371 4372以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4373 4374| 错误码ID | 错误信息 | 4375| ------ | ---------------------------------------- | 4376| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4377| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 4378| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. | 4379 4380**示例:** 4381 4382```ts 4383import { BusinessError } from '@kit.BasicServicesKit' 4384 4385@Entry 4386@Component 4387struct Index { 4388 async routePage() { 4389 this.getUIContext().getRouter().replaceUrl({ 4390 url: 'pages/detail', 4391 params: { 4392 data1: 'message' 4393 } 4394 }) 4395 .then(() => { 4396 console.info('succeeded') 4397 }) 4398 .catch((error: BusinessError) => { 4399 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4400 }) 4401 } 4402 4403 build() { 4404 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4405 Button() { 4406 Text('next page') 4407 .fontSize(25) 4408 .fontWeight(FontWeight.Bold) 4409 }.type(ButtonType.Capsule) 4410 .margin({ top: 20 }) 4411 .backgroundColor('#ccc') 4412 .onClick(() => { 4413 this.routePage() 4414 }) 4415 } 4416 .width('100%') 4417 .height('100%') 4418 } 4419} 4420``` 4421 4422### replaceUrl 4423 4424replaceUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void 4425 4426用应用内的某个页面替换当前页面,并销毁被替换的页面。 4427 4428**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4429 4430**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4431 4432**参数:** 4433 4434| 参数名 | 类型 | 必填 | 说明 | 4435| -------- | ---------------------------------------- | ---- | --------- | 4436| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 | 4437| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 4438 4439**错误码:** 4440 4441以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4442 4443| 错误码ID | 错误信息 | 4444| ------ | ---------------------------------------- | 4445| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4446| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 4447| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. | 4448 4449**示例:** 4450 4451```ts 4452import { BusinessError } from '@kit.BasicServicesKit' 4453 4454@Entry 4455@Component 4456struct Index { 4457 async routePage() { 4458 this.getUIContext().getRouter().replaceUrl({ 4459 url: 'pages/detail', 4460 params: { 4461 data1: 'message' 4462 } 4463 }, (err: Error) => { 4464 if (err) { 4465 let message = (err as BusinessError).message; 4466 let code = (err as BusinessError).code; 4467 console.error(`replaceUrl failed, code is ${code}, message is ${message}`); 4468 return; 4469 } 4470 console.info('replaceUrl success'); 4471 }) 4472 } 4473 4474 build() { 4475 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4476 Button() { 4477 Text('next page') 4478 .fontSize(25) 4479 .fontWeight(FontWeight.Bold) 4480 }.type(ButtonType.Capsule) 4481 .margin({ top: 20 }) 4482 .backgroundColor('#ccc') 4483 .onClick(() => { 4484 this.routePage() 4485 }) 4486 } 4487 .width('100%') 4488 .height('100%') 4489 } 4490} 4491``` 4492 4493### replaceUrl 4494 4495replaceUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void> 4496 4497用应用内的某个页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。 4498 4499**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4500 4501**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4502 4503**参数:** 4504 4505| 参数名 | 类型 | 必填 | 说明 | 4506| ------- | ---------------------------------------- | ---- | ---------- | 4507| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 | 4508| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 4509 4510**返回值:** 4511 4512| 类型 | 说明 | 4513| ------------------- | ------- | 4514| Promise<void> | 异常返回结果。 | 4515 4516**错误码:** 4517 4518以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4519 4520| 错误码ID | 错误信息 | 4521| ------ | ---------------------------------------- | 4522| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4523| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. | 4524| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. | 4525 4526**示例:** 4527 4528```ts 4529import { router } from '@kit.ArkUI'; 4530import { BusinessError } from '@kit.BasicServicesKit' 4531 4532class RouterTmp { 4533 Standard: router.RouterMode = router.RouterMode.Standard 4534} 4535 4536let rtm: RouterTmp = new RouterTmp() 4537 4538@Entry 4539@Component 4540struct Index { 4541 async routePage() { 4542 this.getUIContext().getRouter().replaceUrl({ 4543 url: 'pages/detail', 4544 params: { 4545 data1: 'message' 4546 } 4547 }, rtm.Standard) 4548 .then(() => { 4549 console.info('succeeded') 4550 }) 4551 .catch((error: BusinessError) => { 4552 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4553 }) 4554 } 4555 4556 build() { 4557 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4558 Button() { 4559 Text('next page') 4560 .fontSize(25) 4561 .fontWeight(FontWeight.Bold) 4562 }.type(ButtonType.Capsule) 4563 .margin({ top: 20 }) 4564 .backgroundColor('#ccc') 4565 .onClick(() => { 4566 this.routePage() 4567 }) 4568 } 4569 .width('100%') 4570 .height('100%') 4571 } 4572} 4573``` 4574 4575### replaceUrl 4576 4577replaceUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 4578 4579用应用内的某个页面替换当前页面,并销毁被替换的页面。 4580 4581**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4582 4583**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4584 4585**参数:** 4586 4587| 参数名 | 类型 | 必填 | 说明 | 4588| -------- | ---------------------------------------- | ---- | ---------- | 4589| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 | 4590| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 4591| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 4592 4593**错误码:** 4594 4595以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4596 4597| 错误码ID | 错误信息 | 4598| ------ | ---------------------------------------- | 4599| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4600| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 4601| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. | 4602 4603**示例:** 4604 4605```ts 4606import { router } from '@kit.ArkUI'; 4607import { BusinessError } from '@kit.BasicServicesKit'; 4608 4609class RouterTmp { 4610 Standard: router.RouterMode = router.RouterMode.Standard 4611} 4612 4613let rtm: RouterTmp = new RouterTmp() 4614 4615@Entry 4616@Component 4617struct Index { 4618 async routePage() { 4619 this.getUIContext().getRouter().replaceUrl({ 4620 url: 'pages/detail', 4621 params: { 4622 data1: 'message' 4623 } 4624 }, rtm.Standard, (err: Error) => { 4625 if (err) { 4626 let message = (err as BusinessError).message; 4627 let code = (err as BusinessError).code; 4628 console.error(`replaceUrl failed, code is ${code}, message is ${message}`); 4629 return; 4630 } 4631 console.info('replaceUrl success'); 4632 }); 4633 } 4634 4635 build() { 4636 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4637 Button() { 4638 Text('next page') 4639 .fontSize(25) 4640 .fontWeight(FontWeight.Bold) 4641 }.type(ButtonType.Capsule) 4642 .margin({ top: 20 }) 4643 .backgroundColor('#ccc') 4644 .onClick(() => { 4645 this.routePage() 4646 }) 4647 } 4648 .width('100%') 4649 .height('100%') 4650 } 4651} 4652``` 4653 4654### pushNamedRoute 4655 4656pushNamedRoute(options: router.NamedRouterOptions): Promise<void> 4657 4658跳转到指定的命名路由页面,通过Promise获取跳转异常的返回结果。 4659 4660**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4661 4662**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4663 4664**参数:** 4665 4666| 参数名 | 类型 | 必填 | 说明 | 4667| ------- | ---------------------------------------- | ---- | --------- | 4668| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 | 4669 4670**返回值:** 4671 4672| 类型 | 说明 | 4673| ------------------- | ------- | 4674| Promise<void> | 异常返回结果。 | 4675 4676**错误码:** 4677 4678以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4679 4680| 错误码ID | 错误信息 | 4681| ------ | ---------------------------------- | 4682| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4683| 100001 | Internal error. | 4684| 100003 | Page stack error. Too many pages are pushed. | 4685| 100004 | Named route error. The named route does not exist. | 4686 4687**示例:** 4688 4689```ts 4690import { BusinessError } from '@kit.BasicServicesKit' 4691 4692@Entry 4693@Component 4694struct Index { 4695 async routePage() { 4696 this.getUIContext().getRouter().pushNamedRoute({ 4697 name: 'myPage', 4698 params: { 4699 data1: 'message', 4700 data2: { 4701 data3: [123, 456, 789] 4702 } 4703 } 4704 }) 4705 .then(() => { 4706 console.info('succeeded') 4707 }) 4708 .catch((error: BusinessError) => { 4709 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4710 }) 4711 } 4712 4713 build() { 4714 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4715 Button() { 4716 Text('next page') 4717 .fontSize(25) 4718 .fontWeight(FontWeight.Bold) 4719 }.type(ButtonType.Capsule) 4720 .margin({ top: 20 }) 4721 .backgroundColor('#ccc') 4722 .onClick(() => { 4723 this.routePage() 4724 }) 4725 } 4726 .width('100%') 4727 .height('100%') 4728 } 4729} 4730``` 4731 4732### pushNamedRoute 4733 4734pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void 4735 4736跳转到指定的命名路由页面。 4737 4738**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4739 4740**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4741 4742**参数:** 4743 4744| 参数名 | 类型 | 必填 | 说明 | 4745| -------- | ---------------------------------------- | ---- | --------- | 4746| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 | 4747| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 4748 4749**错误码:** 4750 4751以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4752 4753| 错误码ID | 错误信息 | 4754| ------ | ---------------------------------- | 4755| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4756| 100001 | Internal error. | 4757| 100003 | Page stack error. Too many pages are pushed. | 4758| 100004 | Named route error. The named route does not exist. | 4759 4760**示例:** 4761 4762```ts 4763import { BusinessError } from '@kit.BasicServicesKit'; 4764 4765@Entry 4766@Component 4767struct Index { 4768 async routePage() { 4769 this.getUIContext().getRouter().pushNamedRoute({ 4770 name: 'myPage', 4771 params: { 4772 data1: 'message', 4773 data2: { 4774 data3: [123, 456, 789] 4775 } 4776 } 4777 }, (err: Error) => { 4778 if (err) { 4779 let message = (err as BusinessError).message; 4780 let code = (err as BusinessError).code; 4781 console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); 4782 return; 4783 } 4784 console.info('pushNamedRoute success'); 4785 }) 4786 } 4787 4788 build() { 4789 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4790 Button() { 4791 Text('next page') 4792 .fontSize(25) 4793 .fontWeight(FontWeight.Bold) 4794 }.type(ButtonType.Capsule) 4795 .margin({ top: 20 }) 4796 .backgroundColor('#ccc') 4797 .onClick(() => { 4798 this.routePage() 4799 }) 4800 } 4801 .width('100%') 4802 .height('100%') 4803 } 4804} 4805``` 4806### pushNamedRoute 4807 4808pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void> 4809 4810跳转到指定的命名路由页面,通过Promise获取跳转异常的返回结果。 4811 4812**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4813 4814**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4815 4816**参数:** 4817 4818| 参数名 | 类型 | 必填 | 说明 | 4819| ------- | ---------------------------------------- | ---- | ---------- | 4820| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 | 4821| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 4822 4823**返回值:** 4824 4825| 类型 | 说明 | 4826| ------------------- | ------- | 4827| Promise<void> | 异常返回结果。 | 4828 4829**错误码:** 4830 4831以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4832 4833| 错误码ID | 错误信息 | 4834| ------ | ---------------------------------- | 4835| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4836| 100001 | Internal error. | 4837| 100003 | Page stack error. Too many pages are pushed. | 4838| 100004 | Named route error. The named route does not exist. | 4839 4840**示例:** 4841 4842```ts 4843import { router } from '@kit.ArkUI'; 4844import { BusinessError } from '@kit.BasicServicesKit'; 4845 4846class RouterTmp{ 4847 Standard:router.RouterMode = router.RouterMode.Standard 4848} 4849let rtm:RouterTmp = new RouterTmp() 4850 4851@Entry 4852@Component 4853struct Index { 4854 async routePage() { 4855 this.getUIContext().getRouter().pushNamedRoute({ 4856 name: 'myPage', 4857 params: { 4858 data1: 'message', 4859 data2: { 4860 data3: [123, 456, 789] 4861 } 4862 } 4863 }, rtm.Standard) 4864 .then(() => { 4865 console.info('succeeded') 4866 }) 4867 .catch((error: BusinessError) => { 4868 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4869 }) 4870 } 4871 4872 build() { 4873 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4874 Button() { 4875 Text('next page') 4876 .fontSize(25) 4877 .fontWeight(FontWeight.Bold) 4878 }.type(ButtonType.Capsule) 4879 .margin({ top: 20 }) 4880 .backgroundColor('#ccc') 4881 .onClick(() => { 4882 this.routePage() 4883 }) 4884 } 4885 .width('100%') 4886 .height('100%') 4887 } 4888} 4889``` 4890 4891### pushNamedRoute 4892 4893pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 4894 4895跳转到指定的命名路由页面。 4896 4897**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4898 4899**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4900 4901**参数:** 4902 4903| 参数名 | 类型 | 必填 | 说明 | 4904| -------- | ---------------------------------------- | ---- | ---------- | 4905| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 | 4906| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 4907| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 4908 4909**错误码:** 4910 4911以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4912 4913| 错误码ID | 错误信息 | 4914| ------ | ---------------------------------- | 4915| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4916| 100001 | Internal error. | 4917| 100003 | Page stack error. Too many pages are pushed. | 4918| 100004 | Named route error. The named route does not exist. | 4919 4920**示例:** 4921 4922```ts 4923import { router } from '@kit.ArkUI'; 4924import { BusinessError } from '@kit.BasicServicesKit'; 4925 4926class RouterTmp { 4927 Standard: router.RouterMode = router.RouterMode.Standard 4928} 4929 4930let rtm: RouterTmp = new RouterTmp() 4931 4932@Entry 4933@Component 4934struct Index { 4935 async routePage() { 4936 this.getUIContext().getRouter().pushNamedRoute({ 4937 name: 'myPage', 4938 params: { 4939 data1: 'message', 4940 data2: { 4941 data3: [123, 456, 789] 4942 } 4943 } 4944 }, rtm.Standard, (err: Error) => { 4945 if (err) { 4946 let message = (err as BusinessError).message; 4947 let code = (err as BusinessError).code; 4948 console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); 4949 return; 4950 } 4951 console.info('pushNamedRoute success'); 4952 }) 4953 } 4954 4955 build() { 4956 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4957 Button() { 4958 Text('next page') 4959 .fontSize(25) 4960 .fontWeight(FontWeight.Bold) 4961 }.type(ButtonType.Capsule) 4962 .margin({ top: 20 }) 4963 .backgroundColor('#ccc') 4964 .onClick(() => { 4965 this.routePage() 4966 }) 4967 } 4968 .width('100%') 4969 .height('100%') 4970 } 4971} 4972``` 4973 4974### replaceNamedRoute 4975 4976replaceNamedRoute(options: router.NamedRouterOptions): Promise<void> 4977 4978用指定的命名路由页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。 4979 4980**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4981 4982**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4983 4984**参数:** 4985 4986| 参数名 | 类型 | 必填 | 说明 | 4987| ------- | ---------------------------------------- | ---- | --------- | 4988| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 | 4989 4990**返回值:** 4991 4992| 类型 | 说明 | 4993| ------------------- | ------- | 4994| Promise<void> | 异常返回结果。 | 4995 4996**错误码:** 4997 4998以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4999 5000| 错误码ID | 错误信息 | 5001| ------ | ---------------------------------------- | 5002| 401 | if the number of parameters is less than 1 or the type of the url parameter is not string. | 5003| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 5004| 100004 | Named route error. The named route does not exist. | 5005 5006**示例:** 5007 5008```ts 5009import { BusinessError } from '@kit.BasicServicesKit'; 5010 5011@Entry 5012@Component 5013struct Index { 5014 async routePage() { 5015 this.getUIContext().getRouter().replaceNamedRoute({ 5016 name: 'myPage', 5017 params: { 5018 data1: 'message' 5019 } 5020 }) 5021 .then(() => { 5022 console.info('succeeded') 5023 }) 5024 .catch((error: BusinessError) => { 5025 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 5026 }) 5027 } 5028 5029 build() { 5030 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5031 Button() { 5032 Text('next page') 5033 .fontSize(25) 5034 .fontWeight(FontWeight.Bold) 5035 }.type(ButtonType.Capsule) 5036 .margin({ top: 20 }) 5037 .backgroundColor('#ccc') 5038 .onClick(() => { 5039 this.routePage() 5040 }) 5041 } 5042 .width('100%') 5043 .height('100%') 5044 } 5045} 5046``` 5047 5048### replaceNamedRoute 5049 5050replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void 5051 5052用指定的命名路由页面替换当前页面,并销毁被替换的页面。 5053 5054**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5055 5056**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5057 5058**参数:** 5059 5060| 参数名 | 类型 | 必填 | 说明 | 5061| -------- | ---------------------------------------- | ---- | --------- | 5062| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 | 5063| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 5064 5065**错误码:** 5066 5067以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 5068 5069| 错误码ID | 错误信息 | 5070| ------ | ---------------------------------------- | 5071| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5072| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 5073| 100004 | Named route error. The named route does not exist. | 5074 5075**示例:** 5076 5077```ts 5078import { BusinessError } from '@kit.BasicServicesKit'; 5079 5080@Entry 5081@Component 5082struct Index { 5083 async routePage() { 5084 this.getUIContext().getRouter().replaceNamedRoute({ 5085 name: 'myPage', 5086 params: { 5087 data1: 'message' 5088 } 5089 }, (err: Error) => { 5090 if (err) { 5091 let message = (err as BusinessError).message; 5092 let code = (err as BusinessError).code; 5093 console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`); 5094 return; 5095 } 5096 console.info('replaceNamedRoute success'); 5097 }) 5098 } 5099 5100 build() { 5101 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5102 Button() { 5103 Text('next page') 5104 .fontSize(25) 5105 .fontWeight(FontWeight.Bold) 5106 }.type(ButtonType.Capsule) 5107 .margin({ top: 20 }) 5108 .backgroundColor('#ccc') 5109 .onClick(() => { 5110 this.routePage() 5111 }) 5112 } 5113 .width('100%') 5114 .height('100%') 5115 } 5116} 5117``` 5118 5119### replaceNamedRoute 5120 5121replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void> 5122 5123用指定的命名路由页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。 5124 5125**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5126 5127**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5128 5129**参数:** 5130 5131| 参数名 | 类型 | 必填 | 说明 | 5132| ------- | ---------------------------------------- | ---- | ---------- | 5133| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 | 5134| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 5135 5136 5137**返回值:** 5138 5139| 类型 | 说明 | 5140| ------------------- | ------- | 5141| Promise<void> | 异常返回结果。 | 5142 5143**错误码:** 5144 5145以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 5146 5147| 错误码ID | 错误信息 | 5148| ------ | ---------------------------------------- | 5149| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5150| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. | 5151| 100004 | Named route error. The named route does not exist. | 5152 5153**示例:** 5154 5155```ts 5156import { router } from '@kit.ArkUI'; 5157import { BusinessError } from '@kit.BasicServicesKit'; 5158 5159class RouterTmp { 5160 Standard: router.RouterMode = router.RouterMode.Standard 5161} 5162 5163let rtm: RouterTmp = new RouterTmp() 5164 5165@Entry 5166@Component 5167struct Index { 5168 async routePage() { 5169 this.getUIContext().getRouter().replaceNamedRoute({ 5170 name: 'myPage', 5171 params: { 5172 data1: 'message' 5173 } 5174 }, rtm.Standard) 5175 .then(() => { 5176 console.info('succeeded') 5177 }) 5178 .catch((error: BusinessError) => { 5179 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 5180 }) 5181 } 5182 5183 build() { 5184 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5185 Button() { 5186 Text('next page') 5187 .fontSize(25) 5188 .fontWeight(FontWeight.Bold) 5189 }.type(ButtonType.Capsule) 5190 .margin({ top: 20 }) 5191 .backgroundColor('#ccc') 5192 .onClick(() => { 5193 this.routePage() 5194 }) 5195 } 5196 .width('100%') 5197 .height('100%') 5198 } 5199} 5200``` 5201 5202### replaceNamedRoute 5203 5204replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 5205 5206用指定的命名路由页面替换当前页面,并销毁被替换的页面。 5207 5208**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5209 5210**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5211 5212**参数:** 5213 5214| 参数名 | 类型 | 必填 | 说明 | 5215| -------- | ---------------------------------------- | ---- | ---------- | 5216| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 | 5217| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 5218| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 5219 5220**错误码:** 5221 5222以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 5223 5224| 错误码ID | 错误信息 | 5225| ------ | ---------------------------------------- | 5226| 401 | if the number of parameters is less than 1 or the type of the url parameter is not string. | 5227| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 5228| 100004 | Named route error. The named route does not exist. | 5229 5230**示例:** 5231 5232```ts 5233import { router } from '@kit.ArkUI'; 5234import { BusinessError } from '@kit.BasicServicesKit'; 5235 5236class RouterTmp { 5237 Standard: router.RouterMode = router.RouterMode.Standard 5238} 5239 5240let rtm: RouterTmp = new RouterTmp() 5241 5242@Entry 5243@Component 5244struct Index { 5245 async routePage() { 5246 this.getUIContext().getRouter().replaceNamedRoute({ 5247 name: 'myPage', 5248 params: { 5249 data1: 'message' 5250 } 5251 }, rtm.Standard, (err: Error) => { 5252 if (err) { 5253 let message = (err as BusinessError).message; 5254 let code = (err as BusinessError).code; 5255 console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`); 5256 return; 5257 } 5258 console.info('replaceNamedRoute success'); 5259 }) 5260 } 5261 5262 build() { 5263 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5264 Button() { 5265 Text('next page') 5266 .fontSize(25) 5267 .fontWeight(FontWeight.Bold) 5268 }.type(ButtonType.Capsule) 5269 .margin({ top: 20 }) 5270 .backgroundColor('#ccc') 5271 .onClick(() => { 5272 this.routePage() 5273 }) 5274 } 5275 .width('100%') 5276 .height('100%') 5277 } 5278} 5279``` 5280 5281### back 5282 5283back(options?: router.RouterOptions ): void 5284 5285返回上一页面或指定的页面。 5286 5287**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5288 5289**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5290 5291**参数:** 5292 5293| 参数名 | 类型 | 必填 | 说明 | 5294| ------- | ---------------------------------------- | ---- | ---------------------------------------- | 5295| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 否 | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面不会重新构建,页面栈里面的page不会回收,出栈后会被回收。 | 5296 5297**示例:** 5298 5299```ts 5300import { Router } from '@kit.ArkUI'; 5301let router: Router = uiContext.getRouter(); 5302router.back({url:'pages/detail'}); 5303``` 5304 5305### back<sup>12+</sup> 5306 5307back(index: number, params?: Object): void; 5308 5309返回指定的页面。 5310 5311**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 5312 5313**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5314 5315**参数:** 5316 5317| 参数名 | 类型 | 必填 | 说明 | 5318| ------- | ------------------------------- | ---- | ---------- | 5319| index | number | 是 | 跳转目标页面的索引值。 | 5320| params | Object | 否 | 页面返回时携带的参数。 | 5321 5322**示例:** 5323 5324```ts 5325import { Router } from '@kit.ArkUI'; 5326 5327let router: Router = uiContext.getRouter(); 5328router.back(1); 5329``` 5330 5331```ts 5332import { Router } from '@kit.ArkUI'; 5333 5334let router: Router = uiContext.getRouter(); 5335router.back(1, {info:'来自Home页'}); //携带参数返回 5336``` 5337 5338### clear 5339 5340clear(): void 5341 5342清空页面栈中的所有历史页面,仅保留当前页面作为栈顶页面。 5343 5344**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5345 5346**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5347 5348**示例:** 5349 5350```ts 5351import { Router } from '@kit.ArkUI'; 5352 5353let router: Router = uiContext.getRouter(); 5354router.clear(); 5355``` 5356 5357### getLength 5358 5359getLength(): string 5360 5361获取当前在页面栈内的页面数量。 5362 5363**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5364 5365**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5366 5367**返回值:** 5368 5369| 类型 | 说明 | 5370| ------ | ------------------ | 5371| string | 页面数量,页面栈支持最大数值是32。 | 5372 5373**示例:** 5374 5375```ts 5376import { Router } from '@kit.ArkUI'; 5377 5378let router: Router = uiContext.getRouter(); 5379let size = router.getLength(); 5380console.info('pages stack size = ' + size); 5381``` 5382 5383### getState 5384 5385getState(): router.RouterState 5386 5387获取当前页面的状态信息。 5388 5389**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5390 5391**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5392 5393**返回值:** 5394 5395| 类型 | 说明 | 5396| ---------------------------------------- | ------- | 5397| router.[RouterState](js-apis-router.md#routerstate) | 页面状态信息。 | 5398 5399**示例:** 5400 5401<!--code_no_check--> 5402```ts 5403import { Router } from '@kit.ArkUI'; 5404 5405let router: Router = uiContext.getRouter(); 5406let page = router.getState(); 5407console.info('current index = ' + page.index); 5408console.info('current name = ' + page.name); 5409console.info('current path = ' + page.path); 5410``` 5411 5412### getStateByIndex<sup>12+</sup> 5413 5414getStateByIndex(index: number): router.RouterState | undefined 5415 5416通过索引值获取对应页面的状态信息。 5417 5418**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 5419 5420**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5421 5422**参数:** 5423 5424| 参数名 | 类型 | 必填 | 说明 | 5425| ------- | ------------------------------- | ---- | ---------- | 5426| index | number | 是 | 表示要获取的页面索引。 | 5427 5428**返回值:** 5429 5430| 类型 | 说明 | 5431| --------------------------- | ------- | 5432| router.[RouterState](js-apis-router.md#outerstate) \| undefined | 返回页面状态信息。索引不存在时返回undefined。 | 5433 5434**示例:** 5435 5436<!--code_no_check--> 5437```ts 5438import { Router } from '@kit.ArkUI'; 5439 5440let router: Router = uiContext.getRouter(); 5441let options: router.RouterState | undefined = router.getStateByIndex(1); 5442if (options != undefined) { 5443 console.info('index = ' + options.index); 5444 console.info('name = ' + options.name); 5445 console.info('path = ' + options.path); 5446 console.info('params = ' + options.params); 5447} 5448``` 5449### getStateByUrl<sup>12+</sup> 5450 5451getStateByUrl(url: string): Array<router.[RouterState](js-apis-router.md#outerstate)> 5452 5453通过url获取当前页面的状态信息。 5454 5455**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 5456 5457**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5458 5459**参数:** 5460 5461| 参数名 | 类型 | 必填 | 说明 | 5462| ------- | ------------------------------- | ---- | ---------- | 5463| url | string | 是 | 表示要获取对应页面信息的url。 | 5464 5465**返回值:** 5466 5467| 类型 | 说明 | 5468| --------------------------- | ------- | 5469| Array<router.[RouterState](js-apis-router.md#outerstate)> | 页面状态信息。 | 5470 5471**示例:** 5472 5473<!--code_no_check--> 5474```ts 5475import { Router } from '@kit.ArkUI'; 5476let router: Router = uiContext.getRouter(); 5477let options:Array<router.RouterState> = router.getStateByUrl('pages/index'); 5478for (let i: number = 0; i < options.length; i++) { 5479 console.info('index = ' + options[i].index); 5480 console.info('name = ' + options[i].name); 5481 console.info('path = ' + options[i].path); 5482 console.info('params = ' + options[i].params); 5483} 5484``` 5485 5486### showAlertBeforeBackPage 5487 5488showAlertBeforeBackPage(options: router.EnableAlertOptions): void 5489 5490开启页面返回询问对话框。 5491 5492**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5493 5494**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5495 5496**参数:** 5497 5498| 参数名 | 类型 | 必填 | 说明 | 5499| ------- | ---------------------------------------- | ---- | --------- | 5500| options | [router.EnableAlertOptions](js-apis-router.md#enablealertoptions) | 是 | 文本弹窗信息描述。 | 5501 5502**错误码:** 5503 5504以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 5505 5506| 错误码ID | 错误信息 | 5507| ------ | ---------------------------------- | 5508| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5509| 100001 | Internal error. | 5510 5511**示例:** 5512 5513<!--code_no_check--> 5514```ts 5515import { Router } from '@kit.ArkUI'; 5516import { BusinessError } from '@kit.BasicServicesKit'; 5517 5518let router: Router = uiContext.getRouter(); 5519try { 5520 router.showAlertBeforeBackPage({ 5521 message: 'Message Info' 5522 }); 5523} catch(error) { 5524 let message = (error as BusinessError).message; 5525 let code = (error as BusinessError).code; 5526 console.error(`showAlertBeforeBackPage failed, code is ${code}, message is ${message}`); 5527} 5528``` 5529 5530### hideAlertBeforeBackPage 5531 5532hideAlertBeforeBackPage(): void 5533 5534禁用页面返回询问对话框。 5535 5536**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5537 5538**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5539 5540**示例:** 5541 5542<!--code_no_check--> 5543```ts 5544import { Router } from '@kit.ArkUI'; 5545 5546let router: Router = uiContext.getRouter(); 5547router.hideAlertBeforeBackPage(); 5548``` 5549 5550### getParams 5551 5552getParams(): Object 5553 5554获取发起跳转的页面往当前页传入的参数。 5555 5556**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5557 5558**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5559 5560**返回值:** 5561 5562| 类型 | 说明 | 5563| ------ | ----------------- | 5564| Object | 发起跳转的页面往当前页传入的参数。 | 5565 5566**示例:** 5567 5568<!--code_no_check--> 5569 5570```ts 5571import { Router } from '@kit.ArkUI'; 5572 5573let router: Router = uiContext.getRouter(); 5574router.getParams(); 5575``` 5576 5577## PromptAction 5578 5579以下API需先使用UIContext中的[getPromptAction()](#getpromptaction)方法获取到PromptAction对象,再通过该对象调用对应方法。 5580 5581### showToast 5582 5583showToast(options: promptAction.ShowToastOptions): void 5584 5585创建并显示文本提示框。 5586 5587**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5588 5589**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5590 5591**参数:** 5592 5593| 参数名 | 类型 | 必填 | 说明 | 5594| ------- | ---------------------------------------- | ---- | ------- | 5595| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | 是 | 文本弹窗选项。 | 5596 5597**错误码:** 5598 5599以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 5600 5601| 错误码ID | 错误信息 | 5602| ------ | ---------------------------------- | 5603| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5604| 100001 | Internal error. | 5605 5606**示例:** 5607 5608<!--code_no_check--> 5609```ts 5610import { PromptAction } from '@kit.ArkUI'; 5611import { BusinessError } from '@kit.BasicServicesKit'; 5612 5613let promptAction: PromptAction = uiContext.getPromptAction(); 5614try { 5615 promptAction.showToast({ 5616 message: 'Message Info', 5617 duration: 2000 5618 }); 5619} catch (error) { 5620 let message = (error as BusinessError).message; 5621 let code = (error as BusinessError).code; 5622 console.error(`showToast args error code is ${code}, message is ${message}`); 5623}; 5624``` 5625 5626### showDialog 5627 5628showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse>): void 5629 5630创建并显示对话框,对话框响应结果异步返回。 5631 5632**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5633 5634**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5635 5636**参数:** 5637 5638| 参数名 | 类型 | 必填 | 说明 | 5639| -------- | ---------------------------------------- | ---- | ------------ | 5640| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | 是 | 页面显示对话框信息描述。 | 5641| callback | AsyncCallback<[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | 是 | 对话框响应结果回调。 | 5642 5643**错误码:** 5644 5645以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 5646 5647| 错误码ID | 错误信息 | 5648| ------ | ---------------------------------- | 5649| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5650| 100001 | Internal error. | 5651 5652**示例:** 5653 5654<!--code_no_check--> 5655 5656```ts 5657import { PromptAction } from '@kit.ArkUI'; 5658import { BusinessError } from '@kit.BasicServicesKit'; 5659 5660let promptAction: PromptAction = uiContext.getPromptAction(); 5661try { 5662 promptAction.showDialog({ 5663 title: 'showDialog Title Info', 5664 message: 'Message Info', 5665 buttons: [ 5666 { 5667 text: 'button1', 5668 color: '#000000' 5669 }, 5670 { 5671 text: 'button2', 5672 color: '#000000' 5673 } 5674 ] 5675 }, (err, data) => { 5676 if (err) { 5677 console.error('showDialog err: ' + err); 5678 return; 5679 } 5680 console.info('showDialog success callback, click button: ' + data.index); 5681 }); 5682} catch (error) { 5683 let message = (error as BusinessError).message; 5684 let code = (error as BusinessError).code; 5685 console.error(`showDialog args error code is ${code}, message is ${message}`); 5686}; 5687``` 5688 5689### showDialog 5690 5691showDialog(options: promptAction.ShowDialogOptions): Promise<promptAction.ShowDialogSuccessResponse> 5692 5693创建并显示对话框,对话框响应后同步返回结果,通过Promise获取对话框响应结果。 5694 5695**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5696 5697**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5698 5699**参数:** 5700 5701| 参数名 | 类型 | 必填 | 说明 | 5702| ------- | ---------------------------------------- | ---- | ------ | 5703| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | 是 | 对话框选项。 | 5704 5705**返回值:** 5706 5707| 类型 | 说明 | 5708| ---------------------------------------- | -------- | 5709| Promise<[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | 对话框响应结果。 | 5710 5711**错误码:** 5712 5713以下错误码的详细介绍请参见[ 通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 5714 5715| 错误码ID | 错误信息 | 5716| ------ | ---------------------------------- | 5717| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5718| 100001 | Internal error. | 5719 5720**示例:** 5721 5722<!--code_no_check--> 5723```ts 5724import { PromptAction } from '@kit.ArkUI'; 5725 5726let promptAction: PromptAction = uiContext.getPromptAction(); 5727promptAction.showDialog({ 5728 title: 'Title Info', 5729 message: 'Message Info', 5730 buttons: [ 5731 { 5732 text: 'button1', 5733 color: '#000000' 5734 }, 5735 { 5736 text: 'button2', 5737 color: '#000000' 5738 } 5739 ], 5740}) 5741 .then(data => { 5742 console.info('showDialog success, click button: ' + data.index); 5743 }) 5744 .catch((err: Error) => { 5745 console.error('showDialog error: ' + err); 5746 }) 5747``` 5748 5749### showActionMenu<sup>11+</sup> 5750 5751showActionMenu(options: promptAction.ActionMenuOptions, callback: AsyncCallback<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)>):void 5752 5753创建并显示操作菜单,菜单响应结果异步返回。 5754 5755**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5756 5757**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5758 5759**参数:** 5760 5761| 参数名 | 类型 | 必填 | 说明 | 5762| -------- | ------------------------------------------------------------ | ---- | ------------------ | 5763| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是 | 操作菜单选项。 | 5764| callback | AsyncCallback<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | 是 | 菜单响应结果回调。 | 5765 5766**错误码:** 5767 5768以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 5769 5770| 错误码ID | 错误信息 | 5771| -------- | ---------------------------------- | 5772| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5773| 100001 | Internal error. | 5774 5775**示例:** 5776 5777<!--code_no_check--> 5778```ts 5779import { PromptAction, promptAction } from '@kit.ArkUI'; 5780import { BusinessError } from '@kit.BasicServicesKit'; 5781 5782let promptActionF: PromptAction = uiContext.getPromptAction(); 5783try { 5784 promptActionF.showActionMenu({ 5785 title: 'Title Info', 5786 buttons: [ 5787 { 5788 text: 'item1', 5789 color: '#666666' 5790 }, 5791 { 5792 text: 'item2', 5793 color: '#000000' 5794 } 5795 ] 5796 }, (err:BusinessError, data:promptAction.ActionMenuSuccessResponse) => { 5797 if (err) { 5798 console.error('showDialog err: ' + err); 5799 return; 5800 } 5801 console.info('showDialog success callback, click button: ' + data.index); 5802 }); 5803} catch (error) { 5804 let message = (error as BusinessError).message; 5805 let code = (error as BusinessError).code; 5806 console.error(`showActionMenu args error code is ${code}, message is ${message}`); 5807}; 5808``` 5809 5810### showActionMenu<sup>(deprecated)</sup> 5811 5812showActionMenu(options: promptAction.ActionMenuOptions, callback: [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)):void 5813 5814创建并显示操作菜单,菜单响应结果异步返回。 5815 5816从API version11开始不再维护,建议使用[showActionMenu](#showactionmenu11)。 5817 5818**系统能力:** SystemCapability.ArkUI.ArkUI.Full。 5819 5820**参数:** 5821 5822| 参数名 | 类型 | 必填 | 说明 | 5823| -------- | ------------------------------------------------------------ | ---- | ------------------ | 5824| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是 | 操作菜单选项。 | 5825| callback | [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse) | 是 | 菜单响应结果回调。 | 5826 5827**错误码:** 5828 5829以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 5830 5831| 错误码ID | 错误信息 | 5832| ------ | ---------------------------------- | 5833| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5834| 100001 | Internal error. | 5835 5836**示例:** 5837 5838<!--code_no_check--> 5839```ts 5840import { PromptAction,promptAction } from '@kit.ArkUI'; 5841import { BusinessError } from '@kit.BasicServicesKit'; 5842 5843let promptActionF: PromptAction = uiContext.getPromptAction(); 5844try { 5845 promptActionF.showActionMenu({ 5846 title: 'Title Info', 5847 buttons: [ 5848 { 5849 text: 'item1', 5850 color: '#666666' 5851 }, 5852 { 5853 text: 'item2', 5854 color: '#000000' 5855 } 5856 ] 5857 }, { index:0 }); 5858} catch (error) { 5859 let message = (error as BusinessError).message; 5860 let code = (error as BusinessError).code; 5861 console.error(`showActionMenu args error code is ${code}, message is ${message}`); 5862}; 5863``` 5864 5865### showActionMenu 5866 5867showActionMenu(options: promptAction.ActionMenuOptions): Promise<promptAction.ActionMenuSuccessResponse> 5868 5869创建并显示操作菜单,通过Promise获取菜单响应结果。 5870 5871**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5872 5873**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5874 5875**参数:** 5876 5877| 参数名 | 类型 | 必填 | 说明 | 5878| ------- | ---------------------------------------- | ---- | ------- | 5879| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是 | 操作菜单选项。 | 5880 5881**返回值:** 5882 5883| 类型 | 说明 | 5884| ---------------------------------------- | ------- | 5885| Promise<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | 菜单响应结果。 | 5886 5887**错误码:** 5888 5889以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 5890 5891| 错误码ID | 错误信息 | 5892| ------ | ---------------------------------- | 5893| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5894| 100001 | Internal error. | 5895 5896**示例:** 5897 5898<!--code_no_check--> 5899```ts 5900import { PromptAction } from '@kit.ArkUI'; 5901 5902let promptAction: PromptAction = uiContext.getPromptAction(); 5903promptAction.showActionMenu({ 5904 title: 'showActionMenu Title Info', 5905 buttons: [ 5906 { 5907 text: 'item1', 5908 color: '#666666' 5909 }, 5910 { 5911 text: 'item2', 5912 color: '#000000' 5913 }, 5914 ] 5915}) 5916 .then(data => { 5917 console.info('showActionMenu success, click button: ' + data.index); 5918 }) 5919 .catch((err: Error) => { 5920 console.error('showActionMenu error: ' + err); 5921 }) 5922``` 5923 5924### openCustomDialog<sup>12+</sup> 5925 5926openCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>, options?: promptAction.BaseDialogOptions): Promise<void> 5927 5928创建并弹出dialogContent对应的自定义弹窗,使用Promise异步回调。通过该接口弹出的弹窗内容样式完全按照dialogContent中设置的样式显示,即相当于customdialog设置customStyle为true时的显示效果。暂不支持isModal = true与showInSubWindow = true同时使用。 5929 5930**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 5931 5932**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5933 5934**参数:** 5935 5936| 参数名 | 类型 | 必填 | 说明 | 5937| ------- | ---------------------------------------- | ---- | ------- | 5938| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 | 5939| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | 否 | 弹窗样式。 | 5940 5941**返回值:** 5942 5943| 类型 | 说明 | 5944| ---------------------------------------- | ------- | 5945| Promise<void> | 异常返回Promise对象。 | 5946 5947**错误码:** 5948 5949以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 5950 5951| 错误码ID | 错误信息 | 5952| ------ | ---------------------------------- | 5953| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5954| 103301 | the ComponentContent is incorrect. | 5955| 103302 | Dialog content already exists.| 5956 5957**示例:** 5958 5959```ts 5960import { BusinessError } from '@kit.BasicServicesKit'; 5961import { ComponentContent } from '@kit.ArkUI'; 5962 5963class Params { 5964 text: string = "" 5965 5966 constructor(text: string) { 5967 this.text = text; 5968 } 5969} 5970 5971@Builder 5972function buildText(params: Params) { 5973 Column() { 5974 Text(params.text) 5975 .fontSize(50) 5976 .fontWeight(FontWeight.Bold) 5977 .margin({ bottom: 36 }) 5978 }.backgroundColor('#FFF0F0F0') 5979} 5980 5981@Entry 5982@Component 5983struct Index { 5984 @State message: string = "hello" 5985 5986 build() { 5987 Row() { 5988 Column() { 5989 Button("click me") 5990 .onClick(() => { 5991 let uiContext = this.getUIContext(); 5992 let promptAction = uiContext.getPromptAction(); 5993 let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); 5994 promptAction.openCustomDialog(contentNode) 5995 .then(() => { 5996 console.info('succeeded') 5997 }) 5998 .catch((error: BusinessError) => { 5999 console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`); 6000 }) 6001 }) 6002 } 6003 .width('100%') 6004 .height('100%') 6005 } 6006 .height('100%') 6007 } 6008} 6009``` 6010 6011### closeCustomDialog<sup>12+</sup> 6012 6013closeCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>): Promise<void> 6014 6015关闭已弹出的dialogContent对应的自定义弹窗,使用Promise异步回调。 6016 6017**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6018 6019**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6020 6021**参数:** 6022 6023| 参数名 | 类型 | 必填 | 说明 | 6024| ------- | ---------------------------------------- | ---- | ------- | 6025| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 | 6026 6027**返回值:** 6028 6029| 类型 | 说明 | 6030| ---------------------------------------- | ------- | 6031| Promise<void> | 异常返回Promise对象。 | 6032 6033**错误码:** 6034 6035以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6036 6037| 错误码ID | 错误信息 | 6038| ------ | ---------------------------------- | 6039| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6040| 103301 | the ComponentContent is incorrect. | 6041| 103303 | the ComponentContent cannot be found. | 6042 6043**示例:** 6044 6045```ts 6046import { BusinessError } from '@kit.BasicServicesKit'; 6047import { ComponentContent } from '@kit.ArkUI'; 6048 6049class Params { 6050 text: string = "" 6051 6052 constructor(text: string) { 6053 this.text = text; 6054 } 6055} 6056 6057@Builder 6058function buildText(params: Params) { 6059 Column() { 6060 Text(params.text) 6061 .fontSize(50) 6062 .fontWeight(FontWeight.Bold) 6063 .margin({ bottom: 36 }) 6064 }.backgroundColor('#FFF0F0F0') 6065} 6066 6067@Entry 6068@Component 6069struct Index { 6070 @State message: string = "hello" 6071 6072 build() { 6073 Row() { 6074 Column() { 6075 Button("click me") 6076 .onClick(() => { 6077 let uiContext = this.getUIContext(); 6078 let promptAction = uiContext.getPromptAction(); 6079 let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); 6080 promptAction.openCustomDialog(contentNode) 6081 .then(() => { 6082 console.info('succeeded') 6083 }) 6084 .catch((error: BusinessError) => { 6085 console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`); 6086 }) 6087 setTimeout(() => { 6088 promptAction.closeCustomDialog(contentNode) 6089 .then(() => { 6090 console.info('succeeded') 6091 }) 6092 .catch((error: BusinessError) => { 6093 console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`); 6094 }) 6095 }, 2000); // 2秒后自动关闭 6096 }) 6097 } 6098 .width('100%') 6099 .height('100%') 6100 } 6101 .height('100%') 6102 } 6103} 6104``` 6105 6106### updateCustomDialog<sup>12+</sup> 6107 6108updateCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>, options: promptAction.BaseDialogOptions): Promise<void> 6109 6110更新已弹出的dialogContent对应的自定义弹窗的样式,使用Promise异步回调。 6111 6112**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6113 6114**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6115 6116**参数:** 6117 6118| 参数名 | 类型 | 必填 | 说明 | 6119| ------- | ---------------------------------------- | ---- | ------- | 6120| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 | 6121| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | 是 | 弹窗样式,目前仅支持更新alignment、offset、autoCancel、maskColor。 | 6122 6123**返回值:** 6124 6125| 类型 | 说明 | 6126| ---------------------------------------- | ------- | 6127| Promise<void> | 异常返回Promise对象。 | 6128 6129**错误码:** 6130 6131以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6132 6133| 错误码ID | 错误信息 | 6134| ------ | ---------------------------------- | 6135| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6136| 103301 | the ComponentContent is incorrect. | 6137| 103303 | the ComponentContent cannot be found. | 6138 6139**示例:** 6140 6141```ts 6142import { BusinessError } from '@kit.BasicServicesKit'; 6143import { ComponentContent } from '@kit.ArkUI'; 6144 6145class Params { 6146 text: string = "" 6147 6148 constructor(text: string) { 6149 this.text = text; 6150 } 6151} 6152 6153@Builder 6154function buildText(params: Params) { 6155 Column() { 6156 Text(params.text) 6157 .fontSize(50) 6158 .fontWeight(FontWeight.Bold) 6159 .margin({ bottom: 36 }) 6160 }.backgroundColor('#FFF0F0F0') 6161} 6162 6163@Entry 6164@Component 6165struct Index { 6166 @State message: string = "hello" 6167 6168 build() { 6169 Row() { 6170 Column() { 6171 Button("click me") 6172 .onClick(() => { 6173 let uiContext = this.getUIContext(); 6174 let promptAction = uiContext.getPromptAction(); 6175 let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)) 6176 promptAction.openCustomDialog(contentNode) 6177 .then(() => { 6178 console.info('succeeded') 6179 }) 6180 .catch((error: BusinessError) => { 6181 console.error(`updateCustomDialog args error code is ${error.code}, message is ${error.message}`) 6182 }) 6183 6184 setTimeout(() => { 6185 promptAction.updateCustomDialog(contentNode, { alignment: DialogAlignment.CenterEnd }) 6186 .then(() => { 6187 console.info('succeeded') 6188 }) 6189 .catch((error: BusinessError) => { 6190 console.error(`updateCustomDialog args error code is ${error.code}, message is ${error.message}`) 6191 }) 6192 }, 2000); // 2秒后自动更新弹窗位置 6193 }) 6194 } 6195 .width('100%') 6196 .height('100%') 6197 } 6198 .height('100%') 6199 } 6200} 6201``` 6202 6203### openCustomDialog<sup>12+</sup> 6204 6205openCustomDialog(options: promptAction.CustomDialogOptions): Promise\<number> 6206 6207创建并弹出自定义弹窗。使用Promise异步回调,返回供closeCustomDialog使用的对话框id。暂不支持[isModal](js-apis-promptAction.md#basedialogoptions11) = true与[showInSubWindow](js-apis-promptAction.md#customdialogoptions11) = true同时使用。 6208 6209**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6210 6211**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6212 6213**参数:** 6214 6215| 参数名 | 类型 | 必填 | 说明 | 6216| ------- | ------------------------------------------------------------ | ---- | ------------------ | 6217| options | [promptAction.CustomDialogOptions](js-apis-promptAction.md#customdialogoptions11) | 是 | 自定义弹窗的内容。 | 6218 6219**返回值:** 6220 6221| 类型 | 说明 | 6222| ------------------- | --------------------------------------- | 6223| Promise<void> | 返回供closeCustomDialog使用的对话框id。 | 6224 6225**错误码:** 6226 6227以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6228 6229| 错误码ID | 错误信息 | 6230| -------- | ------------------------------------------------------------ | 6231| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6232| 100001 | Internal error. | 6233 6234### closeCustomDialog<sup>12+</sup> 6235 6236closeCustomDialog(dialogId: number): void 6237 6238关闭自定义弹窗。 6239 6240**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6241 6242**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6243 6244**参数:** 6245 6246| 参数名 | 类型 | 必填 | 说明 | 6247| -------- | ------ | ---- | -------------------------------- | 6248| dialogId | number | 是 | openCustomDialog返回的对话框id。 | 6249 6250**错误码:** 6251 6252以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6253 6254| 错误码ID | 错误信息 | 6255| -------- | ------------------------------------------------------------ | 6256| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6257| 100001 | Internal error. | 6258 6259**示例:** 6260 6261```ts 6262import { PromptAction } from '@kit.ArkUI'; 6263 6264@Entry 6265@Component 6266struct Index { 6267 promptAction: PromptAction = this.getUIContext().getPromptAction() 6268 private customDialogComponentId: number = 0 6269 6270 @Builder 6271 customDialogComponent() { 6272 Column() { 6273 Text('弹窗').fontSize(30) 6274 Row({ space: 50 }) { 6275 Button("确认").onClick(() => { 6276 this.promptAction.closeCustomDialog(this.customDialogComponentId) 6277 }) 6278 Button("取消").onClick(() => { 6279 this.promptAction.closeCustomDialog(this.customDialogComponentId) 6280 }) 6281 } 6282 }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween) 6283 } 6284 6285 build() { 6286 Row() { 6287 Column() { 6288 Button("click me") 6289 .onClick(() => { 6290 this.promptAction.openCustomDialog({ 6291 builder: () => { 6292 this.customDialogComponent() 6293 }, 6294 onWillDismiss: (dismissDialogAction: DismissDialogAction) => { 6295 console.info("reason" + JSON.stringify(dismissDialogAction.reason)) 6296 console.log("dialog onWillDismiss") 6297 if (dismissDialogAction.reason == DismissReason.PRESS_BACK) { 6298 dismissDialogAction.dismiss() 6299 } 6300 if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) { 6301 dismissDialogAction.dismiss() 6302 } 6303 } 6304 }).then((dialogId: number) => { 6305 this.customDialogComponentId = dialogId 6306 }) 6307 }) 6308 } 6309 .width('100%') 6310 .height('100%') 6311 } 6312 .height('100%') 6313 } 6314} 6315``` 6316 6317## DragController<sup>11+</sup> 6318以下API需先使用UIContext中的[getDragController()](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取UIContext实例,再通过此实例调用对应方法。 6319 6320### executeDrag<sup>11+</sup> 6321 6322executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo, callback: AsyncCallback<dragController.DragEventParam>): void 6323 6324主动发起拖拽能力,传入拖拽发起后跟手效果所拖拽的对象以及携带拖拽信息。通过回调返回拖拽事件结果。 6325 6326**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6327 6328**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6329 6330**参数:** 6331 6332| 参数名 | 类型 | 必填 | 说明 | 6333| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 6334| custom | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明) | 是 | 拖拽发起后跟手效果所拖拽的对象。 <br/> **说明:** <br/>不支持全局builder。如果builder中使用了[Image](arkui-ts/ts-basic-components-image.md)组件,应尽量开启同步加载,即配置Image的[syncLoad](arkui-ts/ts-basic-components-image.md#syncload8)为true。该builder只用于生成当次拖拽中显示的图片,builder的修改不会同步到当前正在拖拽的图片,对builder的修改需要在下一次拖拽时生效。 | 6335| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | 是 | 拖拽信息。 | 6336| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<[dragController.DragEventParam](js-apis-arkui-dragController.md#drageventparam12)> | 是 | 拖拽结束返回结果的回调<br/>- event:拖拽事件信息,仅包括拖拽结果。<br/>- extraParams:拖拽事件额外信息。 | 6337 6338**错误码:** 6339以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 6340 6341| 错误码ID | 错误信息 | 6342| -------- | ------------- | 6343| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6344| 100001 | Internal handling failed. | 6345 6346**示例:** 6347 6348```ts 6349import { dragController } from "@kit.ArkUI" 6350import { unifiedDataChannel } from '@kit.ArkData'; 6351 6352@Entry 6353@Component 6354struct DragControllerPage { 6355 @Builder DraggingBuilder() { 6356 Column() { 6357 Text("DraggingBuilder") 6358 } 6359 .width(100) 6360 .height(100) 6361 .backgroundColor(Color.Blue) 6362 } 6363 6364 build() { 6365 Column() { 6366 Button('touch to execute drag') 6367 .onTouch((event?:TouchEvent) => { 6368 if(event){ 6369 if (event.type == TouchType.Down) { 6370 let text = new unifiedDataChannel.Text() 6371 let unifiedData = new unifiedDataChannel.UnifiedData(text) 6372 6373 let dragInfo: dragController.DragInfo = { 6374 pointerId: 0, 6375 data: unifiedData, 6376 extraParams: '' 6377 } 6378 class tmp{ 6379 event:DragEvent|undefined = undefined 6380 extraParams:string = '' 6381 } 6382 let eve:tmp = new tmp() 6383 dragController.executeDrag(()=>{this.DraggingBuilder()}, dragInfo, (err, eve) => { 6384 if(eve.event){ 6385 if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) { 6386 // ... 6387 } else if (eve.event.getResult() == DragResult.DRAG_FAILED) { 6388 // ... 6389 } 6390 } 6391 }) 6392 } 6393 } 6394 }) 6395 } 6396 } 6397} 6398``` 6399 6400### executeDrag<sup>11+</sup> 6401 6402executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo): Promise<dragController.DragEventParam> 6403 6404主动发起拖拽能力,传入拖拽发起后跟手效果所拖拽的对象以及携带拖拽信息。通过Promise返回拖拽事件结果。 6405 6406**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6407 6408**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6409 6410**参数:** 6411 6412| 参数名 | 类型 | 必填 | 说明 | 6413| -------- | ------------------------------------------------------------ | ---- | -------------------------------- | 6414| custom | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明) | 是 | 拖拽发起后跟手效果所拖拽的对象。 | 6415| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | 是 | 拖拽信息。 | 6416 6417**返回值:** 6418 6419| 类型 | 说明 | 6420| ------------------------------------------------------------ | ------------------------------------------------------------ | 6421| Promise<[dragController.DragEventParam](js-apis-arkui-dragController.md#drageventparam12)> | 拖拽结束返回结果的回调<br/>- event:拖拽事件信息,仅包括拖拽结果。<br/>- extraParams:拖拽事件额外信息。 | 6422 6423**错误码:** 6424以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 6425 6426| 错误码ID | 错误信息 | 6427| -------- | ------------- | 6428| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6429| 100001 | Internal handling failed. | 6430 6431**示例:** 6432 6433```ts 6434import { dragController, componentSnapshot } from "@kit.ArkUI" 6435import { image } from '@kit.ImageKit'; 6436import { unifiedDataChannel } from '@kit.ArkData'; 6437 6438@Entry 6439@Component 6440struct DragControllerPage { 6441 @State pixmap: image.PixelMap|null = null 6442 6443 @Builder DraggingBuilder() { 6444 Column() { 6445 Text("DraggingBuilder") 6446 } 6447 .width(100) 6448 .height(100) 6449 .backgroundColor(Color.Blue) 6450 } 6451 6452 @Builder PixmapBuilder() { 6453 Column() { 6454 Text("PixmapBuilder") 6455 } 6456 .width(100) 6457 .height(100) 6458 .backgroundColor(Color.Blue) 6459 } 6460 6461 build() { 6462 Column() { 6463 Button('touch to execute drag') 6464 .onTouch((event?:TouchEvent) => { 6465 if(event){ 6466 if (event.type == TouchType.Down) { 6467 let text = new unifiedDataChannel.Text() 6468 let unifiedData = new unifiedDataChannel.UnifiedData(text) 6469 6470 let dragInfo: dragController.DragInfo = { 6471 pointerId: 0, 6472 data: unifiedData, 6473 extraParams: '' 6474 } 6475 let pb:CustomBuilder = ():void=>{this.PixmapBuilder()} 6476 componentSnapshot.createFromBuilder(pb).then((pix: image.PixelMap) => { 6477 this.pixmap = pix; 6478 let dragItemInfo: DragItemInfo = { 6479 pixelMap: this.pixmap, 6480 builder: ()=>{this.DraggingBuilder()}, 6481 extraInfo: "DragItemInfoTest" 6482 } 6483 6484 class tmp{ 6485 event:DragResult|undefined = undefined 6486 extraParams:string = '' 6487 } 6488 let eve:tmp = new tmp() 6489 dragController.executeDrag(dragItemInfo, dragInfo) 6490 .then((eve) => { 6491 if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) { 6492 // ... 6493 } else if (eve.event.getResult() == DragResult.DRAG_FAILED) { 6494 // ... 6495 } 6496 }) 6497 .catch((err:Error) => { 6498 }) 6499 }) 6500 } 6501 } 6502 }) 6503 } 6504 .width('100%') 6505 .height('100%') 6506 } 6507} 6508``` 6509 6510### createDragAction<sup>11+</sup> 6511 6512createDragAction(customArray: Array<CustomBuilder \| DragItemInfo>, dragInfo: dragController.DragInfo): dragController.DragAction 6513 6514创建拖拽的Action对象,需要显式指定拖拽背板图(可多个),以及拖拽的数据,跟手点等信息;当通过一个已创建的 Action 对象发起的拖拽未结束时,无法再次创建新的 Action 对象,接口会抛出异常;当Action对象的生命周期结束后,注册在该对象上的回调函数会失效,因此需要在一个尽量长的作用域下持有该对象,并在每次发起拖拽前通过createDragAction返回新的对象覆盖旧值。 6515 6516**说明:** 建议控制传递的拖拽背板数量,传递过多容易导致拖起的效率问题。 6517 6518**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6519 6520**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6521 6522**参数:** 6523 6524| 参数名 | 类型 | 必填 | 说明 | 6525| -------- | ------------------------------------------------------------ | ---- | -------------------------------- | 6526| customArray | Array<[CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明)> | 是 | 拖拽发起后跟手效果所拖拽的对象。 | 6527| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | 是 | 拖拽信息。 | 6528 6529**返回值:** 6530 6531| 类型 | 说明 | 6532| ------------------------------------------------------ | ------------------ | 6533| [dragController.DragAction](js-apis-arkui-dragController.md#dragaction11)| 创建拖拽Action对象,主要用于后面实现注册监听拖拽状态改变事件和启动拖拽服务。 | 6534 6535**错误码:** 6536以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 6537 6538| 错误码ID | 错误信息 | 6539| -------- | ------------- | 6540| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6541| 100001 | Internal handling failed. | 6542 6543**示例:** 65441.在EntryAbility.ets中获取UI上下文并保存至LocalStorage中。 6545```ts 6546import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 6547import { hilog } from '@kit.PerformanceAnalysisKit'; 6548import { window, UIContext } from '@kit.ArkUI'; 6549 6550let uiContext: UIContext; 6551let localStorage: LocalStorage = new LocalStorage('uiContext'); 6552 6553export default class EntryAbility extends UIAbility { 6554 storage: LocalStorage = localStorage; 6555 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 6556 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 6557 } 6558 6559 onDestroy(): void { 6560 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); 6561 } 6562 6563 onWindowStageCreate(windowStage: window.WindowStage): void { 6564 // Main window is created, set main page for this ability 6565 let storage: LocalStorage = new LocalStorage(); 6566 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 6567 6568 windowStage.loadContent('pages/Index', storage, (err, data) => { 6569 if (err.code) { 6570 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 6571 return; 6572 } 6573 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 6574 windowStage.getMainWindow((err, data) => 6575 { 6576 if (err.code) { 6577 console.error('Failed to abtain the main window. Cause:' + err.message); 6578 return; 6579 } 6580 let windowClass: window.Window = data; 6581 uiContext = windowClass.getUIContext(); 6582 this.storage.setOrCreate<UIContext>('uiContext', uiContext); 6583 // 获取UIContext实例 6584 }) 6585 }); 6586 } 6587 6588 onWindowStageDestroy(): void { 6589 // Main window is destroyed, release UI related resources 6590 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); 6591 } 6592 6593 onForeground(): void { 6594 // Ability has brought to foreground 6595 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); 6596 } 6597 6598 onBackground(): void { 6599 // Ability has back to background 6600 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); 6601 } 6602} 6603``` 66042.通过LocalStorage.getShared()获取上下文,进而获取DragController对象实施后续操作。 6605```ts 6606import { dragController, componentSnapshot, UIContext, DragController } from "@kit.ArkUI" 6607import { image } from '@kit.ImageKit'; 6608import { unifiedDataChannel } from '@kit.ArkData'; 6609 6610let storages = LocalStorage.getShared(); 6611 6612@Entry(storages) 6613@Component 6614struct DragControllerPage { 6615 @State pixmap: image.PixelMap|null = null 6616 private dragAction: dragController.DragAction|null = null; 6617 customBuilders:Array<CustomBuilder | DragItemInfo> = new Array<CustomBuilder | DragItemInfo>(); 6618 @Builder DraggingBuilder() { 6619 Column() { 6620 Text("DraggingBuilder") 6621 } 6622 .width(100) 6623 .height(100) 6624 .backgroundColor(Color.Blue) 6625 } 6626 6627 build() { 6628 Column() { 6629 6630 Column() { 6631 Text("测试") 6632 } 6633 .width(100) 6634 .height(100) 6635 .backgroundColor(Color.Red) 6636 6637 Button('多对象dragAction customBuilder拖拽').onTouch((event?:TouchEvent) => { 6638 if(event){ 6639 if (event.type == TouchType.Down) { 6640 console.info("muti drag Down by listener"); 6641 this.customBuilders.push(()=>{this.DraggingBuilder()}); 6642 this.customBuilders.push(()=>{this.DraggingBuilder()}); 6643 this.customBuilders.push(()=>{this.DraggingBuilder()}); 6644 let text = new unifiedDataChannel.Text() 6645 let unifiedData = new unifiedDataChannel.UnifiedData(text) 6646 let dragInfo: dragController.DragInfo = { 6647 pointerId: 0, 6648 data: unifiedData, 6649 extraParams: '' 6650 } 6651 try{ 6652 let uiContext: UIContext = storages.get<UIContext>('uiContext') as UIContext; 6653 this.dragAction = uiContext.getDragController().createDragAction(this.customBuilders, dragInfo) 6654 if(!this.dragAction){ 6655 console.info("listener dragAction is null"); 6656 return 6657 } 6658 this.dragAction.on('statusChange', (dragAndDropInfo)=>{ 6659 if (dragAndDropInfo.status == dragController.DragStatus.STARTED) { 6660 console.info("drag has start"); 6661 } else if (dragAndDropInfo.status == dragController.DragStatus.ENDED){ 6662 console.info("drag has end"); 6663 if (!this.dragAction) { 6664 return 6665 } 6666 this.customBuilders.splice(0, this.customBuilders.length) 6667 this.dragAction.off('statusChange') 6668 } 6669 }) 6670 this.dragAction.startDrag().then(()=>{}).catch((err:Error)=>{ 6671 console.error("start drag Error:" + err.message); 6672 }) 6673 } catch(err) { 6674 console.error("create dragAction Error:" + err.message); 6675 } 6676 } 6677 } 6678 }).margin({top:20}) 6679 } 6680 } 6681} 6682``` 6683 6684### getDragPreview<sup>11+</sup> 6685 6686getDragPreview(): dragController.DragPreview 6687 6688返回一个代表拖拽背板的对象。 6689 6690**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6691 6692**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6693 6694**返回值:** 6695 6696| 类型 | 说明 | 6697| ------------------------------------------------------------ | ------------------------------------------------------------ | 6698| [dragController.DragPreview](js-apis-arkui-dragController.md#dragpreview11) | 一个代表拖拽背板的对象,提供背板样式设置的接口,在OnDrop和OnDragEnd回调中使用不生效。 | 6699 6700**错误码:** 通用错误码请参考[通用错误码说明文档](../errorcode-universal.md)。 6701 6702**示例:** 6703 6704请参考[animate](js-apis-arkui-dragController.md#animate11) 6705 6706### setDragEventStrictReportingEnabled<sup>12+</sup> 6707 6708setDragEventStrictReportingEnabled(enable: boolean): void 6709 6710当目标从父组件拖拽到子组件时,通过该方法设置是否会触发父组件的onDragLeave的回调。 6711 6712**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6713 6714**系统能力:** : SystemCapability.ArkUI.ArkUI.Full 6715 6716**参数:** 6717 6718| 参数名 | 类型 | 必填 | 说明 | 6719| ------ | ------- | ---- | ------------------------------------------------------------ | 6720| enable | boolean | 是 | 将目标从父组件拖拽到子组件时,是否会触发父组件的onDragLeave的回调。true表示触发父组件的onDragLeave的回调,false表示不触发。 | 6721 6722**示例:** 6723 6724```ts 6725import { UIAbility } from '@kit.AbilityKit'; 6726import { window, UIContext } from '@kit.ArkUI'; 6727 6728 export default class EntryAbility extends UIAbility { 6729 onWindowStageCreate(windowStage: window.WindowStage): void { 6730 windowStage.loadContent('pages/Index', (err, data) => { 6731 if (err.code) { 6732 return; 6733 } 6734 windowStage.getMainWindow((err, data) => { 6735 if (err.code) { 6736 return; 6737 } 6738 let windowClass: window.Window = data; 6739 let uiContext: UIContext = windowClass.getUIContext(); 6740 uiContext.getDragController().setDragEventStrictReportingEnabled(true); 6741 }); 6742 }); 6743 } 6744} 6745``` 6746### cancelDataLoading<sup>15+</sup> 6747 6748cancelDataLoading(key: string): void 6749 6750当使用[startDataLoading](arkui-ts/ts-universal-events-drag-drop.md#dragevent7)获取拖拽数据时,可调用该接口取消数据传输。 6751 6752**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 6753 6754**系统能力:** : SystemCapability.ArkUI.ArkUI.Full 6755 6756**参数:** 6757 6758| 参数名 | 类型 | 必填 | 说明 | 6759| ------ | ------- | ---- | ------------------------------------------------------------ | 6760| key | string | 是 | 拖拽数据的标识,用于区分每次拖拽。key可通过startDataLoading接口获取。 | 6761 6762**错误码:** 6763 6764以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[拖拽事件错误码](./errorcode-drag-event.md)。 6765 6766| 错误码ID | 错误信息 | 6767| -------- | ------------------------------------------------------------ | 6768| 401 | Parameter error. | 6769| 190004 | Operation failed. | 6770 6771## OverlayManager<sup>12+</sup> 6772 6773以下API需先使用UIContext中的[getOverlayManager()](#getoverlaymanager12)方法获取到OverlayManager对象,再通过该对象调用对应方法。 6774> **说明:** 6775> 6776> OverlayManager上节点的层级在Page页面层级之上,在Dialog、Popup、Menu、BindSheet、BindContentCover和Toast等之下。 6777> 6778> OverlayManager上节点安全区域内外的绘制方式与Page一致,键盘避让方式与Page一致。 6779> 6780> 与OverlayManager相关的属性推荐采用AppStorage来进行应用全局存储,以免切换页面后属性值发生变化从而导致业务错误。 6781 6782### addComponentContent<sup>12+</sup> 6783 6784addComponentContent(content: ComponentContent, index?: number): void 6785 6786在OverlayManager上新增指定节点。 6787 6788**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6789 6790**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6791 6792**参数:** 6793 6794| 参数名 | 类型 | 必填 | 说明 | 6795| ------- | ---------------------------------------- | ---- | ----------- | 6796| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是 | 在OverlayManager上新增指定节点上添加此content。 <br>**说明:** <br/> 新增的节点默认处于页面居中,按层级堆叠。| 6797| index | number | 否 | 新增节点在OverlayManager上的层级位置。<br>**说明:** <br/> 当index ≥ 0时,若index的值越大,则ComponentContent的层级越高;当多个ComponentContent的index相同时,若ComponentContent添加的时间越晚,则层级越高。<br/> 当index < 0、index = null或index = undefined时,ComponentContent默认添加至最高层。<br/>当同一个ComponentContent被添加多次时,只保留最后一次添加的ComponentContent。<br/> 6798 6799**示例:** 6800 6801```ts 6802import { ComponentContent, OverlayManager, router } from '@kit.ArkUI'; 6803 6804class Params { 6805 text: string = "" 6806 offset: Position 6807 constructor(text: string, offset: Position) { 6808 this.text = text 6809 this.offset = offset 6810 } 6811} 6812@Builder 6813function builderText(params: Params) { 6814 Column() { 6815 Text(params.text) 6816 .fontSize(30) 6817 .fontWeight(FontWeight.Bold) 6818 }.offset(params.offset) 6819} 6820 6821@Entry 6822@Component 6823struct OverlayExample { 6824 @State message: string = 'ComponentContent'; 6825 private uiContext: UIContext = this.getUIContext() 6826 private overlayNode: OverlayManager = this.uiContext.getOverlayManager() 6827 @StorageLink('contentArray') contentArray: ComponentContent<Params>[] = [] 6828 @StorageLink('componentContentIndex') componentContentIndex: number = 0 6829 @StorageLink('arrayIndex') arrayIndex: number = 0 6830 @StorageLink("componentOffset") componentOffset: Position = {x: 0, y: 80} 6831 6832 build() { 6833 Column() { 6834 Button("++componentContentIndex: " + this.componentContentIndex).onClick(()=>{ 6835 ++this.componentContentIndex 6836 }) 6837 Button("--componentContentIndex: " + this.componentContentIndex).onClick(()=>{ 6838 --this.componentContentIndex 6839 }) 6840 Button("增加ComponentContent" + this.contentArray.length).onClick(()=>{ 6841 let componentContent = new ComponentContent( 6842 this.uiContext, wrapBuilder<[Params]>(builderText), 6843 new Params(this.message + (this.contentArray.length), this.componentOffset) 6844 ) 6845 this.contentArray.push(componentContent) 6846 this.overlayNode.addComponentContent(componentContent, this.componentContentIndex) 6847 }) 6848 Button("++arrayIndex: " + this.arrayIndex).onClick(()=>{ 6849 ++this.arrayIndex 6850 }) 6851 Button("--arrayIndex: " + this.arrayIndex).onClick(()=>{ 6852 --this.arrayIndex 6853 }) 6854 Button("删除ComponentContent" + this.arrayIndex).onClick(()=>{ 6855 if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) { 6856 let componentContent = this.contentArray.splice(this.arrayIndex, 1) 6857 this.overlayNode.removeComponentContent(componentContent.pop()) 6858 } else { 6859 console.info("arrayIndex有误") 6860 } 6861 }) 6862 Button("显示ComponentContent" + this.arrayIndex).onClick(()=>{ 6863 if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) { 6864 let componentContent = this.contentArray[this.arrayIndex] 6865 this.overlayNode.showComponentContent(componentContent) 6866 } else { 6867 console.info("arrayIndex有误") 6868 } 6869 }) 6870 Button("隐藏ComponentContent" + this.arrayIndex).onClick(()=>{ 6871 if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) { 6872 let componentContent = this.contentArray[this.arrayIndex] 6873 this.overlayNode.hideComponentContent(componentContent) 6874 } else { 6875 console.info("arrayIndex有误") 6876 } 6877 }) 6878 Button("显示所有ComponentContent").onClick(()=>{ 6879 this.overlayNode.showAllComponentContents() 6880 }) 6881 Button("隐藏所有ComponentContent").onClick(()=>{ 6882 this.overlayNode.hideAllComponentContents() 6883 }) 6884 6885 Button("跳转页面").onClick(()=>{ 6886 router.pushUrl({ 6887 url: 'pages/Second' 6888 }) 6889 }) 6890 } 6891 .width('100%') 6892 .height('100%') 6893 } 6894} 6895``` 6896 6897### removeComponentContent<sup>12+</sup> 6898 6899removeComponentContent(content: ComponentContent): void 6900 6901在overlay上删除指定节点。 6902 6903**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6904 6905**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6906 6907**参数:** 6908 6909| 参数名 | 类型 | 必填 | 说明 | 6910| ------- | ---------------------------------------- | ---- | ----------- | 6911| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是 | 在OverlayManager上删除此content。 | 6912 6913**示例:** 6914 6915请参考[addComponentContent示例](#addcomponentcontent12) 6916 6917### showComponentContent<sup>12+</sup> 6918 6919showComponentContent(content: ComponentContent): void 6920 6921在OverlayManager上显示指定节点。 6922 6923**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6924 6925**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6926 6927**参数:** 6928 6929| 参数名 | 类型 | 必填 | 说明 | 6930| ------- | ---------------------------------------- | ---- | ----------- | 6931| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是 | 在OverlayManager上显示此content。| 6932 6933**示例:** 6934 6935请参考[addComponentContent示例](#addcomponentcontent12) 6936 6937### hideComponentContent<sup>12+</sup> 6938 6939hideComponentContent(content: ComponentContent): void 6940 6941在OverlayManager上隐藏指定节点。 6942 6943**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6944 6945**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6946 6947**参数:** 6948 6949| 参数名 | 类型 | 必填 | 说明 | 6950| ------- | ---------------------------------------- | ---- | ----------- | 6951| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是 | 在OverlayManager上隐藏此content。 | 6952 6953**示例:** 6954 6955请参考[addComponentContent示例](#addcomponentcontent12) 6956 6957### showAllComponentContents<sup>12+</sup> 6958 6959showAllComponentContents(): void 6960 6961显示OverlayManager上所有的ComponentContent。 6962 6963**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6964 6965**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6966 6967**示例:** 6968 6969请参考[addComponentContent示例](#addcomponentcontent12) 6970 6971### hideAllComponentContents<sup>12+</sup> 6972 6973hideAllComponentContents(): void 6974 6975隐藏OverlayManager上的所有ComponentContent。 6976 6977**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6978 6979**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6980 6981**示例:** 6982 6983请参考[addComponentContent示例](#addcomponentcontent12) 6984 6985## OverlayManagerOptions<sup>15+</sup> 6986 6987初始化[OverlayManager](#overlaymanager12)时所用参数。 6988 6989**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 6990 6991**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6992 6993| 名称 | 类型 | 必填 | 说明 | 6994| --------------- | ---------------------- | ------------ | --------------------- | 6995| renderRootOverlay | boolean | 否 | 是否渲染overlay根节点,true表示渲染overlay根节点,false表示不渲染overlay根节点,默认值为true。| 6996 6997## AtomicServiceBar<sup>11+</sup> 6998 6999以下接口需要先使用UIContext中的[getAtomicServiceBar](#getatomicservicebar11)方法获取到AtomicServiceBar对象,再通过该对象调用对应方法。 7000> **说明:** 7001> 7002> 从API version 12开始原子化服务menuBar样式变更,以下接口将失效。 7003 7004### setVisible<sup>11+</sup> 7005 7006setVisible(visible: boolean): void 7007 7008通过该方法设置原子化服务menuBar是否可见。 7009> **说明:** 7010> 7011> 从API version 12开始原子化服务menuBar样式变更,menuBar默认隐藏,变为悬浮按钮,通过该接口无法改变menuBar的可见性。 7012 7013**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 7014 7015**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7016 7017**参数:** 7018 7019| 参数名 | 类型 | 必填 | 说明 | 7020| ------- | ------- | ------- | ------- | 7021| visible | boolean | 是 | 原子化服务menuBar是否可见。| 7022 7023 7024**示例:** 7025 7026```ts 7027import {UIContext, AtomicServiceBar, window } from '@kit.ArkUI'; 7028import { hilog } from '@kit.PerformanceAnalysisKit'; 7029 7030onWindowStageCreate(windowStage: window.WindowStage) { 7031 // Main window is created, set main page for this ability 7032 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 7033 windowStage.loadContent('pages/Index', (err, data) => { 7034 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 7035 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 7036 if (atomicServiceBar != undefined) { 7037 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 7038 atomicServiceBar.setVisible(false); 7039 } else { 7040 hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 7041 } 7042 }); 7043} 7044``` 7045 7046### setBackgroundColor<sup>11+</sup> 7047 7048setBackgroundColor(color:Nullable<Color | number | string>): void 7049 7050通过该方法设置原子化服务menuBar的背景颜色。 7051> **说明:** 7052> 7053> 从API version 12开始原子化服务menuBar样式变更,menuBar的背景默认隐藏,通过该接口无法改变menuBar的背景颜色。 7054 7055**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7056 7057**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7058 7059**参数:** 7060 7061| 参数名 | 类型 | 必填 | 说明 | 7062| ------ | ------ | ------ | ------ | 7063| color | Nullable\<[Color](arkui-ts/ts-appendix-enums.md#color) \| number \| string> | 是 | 通过该方法设置原子化服务menuBar的背景颜色,undefined代表使用默认颜色。number为HEX格式颜色,支持rgb或者argb,示例:0xffffff。string为rgb或者argb格式颜色,示例:'#ffffff'。| 7064 7065**示例:** 7066 7067```ts 7068import {UIContext, AtomicServiceBar,window } from '@kit.ArkUI'; 7069import { hilog } from '@kit.PerformanceAnalysisKit'; 7070onWindowStageCreate(windowStage: window.WindowStage) { 7071 // Main window is created, set main page for this ability 7072 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 7073 windowStage.loadContent('pages/Index', (err, data) => { 7074 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 7075 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 7076 if (atomicServiceBar != undefined) { 7077 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 7078 atomicServiceBar.setBackgroundColor(0x88888888); 7079 } else { 7080 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 7081 } 7082 }); 7083} 7084``` 7085 7086### setTitleContent<sup>11+</sup> 7087 7088setTitleContent(content:string): void 7089 7090通过该方法设置原子化服务menuBar的标题内容。 7091> **说明:** 7092> 7093> 从API version 12开始原子化服务menuBar样式变更,menuBar的标题默认隐藏,通过该接口无法改变menuBar的标题内容。 7094 7095**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7096 7097**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7098 7099**参数:** 7100 7101|参数名|类型|必填|说明 | 7102| ------- | ------- | ------- | ------- | 7103| content | string | 是 | 原子化服务menuBar中的标题内容。| 7104 7105**示例:** 7106 7107```ts 7108import {UIContext, AtomicServiceBar,window } from '@kit.ArkUI'; 7109import { hilog } from '@kit.PerformanceAnalysisKit'; 7110 7111onWindowStageCreate(windowStage: window.WindowStage) { 7112 // Main window is created, set main page for this ability 7113 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 7114 windowStage.loadContent('pages/Index', (err, data) => { 7115 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 7116 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 7117 if (atomicServiceBar != undefined) { 7118 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 7119 atomicServiceBar.setTitleContent('text2'); 7120 } else { 7121 hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 7122 } 7123 }); 7124} 7125``` 7126 7127### setTitleFontStyle<sup>11+</sup> 7128 7129setTitleFontStyle(font:FontStyle):void 7130 7131通过该方法设置原子化服务menuBar的字体样式。 7132> **说明:** 7133> 7134> 从API version 12开始原子化服务menuBar样式变更,menuBar的标题默认隐藏,通过该接口无法改变menuBar的字体样式。 7135 7136**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7137 7138**系统能力:** SystemCapability.ArkUI.ArkUI.Full。 7139 7140**参数:** 7141 7142| 参数名 | 类型 | 必填 | 说明 | 7143| ------ | ------ | ------ | ------ | 7144| font | [FontStyle](arkui-ts/ts-appendix-enums.md#fontstyle) | 是 | 原子化服务menuBar中的字体样式。 | 7145 7146**示例:** 7147 7148```ts 7149import {UIContext, Font, AtomicServiceBar } from '@kit.ArkUI'; 7150import { hilog } from '@kit.PerformanceAnalysisKit'; 7151 7152onWindowStageCreate(windowStage: window.WindowStage) { 7153 // Main window is created, set main page for this ability 7154 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 7155 windowStage.loadContent('pages/Index', (err, data) => { 7156 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 7157 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 7158 if (atomicServiceBar != undefined) { 7159 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 7160 atomicServiceBar.setTitleFontStyle(FontStyle.Normal); 7161 } else { 7162 hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 7163 } 7164 }); 7165} 7166``` 7167 7168### setIconColor<sup>11+</sup> 7169 7170setIconColor(color:Nullable<Color | number | string>): void 7171 7172通过该方法设置原子化服务图标的颜色。 7173> **说明:** 7174> 7175> 从API version 12开始原子化服务menuBar样式变更,menuBar默认隐藏,悬浮按钮图标不予用户设置,通过该接口无法改变menuBar的图标颜色。 7176 7177**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7178 7179**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7180 7181**参数:** 7182 7183| 参数名 | 类型 | 必填 | 说明 | 7184| ------- | ------- | ------- | ------- | 7185| color | Nullable\<[Color](arkui-ts/ts-appendix-enums.md#color) \| number \| string> | 是 | 原子化服务图标的颜色,undefined代表使用默认颜色。 | 7186 7187 7188**示例:** 7189 7190```ts 7191import {UIContext, Font, window } from '@kit.ArkUI'; 7192import { hilog } from '@kit.PerformanceAnalysisKit'; 7193 7194onWindowStageCreate(windowStage: window.WindowStage) { 7195 // Main window is created, set main page for this ability 7196 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 7197 windowStage.loadContent('pages/Index', (err, data) => { 7198 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 7199 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 7200 if (atomicServiceBar != undefined) { 7201 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 7202 atomicServiceBar.setIconColor(0x12345678); 7203 } else { 7204 hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 7205 } 7206 }); 7207} 7208``` 7209 7210### getBarRect<sup>15+</sup> 7211 7212getBarRect(): Frame 7213 7214获取原子化服务menuBar相对窗口的布局信息。 7215> **说明:** 7216> 7217> 布局信息包含了原子化服务menuBar的左右margin。 7218 7219**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 7220 7221**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7222 7223**返回值:** 7224 7225| 类型 | 说明 | 7226| ----------------- | ------------- | 7227| [Frame](./js-apis-arkui-graphics.md#frame) | 原子化服务menuBar的大小和位置。 | 7228 7229**示例:** 7230 7231```ts 7232import { AtomicServiceBar } from '@kit.ArkUI'; 7233import { hilog } from '@kit.PerformanceAnalysisKit'; 7234@Entry 7235@Component 7236struct Index { 7237 build() { 7238 Button("getBarRect") 7239 .onClick(() => { 7240 let uiContext: UIContext = this.getUIContext(); 7241 let currentBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 7242 if (currentBar != undefined) { 7243 let rect = currentBar.getBarRect(); 7244 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully. x:' + 7245 rect.x + ' y:' + rect.y + ' width:' + rect.width + ' height:' + rect.height); 7246 } else { 7247 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar failed.'); 7248 } 7249 }) 7250 } 7251} 7252``` 7253 7254## KeyboardAvoidMode<sup>11+</sup> 7255 7256配置键盘避让时页面的避让模式。 7257 7258**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7259 7260| 名称 | 值 | 说明 | 7261| ------ | ---- | ---------- | 7262| OFFSET | 0 | 上抬模式。 <br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。| 7263| RESIZE | 1 | 压缩模式。 <br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。| 7264| OFFSET_WITH_CARET<sup>14+</sup> | 2 | 上抬模式,输入框光标位置发生变化时候也会触发避让。<br/>**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。| 7265| RESIZE_WITH_CARET<sup>14+</sup> | 3 | 压缩模式,输入框光标位置发生变化时候也会触发避让。<br/>**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。| 7266| NONE<sup>14+</sup> | 4 | 不避让键盘。<br/>**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。| 7267 7268 7269## FocusController<sup>12+</sup> 7270以下API需先使用UIContext中的[getFocusController()](js-apis-arkui-UIContext.md#getFocusController12)方法获取UIContext实例,再通过此实例调用对应方法。 7271 7272### clearFocus<sup>12+</sup> 7273 7274clearFocus(): void 7275 7276清除焦点,将焦点强制转移到页面根容器节点,焦点链路上其他节点失焦。 7277 7278**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7279 7280**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7281 7282**示例:** 7283 7284```ts 7285@Entry 7286@Component 7287struct ClearFocusExample { 7288 @State inputValue: string = '' 7289 @State btColor: Color = Color.Blue 7290 7291 build() { 7292 Column({ space: 20 }) { 7293 Column({ space: 5 }) { 7294 Button('button1') 7295 .width(200) 7296 .height(70) 7297 .fontColor(Color.White) 7298 .focusOnTouch(true) 7299 .backgroundColor(Color.Blue) 7300 Button('button2') 7301 .width(200) 7302 .height(70) 7303 .fontColor(Color.White) 7304 .focusOnTouch(true) 7305 .backgroundColor(this.btColor) 7306 .defaultFocus(true) 7307 .onFocus(() => { 7308 this.btColor = Color.Red 7309 }) 7310 .onBlur(() => { 7311 this.btColor = Color.Blue 7312 }) 7313 Button('clearFocus') 7314 .width(200) 7315 .height(70) 7316 .fontColor(Color.White) 7317 .backgroundColor(Color.Blue) 7318 .onClick(() => { 7319 this.getUIContext().getFocusController().clearFocus() 7320 }) 7321 } 7322 } 7323 .width('100%') 7324 .height('100%') 7325 } 7326} 7327``` 7328 7329### requestFocus<sup>12+</sup> 7330 7331requestFocus(key: string): void 7332 7333通过组件的id将焦点转移到组件树对应的实体节点。当前帧生效。 7334 7335**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7336 7337**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7338 7339**参数:** 7340 7341| 参数名 | 类型 | 必填 | 说明 | 7342| ------- | ------- | ------- | ------- | 7343| key | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。| 7344 7345**错误码:** 7346 7347以下错误码的详细介绍请参见[焦点错误码](errorcode-focus.md)。 7348 7349| 错误码ID | 错误信息 | 7350| -------- | ----------------------------------------------- | 7351| 150001 | the component cannot be focused. | 7352| 150002 | This component has an unfocusable ancestor. | 7353| 150003 | the component is not on tree or does not exist. | 7354 7355**示例:** 7356 7357```ts 7358@Entry 7359@Component 7360struct RequestExample { 7361 @State btColor: Color = Color.Blue 7362 7363 build() { 7364 Column({ space: 20 }) { 7365 Column({ space: 5 }) { 7366 Button('Button') 7367 .width(200) 7368 .height(70) 7369 .fontColor(Color.White) 7370 .focusOnTouch(true) 7371 .backgroundColor(this.btColor) 7372 .onFocus(() => { 7373 this.btColor = Color.Red 7374 }) 7375 .onBlur(() => { 7376 this.btColor = Color.Blue 7377 }) 7378 .id("testButton") 7379 7380 Divider() 7381 .vertical(false) 7382 .width("80%") 7383 .backgroundColor(Color.Black) 7384 .height(10) 7385 7386 Button('requestFocus') 7387 .width(200) 7388 .height(70) 7389 .onClick(() => { 7390 this.getUIContext().getFocusController().requestFocus("testButton") 7391 }) 7392 7393 Button('requestFocus fail') 7394 .width(200) 7395 .height(70) 7396 .onClick(() => { 7397 try { 7398 this.getUIContext().getFocusController().requestFocus("eee") 7399 } catch (error) { 7400 console.error('requestFocus failed code is ' + error.code + ' message is ' + error.message) 7401 } 7402 }) 7403 } 7404 } 7405 .width('100%') 7406 .height('100%') 7407 } 7408} 7409``` 7410 7411### activate<sup>14+</sup> 7412 7413activate(isActive: boolean, autoInactive?: boolean): void 7414 7415设置当前界面的[焦点激活态](../../ui/arkts-common-events-focus-event.md)。 7416 7417**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。 7418 7419**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7420 7421**参数:** 7422 7423| 参数名 | 类型 | 必填 | 说明 | 7424| ------- | ------- | ------- | ------- | 7425| isActive| boolean| 是 | 设置是否进入/退出焦点激活态。 | 7426| autoInactive | boolean | 否 | 设置焦点激活态退出逻辑。为true时,会自动在触摸事件、鼠标事件触发时退出,为false时,仅受开发者API控制。| 7427 7428```ts 7429// 该示例表示在页面加载完成时进入焦点激活态,可按方向键在button间走焦 7430@Entry 7431@Component 7432struct ActivateExample { 7433 aboutToAppear() { 7434 this.getUIContext().getFocusController().activate(true, false) 7435 } 7436 7437 aboutToDisappear() { 7438 this.getUIContext().getFocusController().activate(false) 7439 } 7440 7441 build() { 7442 Row() { 7443 Button('Button1') 7444 .width(200) 7445 .height(70) 7446 .defaultFocus(true) 7447 7448 Button('Button2') 7449 .width(200) 7450 .height(70) 7451 7452 Button('Button3') 7453 .width(200) 7454 .height(70) 7455 } 7456 .padding(10) 7457 .justifyContent(FlexAlign.SpaceBetween) 7458 .width(800) 7459 } 7460} 7461``` 7462 7463### setAutoFocusTransfer<sup>14+</sup> 7464 7465setAutoFocusTransfer(isAutoFocusTransfer: boolean): void; 7466 7467设置页面切换时,新的页面是否需要主动获取焦点。 7468 7469**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。 7470 7471**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7472 7473**参数:** 7474 7475| 参数名 | 类型 | 必填 | 说明 | 7476| ------- | ------- | ------- | ------- | 7477| isAutoFocusTransfer | boolean| 是 | 设置页面切换时,新的页面是否需要主动获取焦点,例如[Router](js-apis-router.md#routerpushurl9)、[Navigation](arkui-ts/ts-basic-components-navigation.md#navigation)、[Menu](arkui-ts/ts-basic-components-menu.md#menu)、[Dialog](arkui-ts/ohos-arkui-advanced-Dialog.md)、[Popup](arkui-ts/ohos-arkui-advanced-Popup.md#popup)等。true表示需要主动获取焦点,false表示不需要主动获取焦点。默认值为true。 | 7478 7479```ts 7480@CustomDialog 7481struct CustomDialogExample { 7482 controller?: CustomDialogController 7483 build() { 7484 Column() { 7485 Text('这是自定义弹窗') 7486 .fontSize(30) 7487 .height(100) 7488 Text('弹窗不能主动获取焦点') 7489 .fontSize(20) 7490 .height(100) 7491 Button('点我关闭弹窗') 7492 .onClick(() => { 7493 if (this.controller != undefined) { 7494 this.getUIContext().getFocusController().setAutoFocusTransfer(true) 7495 this.controller.close() 7496 } 7497 }) 7498 .margin(20) 7499 } 7500 } 7501} 7502@Entry 7503@Component 7504struct CustomDialogUser { 7505 dialogController: CustomDialogController | null = new CustomDialogController({ 7506 builder: CustomDialogExample({ 7507 }), 7508 }) 7509 aboutToDisappear() { 7510 this.dialogController = null 7511 } 7512 7513 build() { 7514 Column() { 7515 Button('click me') 7516 .onClick(() => { 7517 if (this.dialogController != null) { 7518 this.getUIContext().getFocusController().setAutoFocusTransfer(false) 7519 this.dialogController.open() 7520 } 7521 }).backgroundColor(0x317aff) 7522 }.width('100%').margin({ top: 5 }) 7523 } 7524} 7525``` 7526 7527### setKeyProcessingMode<sup>15+</sup> 7528 7529setKeyProcessingMode(mode: KeyProcessingMode): void 7530 7531设置按键事件处理的优先级。 7532 7533**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 7534 7535**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7536 7537**参数:** 7538 7539| 参数名 | 类型 | 必填 | 说明 | 7540| ------- | ------- | ------- | ------- | 7541| mode | [KeyProcessingMode](./arkui-ts/ts-universal-attributes-focus.md#keyprocessingmode15)| 是 | 按键处理模式。 | 7542 7543```ts 7544 7545// 该示例演示了在页面加载完成后设置走焦类型的实现方式。 7546@Entry 7547@Component 7548struct Index { 7549 7550 aboutToAppear() { 7551 this.getUIContext().getFocusController().setKeyProcessingMode(KeyProcessingMode.ANCESTOR_EVENT) 7552 } 7553 7554 build() { 7555 Row() { 7556 Row() { 7557 Button('Button1').id('Button1').onKeyEvent((event) => { 7558 console.log("Button1"); 7559 return true 7560 }) 7561 Button('Button2').id('Button2').onKeyEvent((event) => { 7562 console.log("Button2"); 7563 return true 7564 }) 7565 } 7566 .width('100%') 7567 .height('100%') 7568 .id('Row1') 7569 .onKeyEventDispatch((event) => { 7570 let context = this.getUIContext(); 7571 context.getFocusController().requestFocus('Button1'); 7572 return context.dispatchKeyEvent('Button1', event); 7573 }) 7574 } 7575 .height('100%') 7576 .width('100%') 7577 .onKeyEventDispatch((event) => { 7578 if (event.type == KeyType.Down) { 7579 let context = this.getUIContext(); 7580 context.getFocusController().requestFocus('Row1'); 7581 return context.dispatchKeyEvent('Row1', event); 7582 } 7583 return true; 7584 }) 7585 } 7586} 7587``` 7588 7589## PointerStyle<sup>12+</sup> 7590 7591type PointerStyle = pointer.PointerStyle 7592 7593光标样式。 7594 7595**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7596 7597**系统能力:** SystemCapability.MultimodalInput.Input.Pointer 7598 7599|类型|说明| 7600| -- | -- | 7601|[pointer.PointerStyle](../apis-input-kit/js-apis-pointer.md#pointerstyle) |光标样式。| 7602 7603## CursorController<sup>12+</sup> 7604以下API需先使用UIContext中的[getCursorController()](js-apis-arkui-UIContext.md#getcursorcontroller12)方法获取CursorController实例,再通过此实例调用对应方法。 7605 7606### restoreDefault<sup>12+</sup> 7607 7608restoreDefault(): void 7609 7610恢复默认的光标样式 7611 7612**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7613 7614**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7615 7616**示例:** 7617当光标移出绿框时,通过CursorController的restoreDefault方法恢复默认光标样式 7618 7619```ts 7620import { pointer } from '@kit.InputKit'; 7621import { UIContext, CursorController } from '@kit.ArkUI'; 7622 7623@Entry 7624@Component 7625struct CursorControlExample { 7626 @State text: string = '' 7627 cursorCustom: CursorController = this.getUIContext().getCursorController(); 7628 7629 build() { 7630 Column() { 7631 Row().height(200).width(200).backgroundColor(Color.Green).position({x: 150 ,y:70}) 7632 .onHover((flag) => { 7633 if (flag) { 7634 this.cursorCustom.setCursor(pointer.PointerStyle.EAST) 7635 } else { 7636 console.info("restoreDefault"); 7637 this.cursorCustom.restoreDefault(); 7638 } 7639 }) 7640 }.width('100%') 7641 } 7642} 7643``` 7644 7645 7646### setCursor<sup>12+</sup> 7647 7648setCursor(value: PointerStyle): void 7649 7650更改当前的鼠标光标样式 7651 7652**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7653 7654**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7655 7656**参数:** 7657 7658| 参数名 | 类型 | 必填 | 说明 | 7659| ------- | ---------------------------------------- | ---- | ------- | 7660| value | [PointerStyle](#pointerstyle12) | 是 | 光标样式 | 7661 7662**示例:** 7663当光标进入蓝框时,通过CursorController的setCursor方法修改光标样式为PointerStyle.WEST 7664 7665```ts 7666import { pointer } from '@kit.InputKit'; 7667import { UIContext, CursorController } from '@kit.ArkUI'; 7668 7669@Entry 7670@Component 7671struct CursorControlExample { 7672 @State text: string = '' 7673 cursorCustom: CursorController = this.getUIContext().getCursorController(); 7674 7675 build() { 7676 Column() { 7677 Row().height(200).width(200).backgroundColor(Color.Blue).position({x: 100 ,y:70}) 7678 .onHover((flag) => { 7679 if (flag) { 7680 this.cursorCustom.setCursor(pointer.PointerStyle.WEST) 7681 } else { 7682 this.cursorCustom.restoreDefault(); 7683 } 7684 }) 7685 }.width('100%') 7686 } 7687} 7688``` 7689 7690 7691## ContextMenuController<sup>12+</sup> 7692以下API需先使用UIContext中的[getContextMenuController()](js-apis-arkui-UIContext.md#getcontextmenucontroller12)方法获取ContextMenuController实例,再通过此实例调用对应方法。 7693 7694### close<sup>12+</sup> 7695 7696close(): void 7697 7698关闭菜单 7699 7700**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7701 7702**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7703 7704**示例:** 7705通过定时器触发,调用ContextMenuController的close方法关闭菜单 7706 7707```ts 7708import { ContextMenuController } from '@kit.ArkUI'; 7709 7710@Entry 7711@Component 7712struct Index { 7713 menu: ContextMenuController = this.getUIContext().getContextMenuController(); 7714 7715 @Builder MenuBuilder() { 7716 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 7717 Button('Test ContextMenu1 Close') 7718 Divider().strokeWidth(2).margin(5).color(Color.Black) 7719 Button('Test ContextMenu2') 7720 Divider().strokeWidth(2).margin(5).color(Color.Black) 7721 Button('Test ContextMenu3') 7722 } 7723 .width(200) 7724 .height(160) 7725 } 7726 7727 build() { 7728 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 7729 Button("启动定时器").onClick(()=> 7730 { 7731 setTimeout(() => { 7732 this.menu.close(); 7733 }, 10000); 7734 }) 7735 7736 Column() { 7737 Text("Test ContextMenu close") 7738 .fontSize(20) 7739 .width('100%') 7740 .height(500) 7741 .backgroundColor(0xAFEEEE) 7742 .textAlign(TextAlign.Center) 7743 } 7744 .bindContextMenu(this.MenuBuilder, ResponseType.LongPress) 7745 } 7746 .width('100%') 7747 .height('100%') 7748 } 7749} 7750``` 7751 7752 7753 7754## MeasureUtils<sup>12+</sup> 7755 7756以下API需先使用UIContext中的[getMeasureUtils()](js-apis-arkui-UIContext.md#getmeasureutils12)方法获取MeasureUtils实例,再通过此实例调用对应方法。 7757 7758### measureText<sup>12+</sup> 7759 7760measureText(options: MeasureOptions): number 7761 7762计算指定文本单行布局下的宽度。 7763 7764**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7765 7766**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7767 7768**参数:** 7769 7770| 参数名 | 类型 | 必填 | 说明 | 7771| ------- | ------------------------------- | ---- | --------- | 7772| options | [MeasureOptions](js-apis-measure.md#measureoptions) | 是 | 被计算文本描述信息。 | 7773 7774**返回值:** 7775 7776| 类型 | 说明 | 7777| ------------ | --------- | 7778| number | 文本宽度。<br/>**说明:**<br/>单位px。 | 7779 7780 7781**示例:** 7782通过MeasureUtils的measureText方法获取"Hello World"文字的宽度。 7783 7784```ts 7785import { MeasureUtils } from '@kit.ArkUI'; 7786 7787@Entry 7788@Component 7789struct Index { 7790 @State uiContext: UIContext = this.getUIContext(); 7791 @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils(); 7792 @State textWidth: number = this.uiContextMeasure.measureText({ 7793 textContent: "Hello World", 7794 fontSize: '50px' 7795 }) 7796 7797 build() { 7798 Row() { 7799 Column() { 7800 Text(`The width of 'Hello World': ${this.textWidth}`) 7801 } 7802 .width('100%') 7803 } 7804 .height('100%') 7805 } 7806} 7807``` 7808 7809### measureTextSize<sup>12+</sup> 7810 7811measureTextSize(options: MeasureOptions): SizeOptions 7812 7813计算指定文本单行布局下的宽度和高度。 7814 7815**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7816 7817**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7818 7819**参数:** 7820 7821| 参数名 | 类型 | 必填 | 说明 | 7822| ------- | ------------------------------- | ---- | --------- | 7823| options | [MeasureOptions](js-apis-measure.md#measureoptions) | 是 | 被计算文本描述信息。 | 7824 7825**返回值:** 7826 7827| 类型 | 说明 | 7828| ------------ | --------- | 7829| [SizeOption](arkui-ts/ts-types.md#sizeoptions) | 返回文本所占布局宽度和高度。<br/>**说明:**<br/> 文本宽度以及高度返回值单位均为px。 | 7830 7831 7832**示例:** 7833通过MeasureUtils的measureTextSize方法获取"Hello World"文字的宽度和高度 7834 7835```ts 7836import { MeasureUtils } from '@kit.ArkUI'; 7837 7838@Entry 7839@Component 7840struct Index { 7841 @State uiContext: UIContext = this.getUIContext(); 7842 @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils(); 7843 textSize : SizeOptions = this.uiContextMeasure.measureTextSize({ 7844 textContent: "Hello World", 7845 fontSize: '50px' 7846 }) 7847 build() { 7848 Row() { 7849 Column() { 7850 Text(`The width of 'Hello World': ${this.textSize.width}`) 7851 Text(`The height of 'Hello World': ${this.textSize.height}`) 7852 } 7853 .width('100%') 7854 } 7855 .height('100%') 7856 } 7857} 7858``` 7859 7860## ComponentSnapshot<sup>12+</sup> 7861 7862以下API需先使用UIContext中的[getComponentSnapshot()](js-apis-arkui-UIContext.md#getcomponentsnapshot12)方法获取ComponentSnapshot对象,再通过此实例调用对应方法。 7863 7864### get<sup>12+</sup> 7865 7866get(id: string, callback: AsyncCallback<image.PixelMap>, options?: componentSnapshot.SnapshotOptions): void 7867 7868获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过回调返回结果。 7869 7870> **说明:** 7871> 7872> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 7873 7874**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7875 7876**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7877 7878**参数:** 7879 7880| 参数名 | 类型 | 必填 | 说明 | 7881| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 7882| id | string | 是 | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识)。 | 7883| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | 是 | 截图返回结果的回调。 | 7884| options<sup>12+</sup> | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 7885 7886**错误码:** 7887 7888以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 7889 7890| 错误码ID | 错误信息 | 7891| -------- | ------------------------------------------------------------ | 7892| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7893| 100001 | Invalid ID. | 7894 7895**示例:** 7896 7897```ts 7898import { image } from '@kit.ImageKit'; 7899import { UIContext } from '@kit.ArkUI'; 7900 7901@Entry 7902@Component 7903struct SnapshotExample { 7904 @State pixmap: image.PixelMap | undefined = undefined 7905 uiContext: UIContext = this.getUIContext(); 7906 build() { 7907 Column() { 7908 Row() { 7909 Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5) 7910 Image($r('app.media.img')).autoResize(true).width(150).height(150).margin(5).id("root") 7911 } 7912 Button("click to generate UI snapshot") 7913 .onClick(() => { 7914 this.uiContext.getComponentSnapshot().get("root", (error: Error, pixmap: image.PixelMap) => { 7915 if (error) { 7916 console.error("error: " + JSON.stringify(error)) 7917 return; 7918 } 7919 this.pixmap = pixmap 7920 }, {scale : 2, waitUntilRenderFinished : true}) 7921 }).margin(10) 7922 } 7923 .width('100%') 7924 .height('100%') 7925 .alignItems(HorizontalAlign.Center) 7926 } 7927} 7928``` 7929 7930### get<sup>12+</sup> 7931 7932get(id: string, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap> 7933 7934获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过Promise返回结果。 7935 7936> **说明:** 7937> 7938> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 7939 7940**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7941 7942**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7943 7944**参数:** 7945 7946| 参数名 | 类型 | 必填 | 说明 | 7947| ------ | ------ | ---- | ------------------------------------------------------------ | 7948| id | string | 是 | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识)。 | 7949| options<sup>12+</sup> | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 7950 7951**返回值:** 7952 7953| 类型 | 说明 | 7954| ------------------------------------------------------------ | ---------------- | 7955| Promise<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | 截图返回的结果。 | 7956 7957**错误码:** 7958 7959以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 7960 7961| 错误码ID | 错误信息 | 7962| -------- | ------------------------------------------------------------ | 7963| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7964| 100001 | Invalid ID. | 7965 7966**示例:** 7967 7968```ts 7969import { image } from '@kit.ImageKit'; 7970import { UIContext } from '@kit.ArkUI'; 7971 7972@Entry 7973@Component 7974struct SnapshotExample { 7975 @State pixmap: image.PixelMap | undefined = undefined 7976 uiContext: UIContext = this.getUIContext(); 7977 7978 build() { 7979 Column() { 7980 Row() { 7981 Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5) 7982 Image($r('app.media.icon')).autoResize(true).width(150).height(150).margin(5).id("root") 7983 } 7984 Button("click to generate UI snapshot") 7985 .onClick(() => { 7986 this.uiContext.getComponentSnapshot() 7987 .get("root", {scale : 2, waitUntilRenderFinished : true}) 7988 .then((pixmap: image.PixelMap) => { 7989 this.pixmap = pixmap 7990 }) 7991 .catch((err: Error) => { 7992 console.error("error: " + err) 7993 }) 7994 }).margin(10) 7995 } 7996 .width('100%') 7997 .height('100%') 7998 .alignItems(HorizontalAlign.Center) 7999 } 8000} 8001``` 8002 8003### createFromBuilder<sup>12+</sup> 8004 8005createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): void 8006 8007在应用后台渲染[CustomBuilder](arkui-ts/ts-types.md#custombuilder8)自定义组件,并输出其截图。通过回调返回结果。 8008> **说明:** 8009> 8010> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。 8011> 8012> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/ts-basic-components-web.md)组件。 8013 8014**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8015 8016**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8017 8018**参数:** 8019 8020| 参数名 | 类型 | 必填 | 说明 | 8021| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 8022| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | 是 | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。 | 8023| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | 是 | 截图返回结果的回调。支持在回调中获取离屏组件绘制区域坐标和大小。 | 8024| delay<sup>12+</sup> | number | 否 | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 默认值:300 <br/> 单位:毫秒| 8025| checkImageStatus<sup>12+</sup> | boolean | 否 | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false| 8026| options<sup>12+</sup> | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 8027 8028**错误码:** 8029 8030以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 8031 8032| 错误码ID | 错误信息 | 8033| -------- | ------------------------------------------------------------ | 8034| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 8035| 100001 | The builder is not a valid build function. | 8036| 160001 | An image component in builder is not ready for taking a snapshot. The check for the ready state is required when the checkImageStatus option is enabled. | 8037 8038**示例:** 8039 8040```ts 8041import { image } from '@kit.ImageKit'; 8042import { UIContext } from '@kit.ArkUI'; 8043 8044@Entry 8045@Component 8046struct ComponentSnapshotExample { 8047 @State pixmap: image.PixelMap | undefined = undefined 8048 uiContext: UIContext = this.getUIContext(); 8049 @Builder 8050 RandomBuilder() { 8051 Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { 8052 Text('Test menu item 1') 8053 .fontSize(20) 8054 .width(100) 8055 .height(50) 8056 .textAlign(TextAlign.Center) 8057 Divider().height(10) 8058 Text('Test menu item 2') 8059 .fontSize(20) 8060 .width(100) 8061 .height(50) 8062 .textAlign(TextAlign.Center) 8063 } 8064 .width(100) 8065 .id("builder") 8066 } 8067 8068 build() { 8069 Column() { 8070 Button("click to generate UI snapshot") 8071 .onClick(() => { 8072 this.uiContext.getComponentSnapshot().createFromBuilder(() => { 8073 this.RandomBuilder() 8074 }, 8075 (error: Error, pixmap: image.PixelMap) => { 8076 if (error) { 8077 console.error("error: " + JSON.stringify(error)) 8078 return; 8079 } 8080 this.pixmap = pixmap 8081 }, 320, true, {scale : 2, waitUntilRenderFinished : true}) 8082 }) 8083 Image(this.pixmap) 8084 .margin(10) 8085 .height(200) 8086 .width(200) 8087 .border({ color: Color.Black, width: 2 }) 8088 }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300) 8089 } 8090} 8091``` 8092 8093### createFromBuilder<sup>12+</sup> 8094 8095createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap> 8096 8097在应用后台渲染[CustomBuilder](arkui-ts/ts-types.md#custombuilder8)自定义组件,并输出其截图。通过Promise返回结果。 8098 8099> **说明:** 8100> 8101> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。 8102> 8103> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/ts-basic-components-web.md)组件。 8104 8105**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8106 8107**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8108 8109**参数:** 8110 8111| 参数名 | 类型 | 必填 | 说明 | 8112| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- | 8113| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | 是 | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。 | 8114 8115**返回值:** 8116 8117| 类型 | 说明 | 8118| ------------------------------------------------------------ | ---------------- | 8119| Promise<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | 截图返回的结果。 | 8120| delay<sup>12+</sup> | number | 否 | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 默认值:300 <br/> 单位:毫秒| 8121| checkImageStatus<sup>12+</sup> | boolean | 否 | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false| 8122| options<sup>12+</sup> | [SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 8123 8124**错误码:** 8125 8126以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 8127 8128| 错误码ID | 错误信息 | 8129| -------- | ------------------------------------------------------------ | 8130| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 8131| 100001 | The builder is not a valid build function. | 8132| 160001 | An image component in builder is not ready for taking a snapshot. The check for the ready state is required when the checkImageStatus option is enabled. | 8133 8134**示例:** 8135 8136```ts 8137import { image } from '@kit.ImageKit'; 8138import { UIContext } from '@kit.ArkUI'; 8139 8140@Entry 8141@Component 8142struct ComponentSnapshotExample { 8143 @State pixmap: image.PixelMap | undefined = undefined 8144 uiContext: UIContext = this.getUIContext(); 8145 @Builder 8146 RandomBuilder() { 8147 Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { 8148 Text('Test menu item 1') 8149 .fontSize(20) 8150 .width(100) 8151 .height(50) 8152 .textAlign(TextAlign.Center) 8153 Divider().height(10) 8154 Text('Test menu item 2') 8155 .fontSize(20) 8156 .width(100) 8157 .height(50) 8158 .textAlign(TextAlign.Center) 8159 } 8160 .width(100) 8161 .id("builder") 8162 } 8163 build() { 8164 Column() { 8165 Button("click to generate UI snapshot") 8166 .onClick(() => { 8167 this.uiContext.getComponentSnapshot() 8168 .createFromBuilder(() => { 8169 this.RandomBuilder() 8170 }, 320, true, {scale : 2, waitUntilRenderFinished : true}) 8171 .then((pixmap: image.PixelMap) => { 8172 this.pixmap = pixmap 8173 }) 8174 .catch((err: Error) => { 8175 console.error("error: " + err) 8176 }) 8177 }) 8178 Image(this.pixmap) 8179 .margin(10) 8180 .height(200) 8181 .width(200) 8182 .border({ color: Color.Black, width: 2 }) 8183 }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300) 8184 } 8185} 8186``` 8187 8188### getSync<sup>12+</sup> 8189 8190getSync(id: string, options?: componentSnapshot.SnapshotOptions): image.PixelMap 8191 8192获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。同步等待截图完成返回[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)。 8193 8194> **说明:** 8195> 8196> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 8197 8198**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8199 8200**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8201 8202**参数:** 8203 8204| 参数名 | 类型 | 必填 | 说明 | 8205| ---- | ------ | ---- | ---------------------------------------- | 8206| id | string | 是 | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识)。 | 8207| options | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 8208 8209**返回值:** 8210 8211| 类型 | 说明 | 8212| ----------------------------- | -------- | 8213| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | 截图返回的结果。 | 8214 8215**错误码:** 8216 8217以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 8218 8219| 错误码ID | 错误信息 | 8220| ------ | ------------------- | 8221| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 8222| 100001 | Invalid ID. | 8223| 160002 | Timeout. | 8224 8225**示例:** 8226 8227```ts 8228import { image } from '@kit.ImageKit'; 8229import { UIContext } from '@kit.ArkUI'; 8230 8231@Entry 8232@Component 8233struct SnapshotExample { 8234 @State pixmap: image.PixelMap | undefined = undefined 8235 8236 build() { 8237 Column() { 8238 Row() { 8239 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 8240 Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root") 8241 } 8242 Button("click to generate UI snapshot") 8243 .onClick(() => { 8244 try { 8245 let pixelmap = this.getUIContext().getComponentSnapshot().getSync("root", {scale : 2, waitUntilRenderFinished : true}) 8246 this.pixmap = pixelmap 8247 } catch (error) { 8248 console.error("getSync errorCode: " + error.code + " message: " + error.message) 8249 } 8250 }).margin(10) 8251 } 8252 .width('100%') 8253 .height('100%') 8254 .alignItems(HorizontalAlign.Center) 8255 } 8256} 8257``` 8258 8259### getWithUniqueId<sup>15+</sup> 8260 8261getWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap> 8262 8263获取已加载的组件的截图,传入组件的[uniqueId](js-apis-arkui-frameNode.md#getuniqueid12),找到对应组件进行截图。通过Promise返回结果。 8264 8265> **说明:** 8266> 8267> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 8268 8269**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 8270 8271**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8272 8273**参数:** 8274 8275| 参数名 | 类型 | 必填 | 说明 | 8276| ---- | ------ | ---- | ---------------------------------------- | 8277| uniqueId | number | 是 | 目标组件的[uniqueId](js-apis-arkui-frameNode.md#getuniqueid12) | 8278| options | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 8279 8280**返回值:** 8281 8282| 类型 | 说明 | 8283| ------------------------------------------------------------ | ---------------- | 8284| Promise<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | 截图返回的结果。 | 8285 8286**错误码:** 8287 8288以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 8289 8290| 错误码ID | 错误信息 | 8291| -------- | ------------------------------------------------------------ | 8292| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 8293| 100001 | Invalid ID. | 8294 8295**示例:** 8296 8297```ts 8298import { NodeController, FrameNode, typeNode } from '@kit.ArkUI'; 8299import { image } from '@kit.ImageKit'; 8300import { UIContext } from '@kit.ArkUI'; 8301 8302class MyNodeController extends NodeController { 8303 public node: FrameNode | null = null; 8304 8305 public imageNode: FrameNode | null = null; 8306 8307 makeNode(uiContext: UIContext): FrameNode | null { 8308 this.node = new FrameNode(uiContext); 8309 this.node.commonAttribute.width('100%').height('100%') 8310 8311 let image = typeNode.createNode(uiContext, 'Image'); 8312 image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true) 8313 this.imageNode = image; 8314 8315 this.node.appendChild(image); 8316 return this.node; 8317 } 8318} 8319 8320@Entry 8321@Component 8322struct SnapshotExample { 8323 private myNodeController: MyNodeController = new MyNodeController(); 8324 8325 @State pixmap: image.PixelMap | undefined = undefined 8326 8327 build() { 8328 Column() { 8329 Row() { 8330 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 8331 NodeContainer(this.myNodeController).width(200).height(200).margin(5) 8332 } 8333 Button("UniqueId get snapshot") 8334 .onClick(() => { 8335 try { 8336 this.getUIContext() 8337 .getComponentSnapshot() 8338 .getWithUniqueId(this.myNodeController.imageNode?.getUniqueId(), {scale: 2, waitUntilRenderFinished: true}) 8339 .then((pixmap: image.PixelMap) => { 8340 this.pixmap = pixmap 8341 }) 8342 .catch((err: Error) => { 8343 console.log("error: " + err) 8344 }) 8345 } catch (error) { 8346 console.error("UniqueId get snapshot Error: " + JSON.stringify(error)) 8347 } 8348 }).margin(10) 8349 } 8350 .width('100%') 8351 .height('100%') 8352 .alignItems(HorizontalAlign.Center) 8353 } 8354} 8355``` 8356 8357### getSyncWithUniqueId<sup>15+</sup> 8358 8359getSyncWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): image.PixelMap 8360 8361获取已加载的组件的截图,传入组件的[uniqueId](js-apis-arkui-frameNode.md#getuniqueid12),找到对应组件进行截图。同步等待截图完成返回[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)。 8362 8363> **说明:** 8364> 8365> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 8366 8367**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 8368 8369**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8370 8371**参数:** 8372 8373| 参数名 | 类型 | 必填 | 说明 | 8374| ---- | ------ | ---- | ---------------------------------------- | 8375| uniqueId | number | 是 | 目标组件的[uniqueId](js-apis-arkui-frameNode.md#getuniqueid12) | 8376| options | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 8377 8378**返回值:** 8379 8380| 类型 | 说明 | 8381| ----------------------------- | -------- | 8382| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | 截图返回的结果。 | 8383 8384**错误码:** 8385 8386以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 8387 8388| 错误码ID | 错误信息 | 8389| ------ | ------------------- | 8390| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 8391| 100001 | Invalid ID. | 8392| 160002 | Timeout. | 8393 8394**示例:** 8395 8396```ts 8397import { NodeController, FrameNode, typeNode } from '@kit.ArkUI'; 8398import { image } from '@kit.ImageKit'; 8399import { UIContext } from '@kit.ArkUI'; 8400 8401class MyNodeController extends NodeController { 8402 public node: FrameNode | null = null; 8403 8404 public imageNode: FrameNode | null = null; 8405 8406 makeNode(uiContext: UIContext): FrameNode | null { 8407 this.node = new FrameNode(uiContext); 8408 this.node.commonAttribute.width('100%').height('100%') 8409 8410 let image = typeNode.createNode(uiContext, 'Image'); 8411 image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true) 8412 this.imageNode = image; 8413 8414 this.node.appendChild(image); 8415 return this.node; 8416 } 8417} 8418 8419@Entry 8420@Component 8421struct SnapshotExample { 8422 private myNodeController: MyNodeController = new MyNodeController(); 8423 8424 @State pixmap: image.PixelMap | undefined = undefined 8425 8426 build() { 8427 Column() { 8428 Row() { 8429 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 8430 NodeContainer(this.myNodeController).width(200).height(200).margin(5) 8431 } 8432 Button("UniqueId getSync snapshot") 8433 .onClick(() => { 8434 try { 8435 this.pixmap = this.getUIContext() 8436 .getComponentSnapshot() 8437 .getSyncWithUniqueId(this.myNodeController.imageNode?.getUniqueId(), {scale: 2, waitUntilRenderFinished: true}) 8438 } catch (error) { 8439 console.error("UniqueId getSync snapshot Error: " + JSON.stringify(error)) 8440 } 8441 }).margin(10) 8442 } 8443 .width('100%') 8444 .height('100%') 8445 .alignItems(HorizontalAlign.Center) 8446 } 8447} 8448``` 8449 8450## FrameCallback<sup>12+</sup> 8451 8452用于设置下一帧渲染时需要执行的任务。需要配合[UIContext](#uicontext)中的[postFrameCallback](#postframecallback12)和[postDelayedFrameCallback](#postdelayedframecallback12)使用。开发者需要继承该类并重写[onFrame](#onframe12)或[onIdle](#onidle12)方法,实现具体的业务逻辑。 8453 8454### onFrame<sup>12+</sup> 8455 8456onFrame(frameTimeInNano: number): void 8457 8458在下一帧进行渲染时,该方法将被执行。 8459 8460**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8461 8462**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8463 8464**参数:** 8465 8466| 参数名 | 类型 | 必填 | 说明 | 8467| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- | 8468| frameTimeInNano | number | 是 | 下一帧渲染开始执行的时间,以纳秒为单位。 | 8469 8470**示例:** 8471 8472```ts 8473import {FrameCallback } from '@kit.ArkUI'; 8474 8475class MyFrameCallback extends FrameCallback { 8476 private tag: string; 8477 8478 constructor(tag: string) { 8479 super() 8480 this.tag = tag; 8481 } 8482 8483 onFrame(frameTimeNanos: number) { 8484 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 8485 } 8486} 8487 8488@Entry 8489@Component 8490struct Index { 8491 build() { 8492 Row() { 8493 Column() { 8494 Button('点击触发postFrameCallback') 8495 .onClick(() => { 8496 this.getUIContext().postFrameCallback(new MyFrameCallback("normTask")); 8497 }) 8498 Button('点击触发postDelayedFrameCallback') 8499 .onClick(() => { 8500 this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5); 8501 }) 8502 } 8503 .width('100%') 8504 } 8505 .height('100%') 8506 } 8507} 8508``` 8509 8510### onIdle<sup>12+</sup> 8511 8512onIdle(timeLeftInNano: number): void 8513 8514在下一帧渲染结束时,如果距离下一个Vsync信号到来还有1ms以上的剩余时间,该方法将被执行,否则将顺延至后面的帧。 8515 8516**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8517 8518**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8519 8520**参数:** 8521 8522| 参数名 | 类型 | 必填 | 说明 | 8523| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- | 8524| timeLeftInNano | number | 是 | 这一帧剩余的空闲时间。 | 8525 8526**示例:** 8527 8528```ts 8529import { FrameCallback } from '@ohos.arkui.UIContext'; 8530 8531class MyIdleCallback extends FrameCallback { 8532 private tag: string; 8533 8534 constructor(tag: string) { 8535 super() 8536 this.tag = tag; 8537 } 8538 8539 onIdle(timeLeftInNano: number) { 8540 console.info('MyIdleCallback ' + this.tag + ' ' + timeLeftInNano.toString()); 8541 } 8542} 8543 8544@Entry 8545@Component 8546struct Index { 8547 build() { 8548 Row() { 8549 Column() { 8550 Button('点击触发postFrameCallback') 8551 .onClick(() => { 8552 this.getUIContext().postFrameCallback(new MyIdleCallback("normTask")); 8553 }) 8554 Button('点击触发postDelayedFrameCallback') 8555 .onClick(() => { 8556 this.getUIContext().postDelayedFrameCallback(new MyIdleCallback("delayTask"), 5); 8557 }) 8558 } 8559 .width('100%') 8560 } 8561 .height('100%') 8562 } 8563} 8564``` 8565 8566## DynamicSyncScene<sup>12+</sup> 8567 8568以下接口需先使用UIContext中的requireDynamicSyncScene()方法获取DynamicSyncScene对象,再通过此实例调用对应方法。 8569 8570### setFrameRateRange<sup>12+</sup> 8571 8572setFrameRateRange(range: ExpectedFrameRateRange): void 8573 8574设置期望帧率范围。 8575 8576最终结果不一定是设置的帧率,会由系统能力做综合决策,尽量满足开发者的设置帧率。 8577 8578**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8579 8580**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8581 8582**参数:** 8583 8584| 参数名 | 类型 | 必填 | 说明 | 8585| -------- | ---------- | ---- | ---- | 8586| range | [ExpectedFrameRateRange](../apis-arkui/arkui-ts/ts-explicit-animation.md#expectedframeraterange11)| 是 | 设置期望的帧率范围。<br />默认值:{min:0, max:120, expected: 120} | 8587 8588**示例:** 8589 8590```ts 8591import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI' 8592 8593@Entry 8594@Component 8595struct Frame { 8596 @State ANIMATION:ExpectedFrameRateRange = {min:0, max:120, expected: 90} 8597 @State GESTURE:ExpectedFrameRateRange = {min:0, max:120, expected: 30} 8598 private scenes: SwiperDynamicSyncScene[] = [] 8599 8600 build() { 8601 Column() { 8602 Text("动画"+ JSON.stringify(this.ANIMATION)) 8603 Text("跟手"+ JSON.stringify(this.GESTURE)) 8604 Row(){ 8605 Swiper() { 8606 Text("one") 8607 Text("two") 8608 Text("three") 8609 } 8610 .width('100%') 8611 .height('300vp') 8612 .id("dynamicSwiper") 8613 .backgroundColor(Color.Blue) 8614 .autoPlay(true) 8615 .onAppear(()=>{ 8616 this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[] 8617 }) 8618 } 8619 8620 Button("set frame") 8621 .onClick(()=>{ 8622 this.scenes.forEach((scenes: SwiperDynamicSyncScene) => { 8623 8624 if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) { 8625 scenes.setFrameRateRange(this.ANIMATION) 8626 } 8627 8628 if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) { 8629 scenes.setFrameRateRange(this.GESTURE) 8630 } 8631 }); 8632 }) 8633 } 8634 } 8635} 8636``` 8637 8638### getFrameRateRange<sup>12+</sup> 8639 8640getFrameRateRange(): ExpectedFrameRateRange 8641 8642获取期望帧率范围。 8643 8644**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8645 8646**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8647 8648**返回值:** 8649 8650| 类型 | 说明 | 8651| ------------------- | ------- | 8652| [ExpectedFrameRateRange](../apis-arkui/arkui-ts/ts-explicit-animation.md#expectedframeraterange11) | 期望帧率范围。| 8653 8654**示例:** 8655 8656```ts 8657import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI' 8658 8659@Entry 8660@Component 8661struct Frame { 8662 @State ANIMATION:ExpectedFrameRateRange = {min:0, max:120, expected: 90} 8663 @State GESTURE:ExpectedFrameRateRange = {min:0, max:120, expected: 30} 8664 private scenes: SwiperDynamicSyncScene[] = [] 8665 8666 build() { 8667 Column() { 8668 Text("动画"+ JSON.stringify(this.ANIMATION)) 8669 Text("跟手"+ JSON.stringify(this.GESTURE)) 8670 Row(){ 8671 Swiper() { 8672 Text("one") 8673 Text("two") 8674 Text("three") 8675 } 8676 .width('100%') 8677 .height('300vp') 8678 .id("dynamicSwiper") 8679 .backgroundColor(Color.Blue) 8680 .autoPlay(true) 8681 .onAppear(()=>{ 8682 this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[] 8683 }) 8684 } 8685 8686 Button("set frame") 8687 .onClick(()=>{ 8688 this.scenes.forEach((scenes: SwiperDynamicSyncScene) => { 8689 8690 if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) { 8691 scenes.setFrameRateRange(this.ANIMATION) 8692 scenes.getFrameRateRange() 8693 } 8694 8695 if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) { 8696 scenes.setFrameRateRange(this.GESTURE) 8697 scenes.getFrameRateRange() 8698 } 8699 }); 8700 }) 8701 } 8702 } 8703} 8704``` 8705## SwiperDynamicSyncScene<sup>12+</sup> 8706 8707SwiperDynamicSyncScene继承自[DynamicSyncScene](#dynamicsyncscene12),对应Swiper的动态帧率场景。 8708 8709**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8710 8711**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8712 8713| 名称 | 类型 | 只读 | 可选 | 说明 | 8714| --------- | --------------------------------------------------------- | ---- | ---- | ---------------------------------- | 8715| type | [SwiperDynamicSyncSceneType](#swiperdynamicsyncscenetype12) | 是 | 否 | Swiper的动态帧率场景。 | 8716 8717## SwiperDynamicSyncSceneType<sup>12+</sup> 8718 8719枚举值,表示动态帧率场景的类型。 8720 8721**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8722 8723**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8724 8725| 名称 | 值 | 说明 | 8726| -------- | ---- | ---------------------- | 8727| GESTURE | 0 | 手势操作场景 | 8728| ANIMATION | 1 | 动画过度场景 | 8729 8730## MarqueeDynamicSyncScene<sup>14+</sup> 8731 8732MarqueeDynamicSyncScene继承自[DynamicSyncScene](#dynamicsyncscene12),对应[Marquee](arkui-ts/ts-basic-components-marquee.md)的动态帧率场景。 8733 8734**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。 8735 8736**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8737 8738| 名称 | 类型 | 只读 | 可选 | 说明 | 8739| --------- | --------------------------------------------------------- | ---- | ---- | ---------------------------------- | 8740| type | [MarqueeDynamicSyncSceneType](#marqueedynamicsyncscenetype14) | 是 | 否 | Marquee的动态帧率场景。 | 8741 8742## MarqueeDynamicSyncSceneType<sup>14+</sup> 8743 8744枚举值,表示Marquee的动态帧率场景的类型。 8745 8746**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。 8747 8748**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8749 8750| 名称 | 值 | 说明 | 8751| -------- | ---- | ---------------------- | 8752| ANIMATION | 1 | 动画过度场景 | 8753 8754**示例:** 8755 8756```ts 8757import { MarqueeDynamicSyncSceneType, MarqueeDynamicSyncScene } from '@kit.ArkUI' 8758 8759@Entry 8760@Component 8761struct MarqueeExample { 8762 @State start: boolean = false 8763 @State src: string = '' 8764 @State marqueeText: string = 'Running Marquee' 8765 private fromStart: boolean = true 8766 private step: number = 10 8767 private loop: number = Number.POSITIVE_INFINITY 8768 controller: TextClockController = new TextClockController() 8769 convert2time(value: number): string{ 8770 let date = new Date(Number(value+'000')); 8771 let hours = date.getHours().toString().padStart(2, '0'); 8772 let minutes = date.getMinutes().toString().padStart(2, '0'); 8773 let seconds = date.getSeconds().toString().padStart(2, '0'); 8774 return hours+ ":" + minutes + ":" + seconds; 8775 } 8776 @State ANIMATION: ExpectedFrameRateRange = {min:0, max:120, expected:30} 8777 private scenes: MarqueeDynamicSyncScene[] = [] 8778 8779 build() { 8780 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 8781 Marquee({ 8782 start: this.start, 8783 step: this.step, 8784 loop: this.loop, 8785 fromStart: this.fromStart, 8786 src: this.marqueeText + this.src 8787 }) 8788 .marqueeUpdateStrategy(MarqueeUpdateStrategy.PRESERVE_POSITION) 8789 .width(300) 8790 .height(80) 8791 .fontColor('#FFFFFF') 8792 .fontSize(48) 8793 .fontWeight(700) 8794 .backgroundColor('#182431') 8795 .margin({ bottom: 40 }) 8796 .id('dynamicMarquee') 8797 .onAppear(()=>{ 8798 this.scenes = this.getUIContext().requireDynamicSyncScene('dynamicMarquee') as MarqueeDynamicSyncScene[] 8799 }) 8800 Button('Start') 8801 .onClick(() => { 8802 this.start = true 8803 this.controller.start() 8804 this.scenes.forEach((scenes: MarqueeDynamicSyncScene) => { 8805 if (scenes.type == MarqueeDynamicSyncSceneType.ANIMATION) { 8806 scenes.setFrameRateRange(this.ANIMATION) 8807 } 8808 }); 8809 }) 8810 .width(120) 8811 .height(40) 8812 .fontSize(16) 8813 .fontWeight(500) 8814 .backgroundColor('#007DFF') 8815 TextClock({ timeZoneOffset: -8, controller: this.controller }) 8816 .format('hms') 8817 .onDateChange((value: number) => { 8818 this.src = this.convert2time(value); 8819 }) 8820 .margin(20) 8821 .fontSize(30) 8822 } 8823 .width('100%') 8824 .height('100%') 8825 } 8826} 8827```