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