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