1# @ohos.arkui.UIContext (UIContext) 2 3在Stage模型中,WindowStage/Window可以通过[loadContent](js-apis-window.md#loadcontent9)接口加载页面并创建UI的实例,并将页面内容渲染到关联的窗口中,所以UI实例和窗口是一一关联的。一些全局的UI接口是和具体UI实例的执行上下文相关的,在当前接口调用时,通过追溯调用链跟踪到UI的上下文,来确定具体的UI实例。若在非UI页面中或者一些异步回调中调用这类接口,可能无法跟踪到当前UI的上下文,导致接口执行失败。 4 5@ohos.window在API version 10 新增[getUIContext](js-apis-window.md#getuicontext10)接口,获取UI上下文实例UIContext对象,使用UIContext对象提供的替代方法,可以直接作用在对应的UI实例上。 6 7> **说明:** 8> 9> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 10> 11> 示例效果请以真机运行为准,当前DevEco Studio预览器不支持。 12 13## UIContext 14 15以下API需先使用ohos.window中的[getUIContext()](js-apis-window.md#getuicontext10)方法获取UIContext实例,再通过此实例调用对应方法。或者可以通过自定义组件内置方法[getUIContext()](arkui-ts/ts-custom-component-api.md#getuicontext)获取。本文中UIContext对象以uiContext表示。 16 17### getFont 18 19getFont(): Font 20 21获取Font对象。 22 23**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 24 25**系统能力:** SystemCapability.ArkUI.ArkUI.Full 26 27**返回值:** 28 29| 类型 | 说明 | 30| ------------- | ----------- | 31| [Font](#font) | 返回Font实例对象。 | 32 33**示例:** 34 35<!--code_no_check--> 36```ts 37uiContext.getFont(); 38``` 39### getComponentUtils 40 41getComponentUtils(): ComponentUtils 42 43获取ComponentUtils对象。 44 45**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 46 47**系统能力:** SystemCapability.ArkUI.ArkUI.Full 48 49**返回值:** 50 51| 类型 | 说明 | 52| --------------------------------- | --------------------- | 53| [ComponentUtils](#componentutils) | 返回ComponentUtils实例对象。 | 54 55**示例:** 56 57<!--code_no_check--> 58```ts 59uiContext.getComponentUtils(); 60``` 61 62### getUIInspector 63 64getUIInspector(): UIInspector 65 66获取UIInspector对象。 67 68**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 69 70**系统能力:** SystemCapability.ArkUI.ArkUI.Full 71 72**返回值:** 73 74| 类型 | 说明 | 75| --------------------------- | ------------------ | 76| [UIInspector](#uiinspector) | 返回UIInspector实例对象。 | 77 78**示例:** 79 80<!--code_no_check--> 81```ts 82uiContext.getUIInspector(); 83``` 84 85### getUIObserver<sup>11+</sup> 86 87getUIObserver(): UIObserver 88 89获取UIObserver对象。 90 91**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 92 93**系统能力:** SystemCapability.ArkUI.ArkUI.Full 94 95**返回值:** 96 97| 类型 | 说明 | 98| --------------------------- | ------------------ | 99| [UIObserver](#uiobserver11) | 返回UIObserver实例对象。 | 100 101**示例:** 102 103<!--code_no_check--> 104```ts 105uiContext.getUIObserver(); 106``` 107 108### getMediaQuery 109 110getMediaQuery(): MediaQuery 111 112获取MediaQuery对象。 113 114**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 115 116**系统能力:** SystemCapability.ArkUI.ArkUI.Full 117 118**返回值:** 119 120| 类型 | 说明 | 121| ------------------------- | ----------------- | 122| [MediaQuery](#mediaquery) | 返回MediaQuery实例对象。 | 123 124**示例:** 125 126<!--code_no_check--> 127```ts 128uiContext.getMediaQuery(); 129``` 130 131### getRouter 132 133getRouter(): Router 134 135获取Router对象。 136 137**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 138 139**系统能力:** SystemCapability.ArkUI.ArkUI.Full 140 141**返回值:** 142 143| 类型 | 说明 | 144| ----------------- | ------------- | 145| [Router](#router) | 返回Router实例对象。 | 146 147**示例:** 148 149<!--code_no_check--> 150```ts 151uiContext.getRouter(); 152``` 153 154### getPromptAction 155 156getPromptAction(): PromptAction 157 158获取PromptAction对象。 159 160**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 161 162**系统能力:** SystemCapability.ArkUI.ArkUI.Full 163 164**返回值:** 165 166| 类型 | 说明 | 167| ----------------------------- | ------------------- | 168| [PromptAction](#promptaction) | 返回PromptAction实例对象。 | 169 170**示例:** 171 172<!--code_no_check--> 173```ts 174uiContext.getPromptAction(); 175``` 176 177### getOverlayManager<sup>12+</sup> 178 179getOverlayManager(): OverlayManager 180 181获取OverlayManager对象。 182 183**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 184 185**系统能力:**: SystemCapability.ArkUI.ArkUI.Full 186 187**返回值:** 188 189| 类型 | 说明 | 190| ----------------------------- | ------------------- | 191| [OverlayManager](#overlaymanager12) | 返回OverlayManager实例对象。 | 192 193**示例:** 194 195<!--code_no_check--> 196```ts 197uiContext.getOverlayManager(); 198``` 199 200### setOverlayManagerOptions<sup>15+</sup> 201 202setOverlayManagerOptions(options: OverlayManagerOptions): boolean 203 204设置[OverlayManager](#overlaymanager12)参数。用于在使用OverlayManager能力之前先初始化overlayManager的参数,包括是否需要渲染overlay根节点等属性。该方法需要在执行getOverlayManager方法之前执行生效,且该方法只生效一次。 205 206**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 207 208**系统能力:**: SystemCapability.ArkUI.ArkUI.Full 209 210**参数:** 211 212| 参数名 | 类型 | 必填 | 说明 | 213| ----- | ---------------------------------------- | ---- | ------------------------------------- | 214| options | [OverlayManagerOptions](#overlaymanageroptions15) | 是 | OverlayManager参数。| 215 216**返回值:** 217 218| 类型 | 说明 | 219| ------- | -------------- | 220| boolean | 是否设置成功。<br/>返回true时,设置成功。返回false时,设置失败。 | 221 222**示例:** 223 224<!--code_no_check--> 225```ts 226uiContext.setOverlayManagerOptions({ renderRootOverlay: true }); 227``` 228 229### getOverlayManagerOptions<sup>15+</sup> 230 231getOverlayManagerOptions(): OverlayManagerOptions 232 233用于获取当前[OverlayManager](#overlaymanager12)参数。 234 235**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 236 237**系统能力:**: SystemCapability.ArkUI.ArkUI.Full 238 239**返回值:** 240 241| 类型 | 说明 | 242| ----------------------------- | ------------------- | 243| [OverlayManagerOptions](#overlaymanageroptions15) | 返回当前OverlayManagerOptions。 | 244 245**示例:** 246 247<!--code_no_check--> 248```ts 249uiContext.getOverlayManagerOptions(); 250``` 251 252### animateTo 253 254animateTo(value: AnimateParam, event: () => void): void 255 256提供animateTo接口来指定由于闭包代码导致的状态变化插入过渡动效。 257 258**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 259 260**系统能力:** SystemCapability.ArkUI.ArkUI.Full 261 262**参数:** 263 264| 参数名 | 类型 | 必填 | 说明 | 265| ----- | ---------------------------------------- | ---- | ------------------------------------- | 266| value | [AnimateParam](arkui-ts/ts-explicit-animation.md#animateparam对象说明) | 是 | 设置动画效果相关参数。 | 267| event | () => void | 是 | 指定显示动效的闭包函数,在闭包函数中导致的状态变化系统会自动插入过渡动画。 | 268 269**示例:** 270 271```ts 272// xxx.ets 273@Entry 274@Component 275struct AnimateToExample { 276 @State widthSize: number = 250 277 @State heightSize: number = 100 278 @State rotateAngle: number = 0 279 private flag: boolean = true 280 uiContext: UIContext | undefined = undefined; 281 282 aboutToAppear() { 283 this.uiContext = this.getUIContext(); 284 if (!this.uiContext) { 285 console.warn("no uiContext"); 286 return; 287 } 288 } 289 290 build() { 291 Column() { 292 Button('change size') 293 .width(this.widthSize) 294 .height(this.heightSize) 295 .margin(30) 296 .onClick(() => { 297 if (this.flag) { 298 this.uiContext?.animateTo({ 299 duration: 2000, 300 curve: Curve.EaseOut, 301 iterations: 3, 302 playMode: PlayMode.Normal, 303 onFinish: () => { 304 console.info('play end') 305 } 306 }, () => { 307 this.widthSize = 150 308 this.heightSize = 60 309 }) 310 } else { 311 this.uiContext?.animateTo({}, () => { 312 this.widthSize = 250 313 this.heightSize = 100 314 }) 315 } 316 this.flag = !this.flag 317 }) 318 Button('stop rotating') 319 .margin(50) 320 .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle }) 321 .onAppear(() => { 322 // 组件出现时开始做动画 323 this.uiContext?.animateTo({ 324 duration: 1200, 325 curve: Curve.Friction, 326 delay: 500, 327 iterations: -1, // 设置-1表示动画无限循环 328 playMode: PlayMode.Alternate, 329 expectedFrameRateRange: { 330 min: 10, 331 max: 120, 332 expected: 60, 333 } 334 }, () => { 335 this.rotateAngle = 90 336 }) 337 }) 338 .onClick(() => { 339 this.uiContext?.animateTo({ duration: 0 }, () => { 340 // this.rotateAngle之前为90,在duration为0的动画中修改属性,可以停止该属性之前的动画,按新设置的属性显示 341 this.rotateAngle = 0 342 }) 343 }) 344 }.width('100%').margin({ top: 5 }) 345 } 346} 347``` 348 349### getSharedLocalStorage<sup>12+</sup> 350 351getSharedLocalStorage(): LocalStorage | undefined 352 353获取当前stage共享的LocalStorage实例。 354 355**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 356 357**系统能力:** SystemCapability.ArkUI.ArkUI.Full 358 359**模型约束:** 此接口仅可在Stage模型下使用。 360 361**返回值:** 362 363| 类型 | 描述 | 364| ------------------------------ | ----------------- | 365| [LocalStorage](arkui-ts/ts-state-management.md#localstorage9) \| undefined | 返回LocalStorage实例。共享的LocalStorage实例不存在时返回undefined。 | 366 367**示例:** 368 369```ts 370// EntryAbility.ets 371import { UIAbility } from '@kit.AbilityKit'; 372import { window } from '@kit.ArkUI'; 373 374export default class EntryAbility extends UIAbility { 375 storage: LocalStorage = new LocalStorage(); 376 377 onWindowStageCreate(windowStage: window.WindowStage) { 378 windowStage.loadContent('pages/Index', this.storage); 379 } 380} 381``` 382 383```ts 384// Index.ets 385 386@Entry 387@Component 388struct SharedLocalStorage { 389 localStorage = this.getUIContext().getSharedLocalStorage(); 390 391 build() { 392 Row() { 393 Column() { 394 Button("Change Local Storage to 47") 395 .onClick(() => { 396 this.localStorage?.setOrCreate("propA", 47); 397 }) 398 Button("Get Local Storage") 399 .onClick(() => { 400 console.info(`localStorage: ${this.localStorage?.get("propA")}`); 401 }) 402 } 403 .width('100%') 404 } 405 .height('100%') 406 } 407} 408``` 409 410### getHostContext<sup>12+</sup> 411 412getHostContext(): Context | undefined 413 414获得当前元能力的Context。 415 416**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 417 418**系统能力:** SystemCapability.ArkUI.ArkUI.Full 419 420**模型约束:** 此接口仅可在Stage模型下使用。 421 422**返回值:** 423 424| 类型 | 说明 | 425| ------ | ------------------------------- | 426| [Context](#context12) \| undefined | 返回当前组件所在Ability的Context,Context的具体类型为当前Ability关联的Context对象。例如:在UIAbility窗口中的页面调用该接口,返回类型为UIAbilityContext。在ExtensionAbility窗口中的页面调用该接口,返回类型为ExtensionContext。ability上下文不存在时返回undefined。 | 427 428**示例:** 429 430```ts 431@Entry 432@Component 433struct Index { 434 uiContext = this.getUIContext(); 435 436 build() { 437 Row() { 438 Column() { 439 Text("cacheDir='"+this.uiContext?.getHostContext()?.cacheDir+"'").fontSize(25) 440 Text("bundleCodeDir='"+this.uiContext?.getHostContext()?.bundleCodeDir+"'").fontSize(25) 441 } 442 .width('100%') 443 } 444 .height('100%') 445 } 446} 447``` 448 449### getFrameNodeById<sup>12+</sup> 450 451getFrameNodeById(id: string): FrameNode | null 452 453通过组件的id获取组件树的实体节点。 454 455**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 456 457**系统能力:** SystemCapability.ArkUI.ArkUI.Full 458 459**参数:** 460 461| 参数名 | 类型 | 必填 | 说明 | 462| ----- | ---------------------------------------- | ---- | ------------------------------------- | 463| id | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。 | 464 465**返回值:** 466 467| 类型 | 说明 | 468| ---------------------------------------- | ------------- | 469| [FrameNode](js-apis-arkui-frameNode.md) \| null | 返回的组件树的实体节点或者空节点。 | 470 471> **说明:** 472> 473> getFrameNodeById通过遍历查询对应id的节点,性能较差。推荐使用[getAttachedFrameNodeById](#getattachedframenodebyid12)。 474 475**示例:** 476 477<!--code_no_check--> 478```ts 479uiContext.getFrameNodeById("TestNode") 480``` 481 482### getAttachedFrameNodeById<sup>12+</sup> 483 484getAttachedFrameNodeById(id: string): FrameNode | null 485 486通过组件的id获取当前窗口上的实体节点。 487 488**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 489 490**系统能力:** SystemCapability.ArkUI.ArkUI.Full 491 492**参数:** 493 494| 参数名 | 类型 | 必填 | 说明 | 495| ----- | ---------------------------------------- | ---- | ------------------------------------- | 496| id | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。 | 497 498**返回值:** 499 500| 类型 | 说明 | 501| ---------------------------------------- | ------------- | 502| [FrameNode](js-apis-arkui-frameNode.md) \| null | 返回的组件树的实体节点或者空节点。 | 503 504> **说明:** 505> 506> getAttachedFrameNodeById仅能查询上屏节点。 507 508**示例:** 509 510<!--code_no_check--> 511```ts 512uiContext.getAttachedFrameNodeById("TestNode") 513``` 514 515### getFrameNodeByUniqueId<sup>12+</sup> 516 517getFrameNodeByUniqueId(id: number): FrameNode | null 518 519提供getFrameNodeByUniqueId接口通过组件的uniqueId获取组件树的实体节点。 5201. 当uniqueId对应的是系统组件时,返回组件所对应的FrameNode; 5212. 当uniqueId对应的是自定义组件时,若其有渲染内容,则返回该自定义组件的根节点,类型为__Common__;若其无渲染内容,则返回其第一个子组件的FrameNode。 5223. 当uniqueId无对应的组件时,返回null。 523 524**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 525 526**系统能力:** SystemCapability.ArkUI.ArkUI.Full 527 528**参数:** 529 530| 参数名 | 类型 | 必填 | 说明 | 531| ----- | ---------------------------------------- | ---- | ------------------------------------- | 532| id | number | 是 | 节点对应的UniqueId | 533 534**返回值:** 535 536| 类型 | 说明 | 537| ---------------------------------------- | ------------- | 538| [FrameNode](js-apis-arkui-frameNode.md) \| null | 返回的组件树的实体节点或者空节点。 | 539 540**示例:** 541 542```ts 543import { UIContext, FrameNode } from '@kit.ArkUI'; 544 545@Entry 546@Component 547struct MyComponent { 548 aboutToAppear() { 549 let uniqueId: number = this.getUniqueId(); 550 let uiContext: UIContext = this.getUIContext(); 551 if (uiContext) { 552 let node: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 553 } 554 } 555 556 build() { 557 // ... 558 } 559} 560``` 561 562### getPageInfoByUniqueId<sup>12+</sup> 563 564getPageInfoByUniqueId(id: number): PageInfo 565 566提供getPageInfoByUniqueId接口通过组件的uniqueId获取该节点对应的Router和NavDestination页面信息。 5671. 当uniqueId对应的节点在Page节点中,routerPageInfo属性为其对应的Router信息; 5682. 当uniqueId对应的节点在NavDestination节点中,navDestinationInfo属性为其对应的NavDestination信息; 5693. 当uniqueId对应的节点无对应的Router或NavDestination信息时,对应的属性为undefined; 5704. 模态弹窗并不在任何Page节点中。当uniqueId对应的节点在模态弹窗中,例如[CustomDialog](./arkui-ts/ts-methods-custom-dialog-box.md)、[bindSheet](./arkui-ts/ts-universal-attributes-sheet-transition.md#bindsheet)和[bindContentCover](./arkui-ts/ts-universal-attributes-modal-transition.md#bindcontentcover)构建的模态页面中,routerPageInfo属性为undefined。 571 572**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 573 574**系统能力:** SystemCapability.ArkUI.ArkUI.Full 575 576**参数:** 577 578| 参数名 | 类型 | 必填 | 说明 | 579| ----- | ---------------------------------------- | ---- | ------------------------------------- | 580| id | number | 是 | 节点对应的UniqueId | 581 582**返回值:** 583 584| 类型 | 说明 | 585| ---------------------------------------- | ------------- | 586| [PageInfo](#pageinfo12) | 返回节点对应的Router和NavDestination信息。 | 587 588**示例:** 589 590```ts 591import { UIContext, PageInfo } from '@kit.ArkUI'; 592 593@Entry 594@Component 595struct PageInfoExample { 596 @Provide('pageInfos') pageInfos: NavPathStack = new NavPathStack(); 597 598 build() { 599 Column() { 600 Navigation(this.pageInfos) { 601 NavDestination() { 602 MyComponent() 603 } 604 }.id('navigation') 605 } 606 } 607} 608 609@Component 610struct MyComponent { 611 @State content: string = ''; 612 613 build() { 614 Column() { 615 Text('PageInfoExample') 616 Button('click').onClick(() => { 617 const uiContext: UIContext = this.getUIContext(); 618 const uniqueId: number = this.getUniqueId(); 619 const pageInfo: PageInfo = uiContext.getPageInfoByUniqueId(uniqueId); 620 console.info('pageInfo: ' + JSON.stringify(pageInfo)); 621 console.info('navigationInfo: ' + JSON.stringify(uiContext.getNavigationInfoByUniqueId(uniqueId))); 622 }) 623 TextArea({ 624 text: this.content 625 }) 626 .width('100%') 627 .height(100) 628 } 629 .width('100%') 630 .alignItems(HorizontalAlign.Center) 631 } 632} 633``` 634 635### getNavigationInfoByUniqueId<sup>12+</sup> 636 637getNavigationInfoByUniqueId(id: number): observer.NavigationInfo | undefined 638 639提供getNavigationInfoByUniqueId接口通过组件的uniqueId获取该节点对应的Navigation页面信息。 6401. 当uniqueId对应的节点在Navigation节点中,返回其对应的Navigation信息; 6412. 当uniqueId对应的节点无对应的Navigation信息时,返回undefined。 642 643**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 644 645**系统能力:** SystemCapability.ArkUI.ArkUI.Full 646 647**参数:** 648 649| 参数名 | 类型 | 必填 | 说明 | 650| ----- | ---------------------------------------- | ---- | ------------------------------------- | 651| id | number | 是 | 节点对应的UniqueId | 652 653**返回值:** 654 655| 类型 | 说明 | 656| ---------------------------------------- | ------------- | 657| observer.[NavigationInfo](js-apis-arkui-observer.md#navigationinfo12) \| undefined | 返回节点对应的Navigation信息。 | 658 659**示例:** 660 661请参考[getPageInfoByUniqueId](#getpageinfobyuniqueid12)的示例。 662 663### showAlertDialog 664 665showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions): void 666 667显示警告弹窗组件,可设置文本内容与响应回调。 668 669**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 670 671**系统能力:** SystemCapability.ArkUI.ArkUI.Full 672 673**参数:** 674 675| 参数名 | 类型 | 必填 | 说明 | 676| ------- | ---------------------------------------- | ---- | ------------------- | 677| options | [AlertDialogParamWithConfirm](arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm对象说明) \| [AlertDialogParamWithButtons](arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons对象说明) \| [AlertDialogParamWithOptions](arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithoptions10对象说明) | 是 | 定义并显示AlertDialog组件。 | 678 679 680**示例:** 681 682<!--code_no_check--> 683```ts 684uiContext.showAlertDialog( 685 { 686 title: 'title', 687 message: 'text', 688 autoCancel: true, 689 alignment: DialogAlignment.Bottom, 690 offset: { dx: 0, dy: -20 }, 691 gridCount: 3, 692 confirm: { 693 value: 'button', 694 action: () => { 695 console.info('Button-clicking callback') 696 } 697 }, 698 cancel: () => { 699 console.info('Closed callbacks') 700 } 701 } 702) 703``` 704 705### showActionSheet 706 707showActionSheet(value: ActionSheetOptions): void 708 709定义列表弹窗并弹出。 710 711**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 712 713**系统能力:** SystemCapability.ArkUI.ArkUI.Full 714 715**参数:** 716 717| 参数名 | 类型 | 必填 | 说明 | 718| ------ | ------------------------------------------------------------ | ---- | -------------------- | 719| value | [ActionSheetOptions](arkui-ts/ts-methods-action-sheet.md#actionsheetoptions对象说明) | 是 | 配置列表弹窗的参数。 | 720 721**示例:** 722 723<!--code_no_check--> 724```ts 725uiContext.showActionSheet({ 726 title: 'ActionSheet title', 727 message: 'message', 728 autoCancel: true, 729 confirm: { 730 value: 'Confirm button', 731 action: () => { 732 console.info('Get Alert Dialog handled') 733 } 734 }, 735 cancel: () => { 736 console.info('actionSheet canceled') 737 }, 738 alignment: DialogAlignment.Bottom, 739 offset: { dx: 0, dy: -10 }, 740 sheets: [ 741 { 742 title: 'apples', 743 action: () => { 744 console.info('apples') 745 } 746 }, 747 { 748 title: 'bananas', 749 action: () => { 750 console.info('bananas') 751 } 752 }, 753 { 754 title: 'pears', 755 action: () => { 756 console.info('pears') 757 } 758 } 759 ] 760}) 761``` 762 763### showDatePickerDialog 764 765showDatePickerDialog(options: DatePickerDialogOptions): void 766 767定义日期滑动选择器弹窗并弹出。 768 769**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 770 771**系统能力:** SystemCapability.ArkUI.ArkUI.Full 772 773**参数:** 774 775| 参数名 | 类型 | 必填 | 说明 | 776| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 777| options | [DatePickerDialogOptions](arkui-ts/ts-methods-datepicker-dialog.md#datepickerdialogoptions对象说明) | 是 | 配置日期滑动选择器弹窗的参数。 | 778 779**示例:** 780 781<!--code_no_check--> 782```ts 783let selectedDate: Date = new Date("2010-1-1") 784uiContext.showDatePickerDialog({ 785 start: new Date("2000-1-1"), 786 end: new Date("2100-12-31"), 787 selected: selectedDate, 788 onAccept: (value: DatePickerResult) => { 789 // 通过Date的setFullYear方法设置按下确定按钮时的日期,这样当弹窗再次弹出时显示选中的是上一次确定的日期 790 selectedDate.setFullYear(Number(value.year), Number(value.month), Number(value.day)) 791 console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) 792 }, 793 onCancel: () => { 794 console.info("DatePickerDialog:onCancel()") 795 }, 796 onChange: (value: DatePickerResult) => { 797 console.info("DatePickerDialog:onChange()" + JSON.stringify(value)) 798 } 799}) 800``` 801 802### showTimePickerDialog 803 804showTimePickerDialog(options: TimePickerDialogOptions): void 805 806定义时间滑动选择器弹窗并弹出。 807 808**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 809 810**系统能力:** SystemCapability.ArkUI.ArkUI.Full 811 812**参数:** 813 814| 参数名 | 类型 | 必填 | 说明 | 815| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 816| options | [TimePickerDialogOptions](arkui-ts/ts-methods-timepicker-dialog.md#timepickerdialogoptions对象说明) | 是 | 配置时间滑动选择器弹窗的参数。 | 817 818**示例:** 819 820```ts 821// xxx.ets 822 823class SelectTime{ 824 selectTime: Date = new Date('2020-12-25T08:30:00') 825 hours(h:number,m:number){ 826 this.selectTime.setHours(h,m) 827 } 828} 829 830@Entry 831@Component 832struct TimePickerDialogExample { 833 @State selectTime: Date = new Date('2023-12-25T08:30:00'); 834 835 build() { 836 Column() { 837 Button('showTimePickerDialog') 838 .margin(30) 839 .onClick(() => { 840 this.getUIContext().showTimePickerDialog({ 841 selected: this.selectTime, 842 onAccept: (value: TimePickerResult) => { 843 // 设置selectTime为按下确定按钮时的时间,这样当弹窗再次弹出时显示选中的为上一次确定的时间 844 let time = new SelectTime() 845 if(value.hour&&value.minute){ 846 time.hours(value.hour, value.minute) 847 } 848 console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) 849 }, 850 onCancel: () => { 851 console.info("TimePickerDialog:onCancel()") 852 }, 853 onChange: (value: TimePickerResult) => { 854 console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) 855 } 856 }) 857 }) 858 }.width('100%').margin({ top: 5 }) 859 } 860} 861``` 862 863### showTextPickerDialog 864 865showTextPickerDialog(options: TextPickerDialogOptions): void 866 867定义文本滑动选择器弹窗并弹出。 868 869**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 870 871**系统能力:** SystemCapability.ArkUI.ArkUI.Full 872 873**参数:** 874 875| 参数名 | 类型 | 必填 | 说明 | 876| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 877| options | [TextPickerDialogOptions](arkui-ts/ts-methods-textpicker-dialog.md#textpickerdialogoptions对象说明) | 是 | 配置文本滑动选择器弹窗的参数。 | 878 879**示例:** 880 881```ts 882// xxx.ets 883 884class SelectedValue{ 885 select: number = 2 886 set(val:number){ 887 this.select = val 888 } 889} 890class SelectedArray{ 891 select: number[] = [] 892 set(val:number[]){ 893 this.select = val 894 } 895} 896@Entry 897@Component 898struct TextPickerDialogExample { 899 @State selectTime: Date = new Date('2023-12-25T08:30:00'); 900 private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5'] 901 private select : number = 0; 902 build() { 903 Column() { 904 Button('showTextPickerDialog') 905 .margin(30) 906 .onClick(() => { 907 this.getUIContext().showTextPickerDialog({ 908 range: this.fruits, 909 selected: this.select, 910 onAccept: (value: TextPickerResult) => { 911 // 设置select为按下确定按钮时候的选中项index,这样当弹窗再次弹出时显示选中的是上一次确定的选项 912 let selectedVal = new SelectedValue() 913 let selectedArr = new SelectedArray() 914 if(value.index){ 915 value.index instanceof Array?selectedArr.set(value.index) : selectedVal.set(value.index) 916 } 917 console.info("TextPickerDialog:onAccept()" + JSON.stringify(value)) 918 }, 919 onCancel: () => { 920 console.info("TextPickerDialog:onCancel()") 921 }, 922 onChange: (value: TextPickerResult) => { 923 console.info("TextPickerDialog:onChange()" + JSON.stringify(value)) 924 } 925 }) 926 }) 927 }.width('100%').margin({ top: 5 }) 928 } 929} 930``` 931 932### createAnimator 933 934createAnimator(options: AnimatorOptions): AnimatorResult 935 936定义Animator类。 937 938**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 939 940**系统能力:** SystemCapability.ArkUI.ArkUI.Full 941 942**参数:** 943 944| 参数名 | 类型 | 必填 | 说明 | 945| ------- | ---------------------------------------- | ---- | ------- | 946| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) | 是 | 定义动画选项。 | 947 948**返回值:** 949 950| 类型 | 说明 | 951| ---------------------------------------- | ------------- | 952| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator结果接口。 | 953 954 955**错误码**: 956 957以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。 958 959| 错误码ID | 错误信息 | 960| ------- | -------- | 961| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 962 963**示例:** 964 965```ts 966// EntryAbility.ets 967import { AnimatorOptions, window } from '@kit.ArkUI'; 968import { hilog } from '@kit.PerformanceAnalysisKit'; 969 970// used in UIAbility 971onWindowStageCreate(windowStage: window.WindowStage) { 972 // Main window is created, set main page for this ability 973 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 974 windowStage.loadContent('pages/Index', (err, data) => { 975 if (err.code) { 976 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 977 return; 978 } 979 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 980 let uiContext = windowStage.getMainWindowSync().getUIContext(); 981 let options:AnimatorOptions = { 982 duration: 1500, 983 easing: "friction", 984 delay: 0, 985 fill: "forwards", 986 direction: "normal", 987 iterations: 3, 988 begin: 200.0, 989 end: 400.0 990 }; 991 uiContext.createAnimator(options); 992 }); 993} 994``` 995 996### createAnimator<sup>18+</sup> 997 998createAnimator(options: AnimatorOptions | SimpleAnimatorOptions): AnimatorResult 999 1000创建animator动画结果对象(AnimatorResult)。与[createAnimator](#createanimator)相比,新增对[SimpleAnimatorOptions](js-apis-animator.md#simpleanimatoroptions18)类型入参的支持。 1001 1002**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1003 1004**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1005 1006**参数:** 1007 1008| 参数名 | 类型 | 必填 | 说明 | 1009| ------- | ---------------------------------------- | ---- | ------- | 1010| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) \| [SimpleAnimatorOptions](js-apis-animator.md#simpleanimatoroptions18) | 是 | 定义动画选项。 | 1011 1012**返回值:** 1013 1014| 类型 | 说明 | 1015| ---------------------------------------- | ------------- | 1016| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator结果接口。 | 1017 1018**错误码**: 1019 1020以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。 1021 1022| 错误码ID | 错误信息 | 1023| ------- | -------- | 1024| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1025 1026**示例:** 1027 1028```ts 1029import { SimpleAnimatorOptions, window } from '@kit.ArkUI'; 1030import { hilog } from '@kit.PerformanceAnalysisKit'; 1031 1032// used in UIAbility 1033onWindowStageCreate(windowStage: window.WindowStage) { 1034 // Main window is created, set main page for this ability 1035 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1036 windowStage.loadContent('pages/Index', (err, data) => { 1037 if (err.code) { 1038 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1039 return; 1040 } 1041 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1042 let uiContext = windowStage.getMainWindowSync().getUIContext(); 1043 let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).duration(2000); 1044 uiContext.createAnimator(options); 1045 }); 1046} 1047``` 1048 1049### runScopedTask 1050 1051runScopedTask(callback: () => void): void 1052 1053在当前UI上下文执行传入的回调函数。 1054 1055**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1056 1057**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1058 1059**参数:** 1060 1061| 参数名 | 类型 | 必填 | 说明 | 1062| -------- | ---------- | ---- | ---- | 1063| callback | () => void | 是 | 回调函数 | 1064 1065**示例:** 1066 1067<!--code_no_check--> 1068```ts 1069uiContext.runScopedTask( 1070 () => { 1071 console.info('Succeeded in runScopedTask'); 1072 } 1073); 1074``` 1075 1076### setKeyboardAvoidMode<sup>11+</sup> 1077 1078setKeyboardAvoidMode(value: KeyboardAvoidMode): void 1079 1080配置虚拟键盘弹出时,页面的避让模式。 1081 1082**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1083 1084**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1085 1086**参数:** 1087 1088| 参数名 | 类型 | 必填 | 说明 | 1089| -------- | ---------- | ---- | ---- | 1090| value | [KeyboardAvoidMode](#keyboardavoidmode11)| 是 | 键盘避让时的页面避让模式。<br />默认值:KeyboardAvoidMode.OFFSET | 1091 1092**示例:** 1093 1094```ts 1095// EntryAbility.ets 1096import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI'; 1097import { hilog } from '@kit.PerformanceAnalysisKit'; 1098 1099onWindowStageCreate(windowStage: window.WindowStage) { 1100 // Main window is created, set main page for this ability 1101 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1102 1103 windowStage.loadContent('pages/Index', (err, data) => { 1104 let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext(); 1105 uiContext.setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE); 1106 if (err.code) { 1107 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1108 return; 1109 } 1110 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1111 }); 1112 } 1113``` 1114 1115### getKeyboardAvoidMode<sup>11+</sup> 1116 1117getKeyboardAvoidMode(): KeyboardAvoidMode 1118 1119获取虚拟键盘弹出时,页面的避让模式。 1120 1121**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1122 1123**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1124 1125**返回值:** 1126 1127| 类型 | 说明 | 1128| ---------- | ---- | 1129| [KeyboardAvoidMode](#keyboardavoidmode11)| 返回当前的页面避让模式。| 1130 1131**示例:** 1132 1133```ts 1134// EntryAbility.ets 1135import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI'; 1136import { hilog } from '@kit.PerformanceAnalysisKit'; 1137 1138onWindowStageCreate(windowStage: window.WindowStage) { 1139 // Main window is created, set main page for this ability 1140 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 1141 1142 windowStage.loadContent('pages/Index', (err, data) => { 1143 let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext(); 1144 let KeyboardAvoidMode = uiContext.getKeyboardAvoidMode(); 1145 hilog.info(0x0000, "KeyboardAvoidMode:", JSON.stringify(KeyboardAvoidMode)); 1146 if (err.code) { 1147 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 1148 return; 1149 } 1150 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 1151 }); 1152 } 1153 1154``` 1155 1156### getAtomicServiceBar<sup>11+</sup> 1157 1158getAtomicServiceBar(): Nullable\<AtomicServiceBar> 1159 1160获取AtomicServiceBar对象,通过该对象设置原子化服务menuBar的属性。 1161 1162**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1163 1164**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1165 1166**返回值:** 1167 1168| 类型 | 说明 | 1169| ------------------------------------------------- | ------------------------------------------------------------ | 1170| Nullable<[AtomicServiceBar](#atomicservicebar11)> | 如果是原子化服务则返回AtomicServerBar类型,否则返回undefined。 | 1171 1172**示例:** 1173 1174```ts 1175// EntryAbility.ets 1176import { UIContext, AtomicServiceBar, window } from '@kit.ArkUI'; 1177import { hilog } from '@kit.PerformanceAnalysisKit'; 1178onWindowStageCreate(windowStage: window.WindowStage) { 1179 // Main window is created, set main page for this ability 1180 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 1181 windowStage.loadContent('pages/Index', (err, data) => { 1182 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 1183 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 1184 if (atomicServiceBar != undefined) { 1185 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 1186 } else { 1187 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 1188 } 1189 }); 1190} 1191``` 1192### getDragController<sup>11+</sup> 1193 1194getDragController(): DragController 1195 1196获取DragController对象,可通过该对象创建并发起拖拽。 1197 1198**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1199 1200**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1201 1202**返回值:** 1203 1204|类型|说明| 1205|----|----| 1206|[DragController](js-apis-arkui-dragController.md#dragController)| 获取DragController对象。| 1207 1208**示例:** 1209 1210<!--code_no_check--> 1211```ts 1212uiContext.getDragController(); 1213``` 1214 1215### keyframeAnimateTo<sup>11+</sup> 1216 1217keyframeAnimateTo(param: KeyframeAnimateParam, keyframes: Array<KeyframeState>): void 1218 1219产生关键帧动画。该接口的使用说明请参考[keyframeAnimateTo](arkui-ts/ts-keyframeAnimateTo.md)。 1220 1221**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1222 1223**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1224 1225**参数:** 1226 1227| 参数名 | 类型 | 必填 | 说明 | 1228| ------------ | ---------------------------------------------------- | ------- | ---------------------------- | 1229| param | [KeyframeAnimateParam](arkui-ts/ts-keyframeAnimateTo.md#keyframeanimateparam对象说明) | 是 | 关键帧动画的整体动画参数。 | 1230| keyframes | Array<[KeyframeState](arkui-ts/ts-keyframeAnimateTo.md#keyframestate对象说明)> | 是 | 所有的关键帧状态。 | 1231 1232### getFocusController<sup>12+</sup> 1233 1234getFocusController(): FocusController 1235 1236获取[FocusController](js-apis-arkui-UIContext.md#focuscontroller12)对象,可通过该对象控制焦点。 1237 1238**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1239 1240**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1241 1242**返回值:** 1243 1244|类型|说明| 1245|----|----| 1246|[FocusController](js-apis-arkui-UIContext.md#focuscontroller12)| 获取FocusController对象。| 1247 1248**示例:** 1249 1250<!--code_no_check--> 1251```ts 1252uiContext.getFocusController(); 1253``` 1254 1255### getFilteredInspectorTree<sup>12+</sup> 1256 1257getFilteredInspectorTree(filters?: Array\<string\>): string 1258 1259获取组件树及组件属性。 1260 1261**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1262 1263**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1264 1265**参数:** 1266 1267| 参数名 | 类型 | 必填 | 说明 | 1268| ------- | --------------- | ---- | ------------------------------------------------------------ | 1269| filters | Array\<string\> | 否 | 需要获取的组件属性的过滤列表。目前仅支持过滤字段:<br/>"id":组件唯一标识。<br/>"src":资源来源。 <br/>"content":元素、组件或对象所包含的信息或数据。<br/>"editable":是否可编辑。<br/>"scrollable":是否可滚动。<br/>"selectable":是否可选择。<br/>"focusable":是否可聚焦。<br/>"focused":是否已聚焦。<br/>其余字段仅供测试场景使用。 | 1270 1271**返回值:** 1272 1273| 类型 | 说明 | 1274| ------ | ---------------------------------- | 1275| string | 获取组件树及组件属性的JSON字符串。 | 1276 1277**错误码**: 1278 1279以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。 1280 1281| 错误码ID | 错误信息 | 1282| ------- | -------- | 1283| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1284 1285**示例:** 1286 1287<!--code_no_check--> 1288```ts 1289uiContext.getFilteredInspectorTree(['id', 'src', 'content']); 1290``` 1291 1292### getFilteredInspectorTreeById<sup>12+</sup> 1293 1294getFilteredInspectorTreeById(id: string, depth: number, filters?: Array\<string\>): string 1295 1296获取指定的组件及其子组件的属性。 1297 1298**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1299 1300**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1301 1302**参数:** 1303 1304| 参数名 | 类型 | 必填 | 说明 | 1305| ------- | --------------- | ---- | ------------------------------------------------------------ | 1306| id | string | 是 | 指定的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)id。 | 1307| depth | number | 是 | 获取子组件的层数。当取值0时,获取指定的组件及其所有的子孙组件的属性。当取值1时,仅获取指定的组件的属性。当取值2时,指定的组件及其1层子组件的属性。以此类推。 | 1308| filters | Array\<string\> | 否 | 需要获取的组件属性的过滤列表。目前仅支持过滤字段:<br/>"id":组件唯一标识。<br/>"src":资源来源。 <br/>"content":元素、组件或对象所包含的信息或数据。<br/>"editable":是否可编辑。<br/>"scrollable":是否可滚动。<br/>"selectable":是否可选择。<br/>"focusable":是否可聚焦。<br/>"focused":是否已聚焦。<br/>其余字段仅供测试场景使用。 | 1309 1310**返回值:** 1311 1312| 类型 | 说明 | 1313| ------ | -------------------------------------------- | 1314| string | 获取指定的组件及其子组件的属性的JSON字符串。 | 1315 1316 1317**错误码**: 1318 1319以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。 1320 1321| 错误码ID | 错误信息 | 1322| ------- | -------- | 1323| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1324 1325**示例:** 1326 1327<!--code_no_check--> 1328```ts 1329uiContext.getFilteredInspectorTreeById('testId', 0, ['id', 'src', 'content']); 1330``` 1331 1332### getCursorController<sup>12+</sup> 1333 1334getCursorController(): CursorController 1335 1336获取[CursorController](js-apis-arkui-UIContext.md#cursorcontroller12)对象,可通过该对象控制光标。 1337 1338**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1339 1340**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1341 1342**返回值:** 1343 1344|类型|说明| 1345|----|----| 1346|[CursorController](js-apis-arkui-UIContext.md#cursorcontroller12)| 获取CursorController对象。| 1347 1348**示例:** 1349 1350<!--code_no_check--> 1351```ts 1352uiContext.CursorController(); 1353``` 1354 1355### getContextMenuController<sup>12+</sup> 1356 1357getContextMenuController(): ContextMenuController 1358 1359获取[ContextMenuController](#contextmenucontroller12)对象,可通过该对象控制菜单。 1360 1361**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1362 1363**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1364 1365**返回值:** 1366 1367|类型|说明| 1368|----|----| 1369|[ContextMenuController](#contextmenucontroller12)| 获取ContextMenuController对象。| 1370 1371**示例:** 1372 1373<!--code_no_check--> 1374```ts 1375uiContext.getContextMenuController(); 1376``` 1377 1378### getMeasureUtils<sup>12+</sup> 1379 1380getMeasureUtils(): MeasureUtils 1381 1382允许用户通过UIContext对象,获取MeasureUtils对象进行文本计算。 1383 1384**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1385 1386**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1387 1388**返回值:** 1389 1390| 类型 | 说明 | 1391| ------ | -------------------------------------------- | 1392| [MeasureUtils](js-apis-arkui-UIContext.md#measureutils12) | 提供文本宽度、高度等相关计算。 | 1393 1394**示例:** 1395 1396<!--code_no_check--> 1397```ts 1398uiContext.getMeasureUtils(); 1399``` 1400 1401### getComponentSnapshot<sup>12+</sup> 1402 1403getComponentSnapshot(): ComponentSnapshot 1404 1405获取ComponentSnapshot对象,可通过该对象获取组件截图的能力。 1406 1407**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1408 1409**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1410 1411**返回值:** 1412 1413| 类型 | 说明 | 1414| ------------------------------------------------------------ | --------------------------- | 1415| [ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12) | 获取ComponentSnapshot对象。 | 1416 1417**示例:** 1418 1419<!--code_no_check--> 1420```ts 1421uiContext.getComponentSnapshot(); 1422``` 1423 1424### vp2px<sup>12+</sup> 1425 1426vp2px(value : number) : number 1427 1428将vp单位的数值转换为以px为单位的数值。 1429 1430**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1431 1432**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1433 1434**参数:** 1435 1436| 参数名 | 类型 | 必填 | 说明 | 1437| ------ | ------ | ---- | -------------------------------------- | 1438| value | number | 是 | 将vp单位的数值转换为以px为单位的数值。<br/>取值范围:(-∞, +∞) | 1439 1440**返回值:** 1441 1442| 类型 | 说明 | 1443| ------ | -------------- | 1444| number | 转换后的数值。<br/>取值范围:(-∞, +∞) | 1445 1446**示例:** 1447 1448<!--code_no_check--> 1449```ts 1450uiContext.vp2px(200); 1451``` 1452 1453### px2vp<sup>12+</sup> 1454 1455px2vp(value : number) : number 1456 1457将px单位的数值转换为以vp为单位的数值。 1458 1459**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1460 1461**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1462 1463**参数:** 1464 1465| 参数名 | 类型 | 必填 | 说明 | 1466| ------ | ------ | ---- | -------------------------------------- | 1467| value | number | 是 | 将px单位的数值转换为以vp为单位的数值。<br/>取值范围:(-∞, +∞) | 1468 1469**返回值:** 1470 1471| 类型 | 说明 | 1472| ------ | -------------- | 1473| number | 转换后的数值。<br/>取值范围:(-∞, +∞) | 1474 1475**示例:** 1476 1477<!--code_no_check--> 1478```ts 1479uiContext.px2vp(200); 1480``` 1481 1482### fp2px<sup>12+</sup> 1483 1484fp2px(value : number) : number 1485 1486将fp单位的数值转换为以px为单位的数值。 1487 1488**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1489 1490**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1491 1492**参数:** 1493 1494| 参数名 | 类型 | 必填 | 说明 | 1495| ------ | ------ | ---- | -------------------------------------- | 1496| value | number | 是 | 将fp单位的数值转换为以px为单位的数值。<br/>取值范围:(-∞, +∞) | 1497 1498**返回值:** 1499 1500| 类型 | 说明 | 1501| ------ | -------------- | 1502| number | 转换后的数值。<br/>取值范围:(-∞, +∞) | 1503 1504**示例:** 1505 1506<!--code_no_check--> 1507```ts 1508uiContext.fp2px(200); 1509``` 1510 1511### px2fp<sup>12+</sup> 1512 1513px2fp(value : number) : number 1514 1515将px单位的数值转换为以fp为单位的数值。 1516 1517**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1518 1519**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1520 1521**参数:** 1522 1523| 参数名 | 类型 | 必填 | 说明 | 1524| ------ | ------ | ---- | -------------------------------------- | 1525| value | number | 是 | 将px单位的数值转换为以fp为单位的数值。<br/>取值范围:(-∞, +∞) | 1526 1527**返回值:** 1528 1529| 类型 | 说明 | 1530| ------ | -------------- | 1531| number | 转换后的数值。<br/>取值范围:(-∞, +∞) | 1532 1533**示例:** 1534 1535<!--code_no_check--> 1536```ts 1537uiContext.px2fp(200); 1538``` 1539 1540### lpx2px<sup>12+</sup> 1541 1542lpx2px(value : number) : number 1543 1544将lpx单位的数值转换为以px为单位的数值。 1545 1546**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1547 1548**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1549 1550**参数:** 1551 1552| 参数名 | 类型 | 必填 | 说明 | 1553| ------ | ------ | ---- | --------------------------------------- | 1554| value | number | 是 | 将lpx单位的数值转换为以px为单位的数值。<br/>取值范围:(-∞, +∞) | 1555 1556**返回值:** 1557 1558| 类型 | 说明 | 1559| ------ | -------------- | 1560| number | 转换后的数值。<br/>取值范围:(-∞, +∞) | 1561 1562**示例:** 1563 1564<!--code_no_check--> 1565```ts 1566uiContext.lpx2px(200); 1567``` 1568 1569### px2lpx<sup>12+</sup> 1570 1571px2lpx(value : number) : number 1572 1573将px单位的数值转换为以lpx为单位的数值。 1574 1575**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1576 1577**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1578 1579**参数:** 1580 1581| 参数名 | 类型 | 必填 | 说明 | 1582| ------ | ------ | ---- | --------------------------------------- | 1583| value | number | 是 | 将px单位的数值转换为以lpx为单位的数值。<br/>取值范围:(-∞, +∞) | 1584 1585**返回值:** 1586 1587| 类型 | 说明 | 1588| ------ | -------------- | 1589| number | 转换后的数值。<br/>取值范围:(-∞, +∞) | 1590 1591**示例:** 1592 1593<!--code_no_check--> 1594```ts 1595uiContext.px2lpx(200); 1596``` 1597 1598### getWindowName<sup>12+</sup> 1599 1600getWindowName(): string | undefined 1601 1602获取当前实例所在窗口的名称。 1603 1604**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1605 1606**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1607 1608**返回值:** 1609 1610| 类型 | 说明 | 1611| ------ | -------------------------------------------- | 1612| string \| undefined | 当前实例所在窗口的名称。若窗口不存在,则返回undefined。 | 1613 1614**示例:** 1615 1616```ts 1617import { window } from '@kit.ArkUI'; 1618 1619@Entry 1620@Component 1621struct Index { 1622 @State message: string = 'Hello World' 1623 1624 aboutToAppear() { 1625 const windowName = this.getUIContext().getWindowName(); 1626 console.info('WindowName ' + windowName); 1627 const currWindow = window.findWindow(windowName); 1628 const windowProperties = currWindow.getWindowProperties(); 1629 console.info(`Window width ${windowProperties.windowRect.width}, height ${windowProperties.windowRect.height}`); 1630 } 1631 1632 build() { 1633 Row() { 1634 Column() { 1635 Text(this.message) 1636 .fontSize(50) 1637 .fontWeight(FontWeight.Bold) 1638 } 1639 .width('100%') 1640 } 1641 .height('100%') 1642 } 1643} 1644``` 1645 1646### getWindowWidthBreakpoint<sup>13+</sup> 1647 1648getWindowWidthBreakpoint(): WidthBreakpoint 1649 1650获取当前实例所在窗口的宽度断点枚举值。具体枚举值根据窗口宽度vp值确定,详见 [WidthBreakpoint](./arkui-ts/ts-appendix-enums.md#widthbreakpoint13)。 1651 1652**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 1653 1654**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1655 1656**返回值:** 1657 1658| 类型 | 说明 | 1659| ------ | -------------------------------------------- | 1660| [WidthBreakpoint](./arkui-ts/ts-appendix-enums.md#widthbreakpoint13) | 当前实例所在窗口的宽度断点枚举值。若窗口宽度为 0vp,则返回WIDTH_XS。 | 1661 1662**示例:** 1663 1664```ts 1665import { UIContext } from '@kit.ArkUI'; 1666 1667@Entry 1668@Component 1669struct Index { 1670 @State message: string = 'Hello World'; 1671 1672 build() { 1673 Row() { 1674 Column() { 1675 Text(this.message) 1676 .fontSize(30) 1677 .fontWeight(FontWeight.Bold) 1678 Button() { 1679 Text('test') 1680 .fontSize(30) 1681 } 1682 .onClick(() => { 1683 let uiContext: UIContext = this.getUIContext(); 1684 let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint(); 1685 let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint(); 1686 console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`) 1687 }) 1688 } 1689 .width('100%') 1690 } 1691 .height('100%') 1692 } 1693} 1694``` 1695 1696### getWindowHeightBreakpoint<sup>13+</sup> 1697 1698getWindowHeightBreakpoint(): HeightBreakpoint 1699 1700获取当前实例所在窗口的高度断点。具体枚举值根据窗口高宽比确定,详见 [HeightBreakpoint](./arkui-ts/ts-appendix-enums.md#heightbreakpoint13)。 1701 1702**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 1703 1704**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1705 1706**返回值:** 1707 1708| 类型 | 说明 | 1709| ------ | -------------------------------------------- | 1710| [HeightBreakpoint](./arkui-ts/ts-appendix-enums.md#heightbreakpoint13) | 当前实例所在窗口的宽高比对应的高度断点枚举值。若窗口高宽比为0,则返回HEIGHT_SM。 | 1711 1712**示例:** 1713 1714```ts 1715import { UIContext } from '@kit.ArkUI'; 1716 1717@Entry 1718@Component 1719struct Index { 1720 @State message: string = 'Hello World'; 1721 1722 build() { 1723 Row() { 1724 Column() { 1725 Text(this.message) 1726 .fontSize(30) 1727 .fontWeight(FontWeight.Bold) 1728 Button() { 1729 Text('test') 1730 .fontSize(30) 1731 } 1732 .onClick(() => { 1733 let uiContext: UIContext = this.getUIContext(); 1734 let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint(); 1735 let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint(); 1736 console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`) 1737 }) 1738 } 1739 .width('100%') 1740 } 1741 .height('100%') 1742 } 1743} 1744``` 1745 1746### postFrameCallback<sup>12+</sup> 1747 1748postFrameCallback(frameCallback: FrameCallback): void 1749 1750注册一个回调,仅在下一帧渲染时调用。 1751 1752**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1753 1754**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1755 1756**参数:** 1757 1758| 参数名 | 类型 | 必填 | 说明 | 1759| ------ | ------ | ---- | --------------------------------------- | 1760| frameCallback | [FrameCallback](#framecallback12) | 是 | 下一帧需要执行的回调。 | 1761 1762**示例:** 1763 1764```ts 1765import {FrameCallback } from '@kit.ArkUI'; 1766 1767class MyFrameCallback extends FrameCallback { 1768 private tag: string; 1769 1770 constructor(tag: string) { 1771 super() 1772 this.tag = tag; 1773 } 1774 1775 onFrame(frameTimeNanos: number) { 1776 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 1777 } 1778} 1779 1780@Entry 1781@Component 1782struct Index { 1783 build() { 1784 Row() { 1785 Button('点击触发postFrameCallback') 1786 .onClick(() => { 1787 this.getUIContext().postFrameCallback(new MyFrameCallback("normTask")); 1788 }) 1789 } 1790 } 1791} 1792``` 1793 1794### postDelayedFrameCallback<sup>12+</sup> 1795 1796postDelayedFrameCallback(frameCallback: FrameCallback, delayTime: number): void 1797 1798注册一个回调,在延迟一段时间后的下一帧进行渲染时执行。 1799 1800**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1801 1802**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1803 1804**参数:** 1805 1806| 参数名 | 类型 | 必填 | 说明 | 1807| ------ | ------ | ---- | --------------------------------------- | 1808| frameCallback | [FrameCallback](#framecallback12) | 是 | 下一帧需要执行的回调。 | 1809| delayTime | number | 是 | 延迟的时间,以毫秒为单位。传入null、undefined或小于0的值,会按0处理。 | 1810 1811**示例:** 1812 1813```ts 1814import {FrameCallback } from '@kit.ArkUI'; 1815 1816class MyFrameCallback extends FrameCallback { 1817 private tag: string; 1818 1819 constructor(tag: string) { 1820 super() 1821 this.tag = tag; 1822 } 1823 1824 onFrame(frameTimeNanos: number) { 1825 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 1826 } 1827} 1828 1829@Entry 1830@Component 1831struct Index { 1832 build() { 1833 Row() { 1834 Button('点击触发postDelayedFrameCallback') 1835 .onClick(() => { 1836 this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5); 1837 }) 1838 } 1839 } 1840} 1841``` 1842 1843### requireDynamicSyncScene<sup>12+</sup> 1844 1845requireDynamicSyncScene(id: string): Array<DynamicSyncScene> 1846 1847请求组件的动态帧率场景,用于自定义场景相关帧率配置。 1848 1849**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1850 1851**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1852 1853**参数:** 1854 1855| 参数名 | 类型 | 必填 | 说明 | 1856| ------ | ------ | ---- | --------------------------------------- | 1857| id | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。| 1858 1859**返回值:** 1860 1861| 类型 | 说明 | 1862| ------ | -------------------------------------------- | 1863| Array<DynamicSyncScene> | 获取DynamicSyncScene对象数组。 | 1864 1865**示例:** 1866 1867<!--code_no_check--> 1868```ts 1869uiContext.DynamicSyncScene("dynamicSyncScene") 1870``` 1871 1872### openBindSheet<sup>12+</sup> 1873 1874openBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions?: SheetOptions, targetId?: number): Promise<void> 1875 1876创建并弹出以bindSheetContent作为内容的半模态页面,使用Promise异步回调。通过该接口弹出的半模态页面样式完全按照bindSheetContent中设置的样式显示。 1877 1878> **说明:** 1879> 1880> 1. 使用该接口时,若未传入有效的targetId,则不支持设置SheetOptions.preferType为POPUP模式、不支持设置SheetOptions.mode为EMBEDDED模式。 1881> 1882> 2. 由于[updateBindSheet](#updatebindsheet12)和[closeBindSheet](#closebindsheet12)依赖bindSheetContent去更新或者关闭指定的半模态页面,开发者需自行维护传入的bindSheetContent。 1883> 1884> 3. 不支持设置SheetOptions.UIContext。 1885> 1886 1887**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 1888 1889**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1890 1891**参数:** 1892 1893| 参数名 | 类型 | 必填 | 说明 | 1894| ------- | ---------------------------------------- | ---- | ------- | 1895| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 | 1896| 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)文档。 | 1897| targetId | number | 否 | 需要绑定组件的ID,若不指定则不绑定任何组件。 | 1898 1899**返回值:** 1900 1901| 类型 | 说明 | 1902| ---------------------------------------- | ------- | 1903| Promise<void> | 异常返回Promise对象。 | 1904 1905**错误码:** 1906 1907以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。 1908 1909| 错误码ID | 错误信息 | 1910| ------ | ---------------------------------- | 1911| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 1912| 120001 | The bindSheetContent is incorrect. | 1913| 120002 | The bindSheetContent already exists. | 1914| 120004 | The targetId does not exist. | 1915| 120005 | The node of targetId is not in the component tree. | 1916| 120006 | The node of targetId is not a child of the page node or NavDestination node. | 1917 1918**示例:** 1919 1920```ts 1921import { FrameNode, ComponentContent } from "@kit.ArkUI"; 1922import { BusinessError } from '@kit.BasicServicesKit'; 1923 1924class Params { 1925 text: string = "" 1926 1927 constructor(text: string) { 1928 this.text = text; 1929 } 1930} 1931 1932let contentNode: ComponentContent<Params>; 1933let gUIContext: UIContext; 1934 1935@Builder 1936function buildText(params: Params) { 1937 Column() { 1938 Text(params.text) 1939 Button('Update BindSheet') 1940 .fontSize(20) 1941 .onClick(() => { 1942 gUIContext.updateBindSheet(contentNode, { 1943 backgroundColor: Color.Pink, 1944 }, true) 1945 .then(() => { 1946 console.info('updateBindSheet success'); 1947 }) 1948 .catch((err: BusinessError) => { 1949 console.info('updateBindSheet error: ' + err.code + ' ' + err.message); 1950 }) 1951 }) 1952 1953 Button('Close BindSheet') 1954 .fontSize(20) 1955 .onClick(() => { 1956 gUIContext.closeBindSheet(contentNode) 1957 .then(() => { 1958 console.info('closeBindSheet success'); 1959 }) 1960 .catch((err: BusinessError) => { 1961 console.info('closeBindSheet error: ' + err.code + ' ' + err.message); 1962 }) 1963 }) 1964 } 1965} 1966 1967@Entry 1968@Component 1969struct UIContextBindSheet { 1970 @State message: string = 'BindSheet'; 1971 1972 aboutToAppear() { 1973 gUIContext = this.getUIContext(); 1974 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 1975 } 1976 1977 build() { 1978 RelativeContainer() { 1979 Column() { 1980 Button('Open BindSheet') 1981 .fontSize(20) 1982 .onClick(() => { 1983 let uiContext = this.getUIContext(); 1984 let uniqueId = this.getUniqueId(); 1985 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 1986 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 1987 uiContext.openBindSheet(contentNode, { 1988 height: SheetSize.MEDIUM, 1989 backgroundColor: Color.Green, 1990 title: { title: "Title", subtitle: "subtitle" } 1991 }, targetId) 1992 .then(() => { 1993 console.info('openBindSheet success'); 1994 }) 1995 .catch((err: BusinessError) => { 1996 console.info('openBindSheet error: ' + err.code + ' ' + err.message); 1997 }) 1998 }) 1999 } 2000 } 2001 .height('100%') 2002 .width('100%') 2003 } 2004} 2005``` 2006 2007### updateBindSheet<sup>12+</sup> 2008 2009updateBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>, sheetOptions: SheetOptions, partialUpdate?: boolean ): Promise<void> 2010 2011更新bindSheetContent对应的半模态页面的样式,使用Promise异步回调。 2012 2013> **说明:** 2014> 2015> 不支持更新SheetOptions.UIContext、SheetOptions.mode、回调函数。 2016> 2017 2018**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2019 2020**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2021 2022**参数:** 2023 2024| 参数名 | 类型 | 必填 | 说明 | 2025| ------- | ---------------------------------------- | ---- | ------- | 2026| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 | 2027| sheetOptions | [SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions) | 是 | 半模态页面样式。<br/>**说明:** <br/>不支持更新SheetOptions.uiContext、SheetOptions.mode、回调函数。 | 2028| partialUpdate | boolean | 否 | 半模态页面更新方式, 默认值为false。<br/>**说明:** <br/>1. true为增量更新,保留当前值,更新SheetOptions中的指定属性。 <br/>2. false为全量更新,除SheetOptions中的指定属性,其他属性恢复默认值。 | 2029 2030**返回值:** 2031 2032| 类型 | 说明 | 2033| ---------------------------------------- | ------- | 2034| Promise<void> | 异常返回Promise对象。 | 2035 2036**错误码:** 2037 2038以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。 2039 2040| 错误码ID | 错误信息 | 2041| ------ | ---------------------------------- | 2042| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 2043| 120001 | The bindSheetContent is incorrect. | 2044| 120003 | The bindSheetContent cannot be found. | 2045 2046**示例:** 2047 2048```ts 2049import { FrameNode, ComponentContent } from "@kit.ArkUI"; 2050import { BusinessError } from '@kit.BasicServicesKit'; 2051 2052class Params { 2053 text: string = "" 2054 2055 constructor(text: string) { 2056 this.text = text; 2057 } 2058} 2059 2060let contentNode: ComponentContent<Params>; 2061let gUIContext: UIContext; 2062 2063@Builder 2064function buildText(params: Params) { 2065 Column() { 2066 Text(params.text) 2067 Button('Update BindSheet') 2068 .fontSize(20) 2069 .onClick(() => { 2070 gUIContext.updateBindSheet(contentNode, { 2071 backgroundColor: Color.Pink, 2072 }, true) 2073 .then(() => { 2074 console.info('updateBindSheet success'); 2075 }) 2076 .catch((err: BusinessError) => { 2077 console.info('updateBindSheet error: ' + err.code + ' ' + err.message); 2078 }) 2079 }) 2080 2081 Button('Close BindSheet') 2082 .fontSize(20) 2083 .onClick(() => { 2084 gUIContext.closeBindSheet(contentNode) 2085 .then(() => { 2086 console.info('closeBindSheet success'); 2087 }) 2088 .catch((err: BusinessError) => { 2089 console.info('closeBindSheet error: ' + err.code + ' ' + err.message); 2090 }) 2091 }) 2092 } 2093} 2094 2095@Entry 2096@Component 2097struct UIContextBindSheet { 2098 @State message: string = 'BindSheet'; 2099 2100 aboutToAppear() { 2101 gUIContext = this.getUIContext(); 2102 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 2103 } 2104 2105 build() { 2106 RelativeContainer() { 2107 Column() { 2108 Button('Open BindSheet') 2109 .fontSize(20) 2110 .onClick(() => { 2111 let uiContext = this.getUIContext(); 2112 let uniqueId = this.getUniqueId(); 2113 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 2114 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 2115 uiContext.openBindSheet(contentNode, { 2116 height: SheetSize.MEDIUM, 2117 backgroundColor: Color.Green, 2118 title: { title: "Title", subtitle: "subtitle" } 2119 }, targetId) 2120 .then(() => { 2121 console.info('openBindSheet success'); 2122 }) 2123 .catch((err: BusinessError) => { 2124 console.info('openBindSheet error: ' + err.code + ' ' + err.message); 2125 }) 2126 }) 2127 } 2128 } 2129 .height('100%') 2130 .width('100%') 2131 } 2132} 2133``` 2134 2135### closeBindSheet<sup>12+</sup> 2136 2137closeBindSheet\<T extends Object>(bindSheetContent: ComponentContent\<T>): Promise<void> 2138 2139关闭bindSheetContent对应的半模态页面,使用Promise异步回调。 2140 2141> **说明:** 2142> 2143> 使用此接口关闭半模态页面时,不会触发shouldDismiss回调。 2144> 2145 2146**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2147 2148**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2149 2150**参数:** 2151 2152| 参数名 | 类型 | 必填 | 说明 | 2153| ------- | ---------------------------------------- | ---- | ------- | 2154| bindSheetContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 | 2155 2156**返回值:** 2157 2158| 类型 | 说明 | 2159| ---------------------------------------- | ------- | 2160| Promise<void> | 异常返回Promise对象。 | 2161 2162**错误码:** 2163 2164以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。 2165 2166| 错误码ID | 错误信息 | 2167| ------ | ---------------------------------- | 2168| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 2169| 120001 | The bindSheetContent is incorrect. | 2170| 120003 | The bindSheetContent cannot be found. | 2171 2172**示例:** 2173 2174```ts 2175import { FrameNode, ComponentContent } from "@kit.ArkUI"; 2176import { BusinessError } from '@kit.BasicServicesKit'; 2177 2178class Params { 2179 text: string = "" 2180 2181 constructor(text: string) { 2182 this.text = text; 2183 } 2184} 2185 2186let contentNode: ComponentContent<Params>; 2187let gUIContext: UIContext; 2188 2189@Builder 2190function buildText(params: Params) { 2191 Column() { 2192 Text(params.text) 2193 Button('Update BindSheet') 2194 .fontSize(20) 2195 .onClick(() => { 2196 gUIContext.updateBindSheet(contentNode, { 2197 backgroundColor: Color.Pink, 2198 }, true) 2199 .then(() => { 2200 console.info('updateBindSheet success'); 2201 }) 2202 .catch((err: BusinessError) => { 2203 console.info('updateBindSheet error: ' + err.code + ' ' + err.message); 2204 }) 2205 }) 2206 2207 Button('Close BindSheet') 2208 .fontSize(20) 2209 .onClick(() => { 2210 gUIContext.closeBindSheet(contentNode) 2211 .then(() => { 2212 console.info('closeBindSheet success'); 2213 }) 2214 .catch((err: BusinessError) => { 2215 console.info('closeBindSheet error: ' + err.code + ' ' + err.message); 2216 }) 2217 }) 2218 } 2219} 2220 2221@Entry 2222@Component 2223struct UIContextBindSheet { 2224 @State message: string = 'BindSheet'; 2225 2226 aboutToAppear() { 2227 gUIContext = this.getUIContext(); 2228 contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message)); 2229 } 2230 2231 build() { 2232 RelativeContainer() { 2233 Column() { 2234 Button('Open BindSheet') 2235 .fontSize(20) 2236 .onClick(() => { 2237 let uiContext = this.getUIContext(); 2238 let uniqueId = this.getUniqueId(); 2239 let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId); 2240 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 2241 uiContext.openBindSheet(contentNode, { 2242 height: SheetSize.MEDIUM, 2243 backgroundColor: Color.Green, 2244 title: { title: "Title", subtitle: "subtitle" } 2245 }, targetId) 2246 .then(() => { 2247 console.info('openBindSheet success'); 2248 }) 2249 .catch((err: BusinessError) => { 2250 console.info('openBindSheet error: ' + err.code + ' ' + err.message); 2251 }) 2252 }) 2253 } 2254 } 2255 .height('100%') 2256 .width('100%') 2257 } 2258} 2259``` 2260 2261### isFollowingSystemFontScale<sup>13+</sup> 2262 2263isFollowingSystemFontScale(): boolean 2264 2265获取当前UI上下文是否跟随系统字体倍率。 2266 2267**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2268 2269**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2270 2271**返回值:** 2272 2273| 类型 | 说明 | 2274|---------|---------------| 2275| boolean | 当前UI上下文是否跟随系统字体倍率。<br/> true表示UI上下文跟随系统倍率,false表示UI上下文不跟随系统倍率。 | 2276 2277**示例:** 2278 2279<!--code_no_check--> 2280```ts 2281uiContext.isFollowingSystemFontScale() 2282``` 2283 2284### getMaxFontScale<sup>13+</sup> 2285 2286getMaxFontScale(): number 2287 2288获取当前UI上下文最大字体倍率。 2289 2290**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2291 2292**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2293 2294**返回值:** 2295 2296| 类型 | 说明 | 2297|---------|-----------| 2298| number | 当前UI上下文最大字体倍率。 | 2299 2300**示例:** 2301 2302<!--code_no_check--> 2303```ts 2304uiContext.getMaxFontScale() 2305``` 2306 2307### bindTabsToScrollable<sup>13+</sup> 2308 2309bindTabsToScrollable(tabsController: TabsController, scroller: 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> **说明:** 2314> 2315> 当多个可滚动容器组件绑定了同一个Tabs组件时,只要滑动任意一个可滚动容器组件,就会触发TabBar的显示或隐藏。且当任意一个可滚动容器组件滑动到底部时,会立即触发TabBar的显示动效。因此不建议同时触发多个可滚动容器组件的滑动。 2316 2317**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2318 2319**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2320 2321**参数:** 2322 2323| 参数名 | 类型 | 必填 | 说明 | 2324| ------- | ---------------------------------------- | ---- | ------- | 2325| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 | 2326| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 | 2327 2328**示例:** 2329 2330```ts 2331@Entry 2332@Component 2333struct TabsExample { 2334 private arr: string[] = [] 2335 private parentTabsController: TabsController = new TabsController() 2336 private childTabsController: TabsController = new TabsController() 2337 private listScroller: Scroller = new Scroller() 2338 private parentScroller: Scroller = new Scroller() 2339 private childScroller: Scroller = new Scroller() 2340 2341 aboutToAppear(): void { 2342 for (let i = 0; i < 20; i++) { 2343 this.arr.push(i.toString()) 2344 } 2345 let context = this.getUIContext() 2346 context.bindTabsToScrollable(this.parentTabsController, this.listScroller) 2347 context.bindTabsToScrollable(this.childTabsController, this.listScroller) 2348 context.bindTabsToNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller) 2349 } 2350 2351 aboutToDisappear(): void { 2352 let context = this.getUIContext() 2353 context.unbindTabsFromScrollable(this.parentTabsController, this.listScroller) 2354 context.unbindTabsFromScrollable(this.childTabsController, this.listScroller) 2355 context.unbindTabsFromNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller) 2356 } 2357 2358 build() { 2359 Tabs({ barPosition: BarPosition.End, controller: this.parentTabsController }) { 2360 TabContent() { 2361 Tabs({ controller: this.childTabsController }) { 2362 TabContent() { 2363 List({ space: 20, initialIndex: 0, scroller: this.listScroller }) { 2364 ForEach(this.arr, (item: string) => { 2365 ListItem() { 2366 Text(item) 2367 .width('100%') 2368 .height(100) 2369 .fontSize(16) 2370 .textAlign(TextAlign.Center) 2371 .borderRadius(10) 2372 .backgroundColor(Color.Gray) 2373 } 2374 }, (item: string) => item) 2375 } 2376 .scrollBar(BarState.Off) 2377 .width('90%') 2378 .height('100%') 2379 .contentStartOffset(56) 2380 .contentEndOffset(52) 2381 }.tabBar(SubTabBarStyle.of('顶部页签')) 2382 } 2383 .width('100%') 2384 .height('100%') 2385 .barOverlap(true) // 使TabBar叠加在TabContent上,当TabBar向上或向下隐藏后,原位置处不为空白 2386 .clip(true) // 对超出Tabs组件范围的子组件进行裁剪,防止TabBar向上或向下隐藏后误触TabBar 2387 }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), 'scroller联动多个TabsController')) 2388 2389 TabContent() { 2390 Scroll(this.parentScroller) { 2391 List({ space: 20, initialIndex: 0, scroller: this.childScroller }) { 2392 ForEach(this.arr, (item: string) => { 2393 ListItem() { 2394 Text(item) 2395 .width('100%') 2396 .height(100) 2397 .fontSize(16) 2398 .textAlign(TextAlign.Center) 2399 .borderRadius(10) 2400 .backgroundColor(Color.Gray) 2401 } 2402 }, (item: string) => item) 2403 } 2404 .scrollBar(BarState.Off) 2405 .width('90%') 2406 .height('100%') 2407 .contentEndOffset(52) 2408 .nestedScroll({ scrollForward: NestedScrollMode.SELF_FIRST, scrollBackward: NestedScrollMode.SELF_FIRST }) 2409 } 2410 .width('100%') 2411 .height('100%') 2412 .scrollBar(BarState.Off) 2413 .scrollable(ScrollDirection.Vertical) 2414 .edgeEffect(EdgeEffect.Spring) 2415 }.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), '嵌套的scroller联动TabsController')) 2416 } 2417 .width('100%') 2418 .height('100%') 2419 .barOverlap(true) // 使TabBar叠加在TabContent上,当TabBar向上或向下隐藏后,原位置处不为空白 2420 .clip(true) // 对超出Tabs组件范围的子组件进行裁剪,防止TabBar向上或向下隐藏后误触TabBar 2421 } 2422} 2423``` 2424 2425 2426 2427### unbindTabsFromScrollable<sup>13+</sup> 2428 2429unbindTabsFromScrollable(tabsController: TabsController, scroller: Scroller): void; 2430 2431解除Tabs组件和可滚动容器组件的绑定。 2432 2433**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2434 2435**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2436 2437**参数:** 2438 2439| 参数名 | 类型 | 必填 | 说明 | 2440| ------- | ---------------------------------------- | ---- | ------- | 2441| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 | 2442| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 | 2443 2444**示例:** 2445 2446参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。 2447 2448### bindTabsToNestedScrollable<sup>13+</sup> 2449 2450bindTabsToNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void; 2451 2452绑定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绑定。 2453 2454**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2455 2456**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2457 2458**参数:** 2459 2460| 参数名 | 类型 | 必填 | 说明 | 2461| ------- | ---------------------------------------- | ---- | ------- | 2462| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 | 2463| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 | 2464| childScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。其对应组件为parentScroller对应组件的子组件,且组件间存在嵌套滚动关系。 | 2465 2466**示例:** 2467 2468参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。 2469 2470### unbindTabsFromNestedScrollable<sup>13+</sup> 2471 2472unbindTabsFromNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void; 2473 2474解除Tabs组件和嵌套的可滚动容器组件的绑定。 2475 2476**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。 2477 2478**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2479 2480**参数:** 2481 2482| 参数名 | 类型 | 必填 | 说明 | 2483| ------- | ---------------------------------------- | ---- | ------- | 2484| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 | 2485| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 | 2486| childScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。其对应组件为parentScroller对应组件的子组件,且组件间存在嵌套滚动关系。 | 2487 2488**示例:** 2489 2490参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。 2491 2492### enableSwipeBack<sup>18+</sup> 2493 2494enableSwipeBack(enabled: Optional\<boolean\>): void 2495 2496设置是否支持应用内横向滑动返回上一级。 2497 2498**原子化服务API:** 从API Version 18 开始,该接口支持在原子化服务中使用。 2499 2500**系统能力:** SystemCapability.ArkUI.ArkUI.Circle 2501 2502**参数:** 2503 2504| 参数名 | 类型 | 必填 | 说明 | 2505| --- | --- | --- | --- | 2506| enabled | boolean | 是 | 是否支持应用内横向滑动返回,默认值为true。| 2507 2508**示例:** 2509 2510```js 2511@Entry 2512@Component 2513struct Index { 2514 @State isEnable: boolean = true; 2515 2516 build() { 2517 RelativeContainer() { 2518 Button(`enable swipe back: ${this.isEnable}`).onClick(() => { 2519 this.isEnable = !this.isEnable; 2520 this.getUIContext().enableSwipeBack(this.isEnable); 2521 }) 2522 } 2523 .height('100%') 2524 .width('100%') 2525 } 2526} 2527``` 2528 2529### getTextMenuController<sup>16+</sup> 2530 2531getTextMenuController(): TextMenuController 2532 2533获取[TextMenuController](#textmenucontroller16)对象,可通过该对象控制文本选择菜单。 2534 2535**原子化服务API:** 从API Version 16 开始,该接口支持在原子化服务中使用。 2536 2537**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2538 2539**返回值:** 2540 2541|类型|说明| 2542|----|----| 2543|[TextMenuController](#textmenucontroller16)| 获取TextMenuController对象。| 2544 2545**示例:** 2546 2547参考[TextMenuController](#textmenucontroller16)接口示例。 2548 2549### createUIContextWithoutWindow<sup>17+</sup> 2550 2551static createUIContextWithoutWindow(context: common.UIAbilityContext | common.ExtensionContext) : UIContext | undefined 2552 2553创建一个不依赖窗口的UI实例,并返回其UI上下文。该接口所创建的UI实例是单例。 2554 2555> **说明:** 2556> 2557> 返回的UI上下文只可用于创建[自定义节点](../../ui/arkts-user-defined-node.md),不能执行其他UI操作。 2558 2559**原子化服务API:** 从API version 17 开始,该接口支持在原子化服务中使用。 2560 2561**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2562 2563**参数:** 2564 2565| 参数名 | 类型 | 必填 | 说明 | 2566| ------- | ---------------------------------------- | ---- | ----------- | 2567| context | common.[UIAbilityContext](../apis-ability-kit/js-apis-inner-application-uiAbilityContext.md) \| common.[ExtensionContext](../apis-ability-kit/js-apis-inner-application-extensionContext.md) | 是 | [UIAbility](../apis-ability-kit/js-apis-app-ability-uiAbility.md)或[ExtensionAbility](../apis-ability-kit/js-apis-app-ability-extensionAbility.md)所对应的上下文环境。 | 2568 2569**返回值:** 2570 2571|类型|说明| 2572|----|----| 2573| UIContext \| undefined | 创建的UI实例的上下文,创建失败时返回undefined。 | 2574 2575**错误码:** 2576 2577以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[UI上下文](errorcode-uicontext.md)错误码。 2578 2579| 错误码ID | 错误信息 | 2580| ------ | ---------------------------------- | 2581| 401 | Parameter error. Possible causes: <br> 1. The number of parameters is incorrect.<br> 2. Invalid parameter type of context. | 2582| 100001 | Internal error. | 2583 2584 2585**示例:** 2586```ts 2587import { UIContext } from '@kit.ArkUI'; 2588 2589export default class EntryAbility extends UIAbility { 2590 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 2591 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 2592 let uiContext : UIContext | undefined = UIContext.createUIContextWithoutWindow(this.context); 2593 } 2594 2595 // ...... 2596} 2597``` 2598 2599### destroyUIContextWithoutWindow<sup>17+</sup> 2600 2601static destroyUIContextWithoutWindow(): void 2602 2603销毁[createUIContextWithoutWindow](#createuicontextwithoutwindow17)创建的UI实例。 2604 2605**原子化服务API:** 从API version 17 开始,该接口支持在原子化服务中使用。 2606 2607**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2608 2609**示例:** 2610```ts 2611UIContext.destroyUIContextWithoutWindow(); 2612``` 2613 2614### dispatchKeyEvent<sup>15+</sup> 2615 2616dispatchKeyEvent(node: number | string, event: KeyEvent): boolean 2617 2618按键事件应分发给指定的组件。为了确保行为的可预测性,目标组件必须位于分发组件的子树中。 2619 2620**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 2621 2622**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2623 2624| 参数名 | 类型 | 必填 | 说明 | 2625| ------ | ----------------------------- | ---- | ------------------ | 2626| node | number \| string | 是 | 组件的id或者节点UniqueID。 | 2627| event |[KeyEvent](./arkui-ts/ts-universal-events-key.md#keyevent对象说明) | 是 | KeyEvent对象。 | 2628 2629**示例:** 2630 2631```ts 2632@Entry 2633@Component 2634struct Index { 2635 build() { 2636 Row() { 2637 Row() { 2638 Button('Button1').id('Button1').onKeyEvent((event) => { 2639 console.log("Button1"); 2640 return true 2641 }) 2642 Button('Button2').id('Button2').onKeyEvent((event) => { 2643 console.log("Button2"); 2644 return true 2645 }) 2646 } 2647 .width('100%') 2648 .height('100%') 2649 .id('Row1') 2650 .onKeyEventDispatch((event) => { 2651 let context = this.getUIContext(); 2652 context.getFocusController().requestFocus('Button1'); 2653 return context.dispatchKeyEvent('Button1', event); 2654 }) 2655 2656 } 2657 .height('100%') 2658 .width('100%') 2659 .onKeyEventDispatch((event) => { 2660 if (event.type == KeyType.Down) { 2661 let context = this.getUIContext(); 2662 context.getFocusController().requestFocus('Row1'); 2663 return context.dispatchKeyEvent('Row1', event); 2664 } 2665 return true; 2666 }) 2667 } 2668} 2669``` 2670## Font 2671 2672以下API需先使用UIContext中的[getFont()](#getfont)方法获取到Font对象,再通过该对象调用对应方法。 2673 2674### registerFont 2675 2676registerFont(options: font.FontOptions): void 2677 2678在字体管理中注册自定义字体。 2679 2680**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 2681 2682**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2683 2684**参数:** 2685 2686| 参数名 | 类型 | 必填 | 说明 | 2687| ------- | ---------------------------------------- | ---- | ----------- | 2688| options | [font.FontOptions](js-apis-font.md#fontoptions) | 是 | 注册的自定义字体信息。 | 2689 2690**示例:** 2691 2692<!--code_no_check--> 2693```ts 2694import { Font } from '@kit.ArkUI'; 2695 2696let font:Font = uiContext.getFont(); 2697font.registerFont({ 2698 familyName: 'medium', 2699 familySrc: '/font/medium.ttf' 2700}); 2701``` 2702### getSystemFontList 2703 2704getSystemFontList(): Array\<string> 2705 2706获取系统支持的字体名称列表。 2707 2708**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 2709 2710**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2711 2712**返回值:** 2713 2714| 类型 | 说明 | 2715| -------------- | --------- | 2716| Array\<string> | 系统的字体名列表。 | 2717 2718> **说明:** 2719> 2720> 该接口仅在2in1设备上生效。 2721 2722**示例:** 2723 2724<!--code_no_check--> 2725```ts 2726import { Font } from '@kit.ArkUI'; 2727 2728let font:Font|undefined = uiContext.getFont(); 2729if(font){ 2730 font.getSystemFontList() 2731} 2732``` 2733 2734### getFontByName 2735 2736getFontByName(fontName: string): font.FontInfo 2737 2738根据传入的系统字体名称获取系统字体的相关信息。 2739 2740**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 2741 2742**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2743 2744**参数:** 2745 2746| 参数名 | 类型 | 必填 | 说明 | 2747| -------- | ------ | ---- | ------- | 2748| fontName | string | 是 | 系统的字体名。 | 2749 2750**返回值:** 2751 2752| 类型 | 说明 | 2753| ----------------------------------------- | -------------- | 2754| [font.FontInfo](js-apis-font.md#fontinfo) | 字体的详细信息 | 2755 2756**示例:** 2757 2758<!--code_no_check--> 2759```ts 2760import { Font } from '@kit.ArkUI'; 2761 2762let font:Font|undefined = uiContext.getFont(); 2763if(font){ 2764 font.getFontByName('Sans Italic') 2765} 2766``` 2767 2768## Context<sup>12+</sup> 2769 2770type Context = common.Context 2771 2772当前组件所在Ability的上下文。 2773 2774**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2775 2776**系统能力:** SystemCapability.Ability.AbilityRuntime.Core 2777 2778**模型约束:** 此接口仅可在Stage模型下使用。 2779 2780| 类型 |说明 | 2781| ------ | ------------------- | 2782| [common.Context](../apis-ability-kit/js-apis-app-ability-common.md#context) |Context的具体类型为当前Ability关联的Context对象。| 2783 2784## ComponentUtils 2785 2786以下API需先使用UIContext中的[getComponentUtils()](#getcomponentutils)方法获取到ComponentUtils对象,再通过该对象调用对应方法。 2787 2788### getRectangleById 2789 2790getRectangleById(id: string): componentUtils.ComponentInfo 2791 2792获取组件大小、位置、平移缩放旋转及仿射矩阵属性信息。 2793 2794**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 2795 2796**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2797 2798**参数:** 2799 2800| 参数名 | 类型 | 必填 | 说明 | 2801| ---- | ------ | ---- | --------- | 2802| id | string | 是 | 组件唯一标识id。 | 2803 2804**返回值:** 2805 2806| 类型 | 说明 | 2807| ------------------------------------------------------------ | ------------------------------------------------ | 2808| [componentUtils.ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | 组件大小、位置、平移缩放旋转及仿射矩阵属性信息。 | 2809 2810**错误码:** 2811 2812以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 2813 2814| 错误码ID | 错误信息 | 2815| ------ | ------------------- | 2816| 100001 | UI execution context not found. | 2817 2818**示例:** 2819 2820<!--code_no_check--> 2821```ts 2822import { ComponentUtils } from '@kit.ArkUI'; 2823 2824let componentUtils:ComponentUtils = uiContext.getComponentUtils(); 2825let modePosition = componentUtils.getRectangleById("onClick"); 2826let localOffsetWidth = modePosition.size.width; 2827let localOffsetHeight = modePosition.size.height; 2828``` 2829 2830## UIInspector 2831 2832以下API需先使用UIContext中的[getUIInspector()](#getuiinspector)方法获取到UIInspector对象,再通过该对象调用对应方法。 2833 2834### createComponentObserver 2835 2836createComponentObserver(id: string): inspector.ComponentObserver 2837 2838注册组件布局和组件绘制送显完成回调通知。 2839 2840**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 2841 2842**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2843 2844**参数:** 2845 2846| 参数名 | 类型 | 必填 | 说明 | 2847| ---- | ------ | ---- | ------- | 2848| id | string | 是 | 指定组件id,该id通过通用属性[id](./arkui-ts/ts-universal-attributes-component-id.md#id)或者[key](./arkui-ts/ts-universal-attributes-component-id.md#key12)设置。 | 2849 2850**返回值:** 2851 2852| 类型 | 说明 | 2853| ------------------------------------------------------------ | -------------------------------------------------- | 2854| [inspector.ComponentObserver](js-apis-arkui-inspector.md#componentobserver) | 组件回调事件监听句柄,用于注册和取消注册监听回调。 | 2855 2856**示例:** 2857 2858<!--code_no_check--> 2859```ts 2860import { UIInspector } from '@kit.ArkUI'; 2861 2862let inspector: UIInspector = uiContext.getUIInspector(); 2863let listener = inspector.createComponentObserver('COMPONENT_ID'); 2864``` 2865 2866## PageInfo<sup>12+</sup> 2867Router和NavDestination等页面信息,若无对应的Router或NavDestination页面信息,则对应属性为undefined。 2868 2869**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2870 2871**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2872 2873| 名称 | 类型 | 必填 | 说明 | 2874| -------- | -------- | -------- | -------- | 2875| routerPageInfo | observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo) | 否 | Router信息。 | 2876| navDestinationInfo | observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo) | 否 | NavDestination信息。 | 2877 2878## UIObserver<sup>11+</sup> 2879 2880以下API需先使用UIContext中的[getUIObserver()](#getuiobserver11)方法获取到UIObserver对象,再通过该对象调用对应方法。 2881 2882### on('navDestinationUpdate')<sup>11+</sup> 2883 2884on(type: 'navDestinationUpdate', callback: Callback\<observer.NavDestinationInfo\>): void 2885 2886监听NavDestination组件的状态变化。 2887 2888**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2889 2890**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2891 2892**参数:** 2893 2894| 参数名 | 类型 | 必填 | 说明 | 2895| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 2896| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 | 2897| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 是 | 回调函数。返回当前的NavDestination组件状态。 | 2898 2899**示例:** 2900 2901<!--code_no_check--> 2902```ts 2903// Index.ets 2904// 演示 uiObserver.on('navDestinationUpdate', callback) 2905// uiObserver.off('navDestinationUpdate', callback) 2906 2907@Component 2908struct PageOne { 2909 build() { 2910 NavDestination() { 2911 Text("pageOne") 2912 }.title("pageOne") 2913 } 2914} 2915 2916@Entry 2917@Component 2918struct Index { 2919 private stack: NavPathStack = new NavPathStack(); 2920 2921 @Builder 2922 PageBuilder(name: string) { 2923 PageOne() 2924 } 2925 2926 aboutToAppear() { 2927 this.getUIContext().getUIObserver().on('navDestinationUpdate', (info) => { 2928 console.info('NavDestination state update', JSON.stringify(info)); 2929 }); 2930 } 2931 2932 aboutToDisappear() { 2933 this.getUIContext().getUIObserver().off('navDestinationUpdate'); 2934 } 2935 2936 build() { 2937 Column() { 2938 Navigation(this.stack) { 2939 Button("push").onClick(() => { 2940 this.stack.pushPath({ name: "pageOne" }); 2941 }) 2942 } 2943 .title("Navigation") 2944 .navDestination(this.PageBuilder) 2945 } 2946 .width('100%') 2947 .height('100%') 2948 } 2949} 2950``` 2951 2952### off('navDestinationUpdate')<sup>11+</sup> 2953 2954off(type: 'navDestinationUpdate', callback?: Callback\<observer.NavDestinationInfo\>): void 2955 2956取消监听NavDestination组件的状态变化。 2957 2958**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2959 2960**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2961 2962**参数:** 2963 2964| 参数名 | 类型 | 必填 | 说明 | 2965| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 2966| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 | 2967| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 否 | 回调函数。返回当前的NavDestination组件状态。 | 2968 2969**示例:** 2970 2971参考[uiObserver.on('navDestinationUpdate')](#onnavdestinationupdate11)示例。 2972 2973### on('navDestinationUpdate')<sup>11+</sup> 2974 2975on(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback: Callback\<observer.NavDestinationInfo\>): void 2976 2977监听NavDestination组件的状态变化。 2978 2979**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 2980 2981**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2982 2983**参数:** 2984 2985| 参数名 | 类型 | 必填 | 说明 | 2986| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 2987| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 | 2988| options | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | 是 | 指定监听的Navigation的id。 | 2989| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 是 | 回调函数。返回当前的NavDestination组件状态。 | 2990 2991**示例:** 2992 2993<!--code_no_check--> 2994```ts 2995// Index.ets 2996// 演示 uiObserver.on('navDestinationUpdate', navigationId, callback) 2997// uiObserver.off('navDestinationUpdate', navigationId, callback) 2998@Component 2999struct PageOne { 3000 build() { 3001 NavDestination() { 3002 Text("pageOne") 3003 }.title("pageOne") 3004 } 3005} 3006 3007@Entry 3008@Component 3009struct Index { 3010 private stack: NavPathStack = new NavPathStack(); 3011 3012 @Builder 3013 PageBuilder(name: string) { 3014 PageOne() 3015 } 3016 3017 aboutToAppear() { 3018 this.getUIContext().getUIObserver().on('navDestinationUpdate', { navigationId: "testId" }, (info) => { 3019 console.info('NavDestination state update', JSON.stringify(info)); 3020 }); 3021 } 3022 3023 aboutToDisappear() { 3024 this.getUIContext().getUIObserver().off('navDestinationUpdate', { navigationId: "testId" }); 3025 } 3026 3027 build() { 3028 Column() { 3029 Navigation(this.stack) { 3030 Button("push").onClick(() => { 3031 this.stack.pushPath({ name: "pageOne" }); 3032 }) 3033 } 3034 .id("testId") 3035 .title("Navigation") 3036 .navDestination(this.PageBuilder) 3037 } 3038 .width('100%') 3039 .height('100%') 3040 } 3041} 3042``` 3043 3044### off('navDestinationUpdate')<sup>11+</sup> 3045 3046off(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback?: Callback\<observer.NavDestinationInfo\>): void 3047 3048取消监听NavDestination组件的状态变化。 3049 3050**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3051 3052**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3053 3054**参数:** 3055 3056| 参数名 | 类型 | 必填 | 说明 | 3057| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3058| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 | 3059| options | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | 是 | 指定监听的Navigation的id。 | 3060| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 否 | 回调函数。返回当前的NavDestination组件状态。 | 3061 3062**示例:** 3063 3064参考[uiObserver.on('navDestinationUpdate')](#onnavdestinationupdate11-1)示例。 3065 3066### on('scrollEvent')<sup>12+</sup> 3067 3068on(type: 'scrollEvent', callback: Callback\<observer.ScrollEventInfo\>): void 3069 3070监听滚动事件的开始和结束。 3071 3072**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3073 3074**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3075 3076**参数:** 3077 3078| 参数名 | 类型 | 必填 | 说明 | 3079| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 3080| type | string | 是 | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 | 3081| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\> | 是 | 回调函数。返回滚动事件的信息。 | 3082 3083**示例:** 3084 3085请参考[offscrollevent示例](#offscrollevent12-1) 3086 3087### off('scrollEvent')<sup>12+</sup> 3088 3089off(type: 'scrollEvent', callback?: Callback\<observer.ScrollEventInfo\>): void 3090 3091取消监听滚动事件的开始和结束。 3092 3093**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3094 3095**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3096 3097**参数:** 3098 3099| 参数名 | 类型 | 必填 | 说明 | 3100| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 3101| type | string | 是 | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 | 3102| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\> | 否 | 回调函数。返回滚动事件的信息。 | 3103 3104**示例:** 3105 3106请参考[offscrollevent示例](#offscrollevent12-1) 3107 3108### on('scrollEvent')<sup>12+</sup> 3109 3110on(type: 'scrollEvent', options: observer.ObserverOptions, callback: Callback\<observer.ScrollEventInfo\>): void 3111 3112监听滚动事件的开始和结束。 3113 3114**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3115 3116**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3117 3118**参数:** 3119 3120| 参数名 | 类型 | 必填 | 说明 | 3121| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3122| type | string | 是 | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 | 3123| options | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是 | Observer选项,包含指定监听的滚动组件的id。 | 3124| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\> | 是 | 回调函数。返回滚动事件的信息。 | 3125 3126**示例:** 3127 3128请参考[offscrollevent示例](#offscrollevent12-1) 3129 3130### off('scrollEvent')<sup>12+</sup> 3131 3132off(type: 'scrollEvent', options: observer.ObserverOptions, callback?: Callback\<observer.ScrollEventInfo\>): void 3133 3134取消监听滚动事件的开始和结束。 3135 3136**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3137 3138**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3139 3140**参数:** 3141 3142| 参数名 | 类型 | 必填 | 说明 | 3143| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3144| type | string | 是 | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 | 3145| options | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是 | Observer选项,包含指定监听的滚动组件的id。 | 3146| callback | Callback\<observer.[ScrollEventInfo](js-apis-arkui-observer.md#scrolleventinfo12)\> | 否 | 回调函数。返回滚动事件的信息。 | 3147 3148**示例:** 3149 3150```ts 3151import { UIObserver } from '@kit.ArkUI' 3152 3153@Entry 3154@Component 3155struct Index { 3156 scroller: Scroller = new Scroller() 3157 observer: UIObserver = new UIObserver() 3158 private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7] 3159 3160 build() { 3161 Row() { 3162 Column() { 3163 Scroll(this.scroller) { 3164 Column() { 3165 ForEach(this.arr, (item: number) => { 3166 Text(item.toString()) 3167 .width('90%') 3168 .height(150) 3169 .backgroundColor(0xFFFFFF) 3170 .borderRadius(15) 3171 .fontSize(16) 3172 .textAlign(TextAlign.Center) 3173 .margin({ top: 10 }) 3174 }, (item: string) => item) 3175 }.width('100%') 3176 } 3177 .id("testId") 3178 .height('80%') 3179 } 3180 .width('100%') 3181 3182 Row() { 3183 Button('UIObserver on') 3184 .onClick(() => { 3185 this.observer.on('scrollEvent', (info) => { 3186 console.info('scrollEventInfo', JSON.stringify(info)); 3187 }); 3188 }) 3189 Button('UIObserver off') 3190 .onClick(() => { 3191 this.observer.off('scrollEvent'); 3192 }) 3193 } 3194 3195 Row() { 3196 Button('UIObserverWithId on') 3197 .onClick(() => { 3198 this.observer.on('scrollEvent', { id:"testId" }, (info) => { 3199 console.info('scrollEventInfo', JSON.stringify(info)); 3200 }); 3201 }) 3202 Button('UIObserverWithId off') 3203 .onClick(() => { 3204 this.observer.off('scrollEvent', { id:"testId" }); 3205 }) 3206 } 3207 } 3208 .height('100%') 3209 } 3210} 3211``` 3212 3213### on('routerPageUpdate')<sup>11+</sup> 3214 3215on(type: 'routerPageUpdate', callback: Callback\<observer.RouterPageInfo\>): void 3216 3217监听router中page页面的状态变化。 3218 3219**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3220 3221**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3222 3223**参数:** 3224 3225| 参数名 | 类型 | 必填 | 说明 | 3226| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3227| type | string | 是 | 监听事件,固定为'routerPageUpdate',即router中page页面的状态变化。 | 3228| callback | Callback\<observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo)\> | 是 | 回调函数。携带pageInfo,返回当前的page页面状态。 | 3229 3230**示例:** 3231 3232```ts 3233import { UIContext, UIObserver } from '@kit.ArkUI'; 3234 3235let observer:UIObserver = this.getUIContext().getUIObserver(); 3236observer.on('routerPageUpdate', (info) => { 3237 console.info('RouterPage state updated, called by ' + `${info.name}`); 3238}); 3239``` 3240 3241### off('routerPageUpdate')<sup>11+</sup> 3242 3243off(type: 'routerPageUpdate', callback?: Callback\<observer.RouterPageInfo\>): void 3244 3245取消监听router中page页面的状态变化。 3246 3247**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3248 3249**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3250 3251**参数:** 3252 3253| 参数名 | 类型 | 必填 | 说明 | 3254| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3255| type | string | 是 | 监听事件,固定为'routerPageUpdate',即router中page页面的状态变化。 | 3256| callback | Callback\<observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo)\> | 否 | 需要被注销的回调函数。 | 3257 3258**示例:** 3259 3260```ts 3261import { UIContext, UIObserver } from '@kit.ArkUI'; 3262 3263let observer:UIObserver = this.getUIContext().getUIObserver(); 3264function callBackFunc(info:observer.RouterPageInfo) {}; 3265// callBackFunc is defined and used before 3266observer.off('routerPageUpdate', callBackFunc); 3267``` 3268 3269### on('densityUpdate')<sup>12+</sup> 3270 3271on(type: 'densityUpdate', callback: Callback\<observer.DensityInfo\>): void 3272 3273监听屏幕像素密度变化。 3274 3275**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3276 3277**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3278 3279**参数:** 3280 3281| 参数名 | 类型 | 必填 | 说明 | 3282| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3283| type | string | 是 | 监听事件,固定为'densityUpdate',即屏幕像素密度变化。 | 3284| callback | Callback\<observer.[DensityInfo](./js-apis-arkui-observer.md#densityinfo12)\> | 是 | 回调函数。携带densityInfo,返回变化后的屏幕像素密度。 | 3285 3286```ts 3287import { uiObserver } from '@kit.ArkUI'; 3288 3289@Entry 3290@Component 3291struct Index { 3292 @State density: number = 0; 3293 @State message: string = '未注册监听' 3294 3295 densityUpdateCallback = (info: uiObserver.DensityInfo) => { 3296 this.density = info.density; 3297 this.message = '变化后的DPI:' + this.density.toString(); 3298 } 3299 3300 build() { 3301 Column() { 3302 Text(this.message) 3303 .fontSize(24) 3304 .fontWeight(FontWeight.Bold) 3305 Button('注册屏幕像素密度变化监听') 3306 .onClick(() => { 3307 this.message = '已注册监听' 3308 this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback); 3309 }) 3310 } 3311 } 3312} 3313``` 3314 3315### off('densityUpdate')<sup>12+</sup> 3316 3317off(type: 'densityUpdate', callback?: Callback\<observer.DensityInfo\>): void 3318 3319取消监听屏幕像素密度的变化。 3320 3321**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3322 3323**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3324 3325**参数:** 3326 3327| 参数名 | 类型 | 必填 | 说明 | 3328| -------- | -------------------------------------------------------------------- | ---- | -------------------------------------------------------------------------------------------- | 3329| type | string | 是 | 监听事件,固定为'densityUpdate',即屏幕像素密度变化。 | 3330| callback | Callback\<observer.[DensityInfo](./js-apis-arkui-observer.md#densityinfo12)\> | 否 | 需要被注销的回调函数。若不指定具体的回调函数,则注销该UIContext下所有densityUpdate事件监听。 | 3331 3332```ts 3333import { uiObserver } from '@kit.ArkUI'; 3334 3335@Entry 3336@Component 3337struct Index { 3338 @State density: number = 0; 3339 @State message: string = '未注册监听' 3340 3341 densityUpdateCallback = (info: uiObserver.DensityInfo) => { 3342 this.density = info.density; 3343 this.message = '变化后的DPI:' + this.density.toString(); 3344 } 3345 3346 build() { 3347 Column() { 3348 Text(this.message) 3349 .fontSize(24) 3350 .fontWeight(FontWeight.Bold) 3351 Button('注册屏幕像素密度变化监听') 3352 .margin({ bottom: 10 }) 3353 .onClick(() => { 3354 this.message = '已注册监听' 3355 this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback); 3356 }) 3357 Button('解除注册屏幕像素密度变化监听') 3358 .onClick(() => { 3359 this.message = '未注册监听' 3360 this.getUIContext().getUIObserver().off('densityUpdate', this.densityUpdateCallback); 3361 }) 3362 } 3363 } 3364} 3365``` 3366 3367### on('willDraw')<sup>12+</sup> 3368 3369on(type: 'willDraw', callback: Callback\<void\>): void 3370 3371监听每一帧绘制指令下发情况。 3372 3373**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3374 3375**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3376 3377**参数:** 3378 3379| 参数名 | 类型 | 必填 | 说明 | 3380| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3381| type | string | 是 | 监听事件,固定为'willDraw',即是否将要绘制。 | 3382| callback | Callback\<void\> | 是 | 回调函数。 | 3383 3384```ts 3385import { uiObserver } from '@kit.ArkUI'; 3386 3387@Entry 3388@Component 3389struct Index { 3390 willDrawCallback = () => { 3391 console.info("willDraw指令下发"); 3392 } 3393 build() { 3394 Column() { 3395 Button('注册绘制指令下发监听') 3396 .onClick(() => { 3397 this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback); 3398 }) 3399 } 3400 } 3401} 3402``` 3403 3404### off('willDraw')<sup>12+</sup> 3405 3406off(type: 'willDraw', callback?: Callback\<void\>): void 3407 3408取消监听每一帧绘制指令下发情况。 3409 3410**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3411 3412**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3413 3414**参数:** 3415 3416| 参数名 | 类型 | 必填 | 说明 | 3417| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3418| type | string | 是 | 监听事件,固定为'willDraw',即是否将要绘制。 | 3419| callback | Callback\<void\> | 否 | 需要被注销的回调函数。 | 3420 3421```ts 3422import { uiObserver } from '@kit.ArkUI'; 3423 3424@Entry 3425@Component 3426struct Index { 3427 willDrawCallback = () => { 3428 console.info("willDraw指令下发") 3429 } 3430 3431 build() { 3432 Column() { 3433 Button('注册绘制指令下发监听') 3434 .margin({ bottom: 10 }) 3435 .onClick(() => { 3436 this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback); 3437 }) 3438 Button('解除注册绘制指令下发监听') 3439 .onClick(() => { 3440 this.getUIContext().getUIObserver().off('willDraw', this.willDrawCallback); 3441 }) 3442 } 3443 } 3444} 3445``` 3446 3447### on('didLayout')<sup>12+</sup> 3448 3449on(type: 'didLayout', callback: Callback\<void\>): void 3450 3451监听每一帧布局完成情况。 3452 3453**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3454 3455**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3456 3457**参数:** 3458 3459| 参数名 | 类型 | 必填 | 说明 | 3460| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3461| type | string | 是 | 监听事件,固定为'didLayout',即是否布局完成。 | 3462| callback | Callback\<void\> | 是 | 回调函数。 | 3463 3464```ts 3465import { uiObserver } from '@kit.ArkUI'; 3466 3467@Entry 3468@Component 3469struct Index { 3470 didLayoutCallback = () => { 3471 console.info("layout布局完成"); 3472 } 3473 build() { 3474 Column() { 3475 Button('注册布局完成监听') 3476 .onClick(() => { 3477 this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback); 3478 }) 3479 } 3480 } 3481} 3482``` 3483 3484### off('didLayout')<sup>12+</sup> 3485 3486off(type: 'didLayout', callback?: Callback\<void\>): void 3487 3488取消监听每一帧布局完成情况。 3489 3490**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3491 3492**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3493 3494**参数:** 3495 3496| 参数名 | 类型 | 必填 | 说明 | 3497| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3498| type | string | 是 | 监听事件,固定为'didLayout',即是否将要绘制。 | 3499| callback | Callback\<void\> | 否 | 需要被注销的回调函数。 | 3500 3501```ts 3502import { uiObserver } from '@kit.ArkUI'; 3503 3504@Entry 3505@Component 3506struct Index { 3507 didLayoutCallback = () => { 3508 console.info("layout布局完成") 3509 } 3510 3511 build() { 3512 Column() { 3513 Button('注册布局完成监听') 3514 .margin({ bottom: 10 }) 3515 .onClick(() => { 3516 this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback); 3517 }) 3518 Button('解除注册注册布局完成监听') 3519 .onClick(() => { 3520 this.getUIContext().getUIObserver().off('didLayout', this.didLayoutCallback); 3521 }) 3522 } 3523 } 3524} 3525``` 3526 3527### on('navDestinationSwitch')<sup>12+</sup> 3528 3529on(type: 'navDestinationSwitch', callback: Callback\<observer.NavDestinationSwitchInfo\>): void 3530 3531监听Navigation的页面切换事件。 3532 3533**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3534 3535**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3536 3537**参数:** 3538 3539| 参数名 | 类型 | 必填 | 说明 | 3540| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3541| type | string | 是 | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 | 3542| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\> | 是 | 回调函数。携带NavDestinationSwitchInfo,返回页面切换事件的信息。 | 3543 3544**示例:** 3545 3546```ts 3547// Index.ets 3548// 演示 UIObserver.on('navDestinationSwitch', callback) 3549// UIObserver.off('navDestinationSwitch', callback) 3550import { uiObserver } from '@kit.ArkUI'; 3551 3552@Component 3553struct PageOne { 3554 build() { 3555 NavDestination() { 3556 Text("pageOne") 3557 }.title("pageOne") 3558 } 3559} 3560 3561function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) { 3562 console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`) 3563} 3564 3565@Entry 3566@Component 3567struct Index { 3568 private stack: NavPathStack = new NavPathStack(); 3569 3570 @Builder 3571 PageBuilder(name: string) { 3572 PageOne() 3573 } 3574 3575 aboutToAppear() { 3576 let obs = this.getUIContext().getUIObserver(); 3577 obs.on('navDestinationSwitch', callBackFunc); 3578 } 3579 3580 aboutToDisappear() { 3581 let obs = this.getUIContext().getUIObserver(); 3582 obs.off('navDestinationSwitch', callBackFunc); 3583 } 3584 3585 build() { 3586 Column() { 3587 Navigation(this.stack) { 3588 Button("push").onClick(() => { 3589 this.stack.pushPath({name: "pageOne"}); 3590 }) 3591 } 3592 .title("Navigation") 3593 .navDestination(this.PageBuilder) 3594 } 3595 .width('100%') 3596 .height('100%') 3597 } 3598} 3599``` 3600 3601### off('navDestinationSwitch')<sup>12+</sup> 3602 3603off(type: 'navDestinationSwitch', callback?: Callback\<observer.NavDestinationSwitchInfo\>): void 3604 3605取消监听Navigation的页面切换事件。 3606 3607**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3608 3609**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3610 3611**参数:** 3612 3613| 参数名 | 类型 | 必填 | 说明 | 3614| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3615| type | string | 是 | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 | 3616| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\> | 否 | 需要被注销的回调函数。 | 3617 3618**示例代码参考上述UIObserver.on('navDestinationSwitch')接口的示例代码** 3619 3620### on('navDestinationSwitch')<sup>12+</sup> 3621 3622on(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback: Callback\<observer.NavDestinationSwitchInfo\>): void 3623 3624监听Navigation的页面切换事件。 3625 3626**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3627 3628**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3629 3630**参数:** 3631 3632| 参数名 | 类型 | 必填 | 说明 | 3633| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3634| type | string | 是 | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 | 3635| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12) | 是 | 监听选项。 | 3636| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\> | 是 | 回调函数。携带NavDestinationSwitchInfo,返回页面切换事件的信息。 | 3637 3638**示例:** 3639 3640```ts 3641// Index.ets 3642// 演示 UIObserver.on('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback) 3643// UIObserver.off('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback) 3644import { uiObserver } from '@kit.ArkUI'; 3645 3646@Component 3647struct PageOne { 3648 build() { 3649 NavDestination() { 3650 Text("pageOne") 3651 }.title("pageOne") 3652 } 3653} 3654 3655function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) { 3656 console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`) 3657} 3658 3659@Entry 3660@Component 3661struct Index { 3662 private stack: NavPathStack = new NavPathStack(); 3663 3664 @Builder 3665 PageBuilder(name: string) { 3666 PageOne() 3667 } 3668 3669 aboutToAppear() { 3670 let obs = this.getUIContext().getUIObserver(); 3671 obs.on('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc) 3672 } 3673 3674 aboutToDisappear() { 3675 let obs = this.getUIContext().getUIObserver(); 3676 obs.off('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc) 3677 } 3678 3679 build() { 3680 Column() { 3681 Navigation(this.stack) { 3682 Button("push").onClick(() => { 3683 this.stack.pushPath({name: "pageOne"}); 3684 }) 3685 } 3686 .id("myNavId") 3687 .title("Navigation") 3688 .navDestination(this.PageBuilder) 3689 } 3690 .width('100%') 3691 .height('100%') 3692 } 3693} 3694``` 3695 3696### off('navDestinationSwitch')<sup>12+</sup> 3697 3698off(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback?: Callback\<observer.NavDestinationSwitchInfo\>): void 3699 3700取消监听Navigation的页面切换事件。 3701 3702**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3703 3704**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3705 3706**参数:** 3707 3708| 参数名 | 类型 | 必填 | 说明 | 3709| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3710| type | string | 是 | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 | 3711| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12) | 是 | 监听选项。 | 3712| callback | Callback\<observer.[NavDestinationSwitchInfo](js-apis-arkui-observer.md#navdestinationswitchinfo12)\> | 否 | 需要被注销的回调函数。 | 3713 3714**示例代码参考上述UIObserver.on('navDestinationSwitch')接口的示例代码** 3715 3716### on('willClick')<sup>12+</sup> 3717 3718on(type: 'willClick', callback: GestureEventListenerCallback): void 3719 3720监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3721 3722**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3723 3724**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3725 3726**参数:** 3727 3728| 参数名 | 类型 | 必填 | 说明 | 3729| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3730| type | string | 是 | 监听事件,固定为'willClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发前触发。 | 3731| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 是 | 回调函数。可以获得点击事件的GestureEvent和组件的FrameNode。 | 3732 3733**示例:** 3734 3735```ts 3736// 在页面Component中使用 3737import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3738 3739// callback是开发者定义的监听回调函数 3740let callback = (event: GestureEvent, frameNode?: FrameNode) => {}; 3741let observer: UIObserver = this.getUIContext().getUIObserver(); 3742observer.on('willClick', callback); 3743``` 3744 3745### off('willClick')<sup>12+</sup> 3746 3747off(type: 'willClick', callback?: GestureEventListenerCallback): void 3748 3749取消监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3750 3751**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3752 3753**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3754 3755**参数:** 3756 3757| 参数名 | 类型 | 必填 | 说明 | 3758| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | 3759| type | string | 是 | 监听事件,固定为'willClick',即点击事件指令下发情况。 | 3760| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 否 | 需要被注销的回调函数。 | 3761 3762**示例:** 3763 3764```ts 3765// 在页面Component中使用 3766import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3767 3768// callback是开发者定义的监听回调函数 3769let callback = (event: GestureEvent, frameNode?: FrameNode) => {}; 3770let observer: UIObserver = this.getUIContext().getUIObserver(); 3771observer.off('willClick', callback); 3772``` 3773 3774### on('didClick')<sup>12+</sup> 3775 3776on(type: 'didClick', callback: GestureEventListenerCallback): void 3777 3778监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3779 3780**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3781 3782**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3783 3784**参数:** 3785 3786| 参数名 | 类型 | 必填 | 说明 | 3787| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3788| type | string | 是 | 监听事件,固定为'didClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发后触发。 | 3789| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 是 | 回调函数。可以获得点击事件的GestureEvent和组件的FrameNode。 | 3790 3791**示例:** 3792 3793```ts 3794// 在页面Component中使用 3795import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3796 3797// callback是开发者定义的监听回调函数 3798let callback = (event: GestureEvent, frameNode?: FrameNode) => {}; 3799let observer: UIObserver = this.getUIContext().getUIObserver(); 3800observer.on('didClick', callback); 3801``` 3802 3803### off('didClick')<sup>12+</sup> 3804 3805off(type: 'didClick', callback?: GestureEventListenerCallback): void 3806 3807取消监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3808 3809**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3810 3811**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3812 3813**参数:** 3814 3815| 参数名 | 类型 | 必填 | 说明 | 3816| -------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------- | 3817| type | string | 是 | 监听事件,固定为'didClick',即点击事件指令下发情况。 | 3818| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 否 | 需要被注销的回调函数。 | 3819 3820**示例:** 3821 3822```ts 3823// 在页面Component中使用 3824import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3825 3826// callback是开发者定义的监听回调函数 3827let callback = (event: GestureEvent, frameNode?: FrameNode) => {}; 3828let observer: UIObserver = this.getUIContext().getUIObserver(); 3829observer.off('didClick', callback); 3830``` 3831 3832### on('willClick')<sup>12+</sup> 3833 3834on(type: 'willClick', callback: ClickEventListenerCallback): void 3835 3836监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3837 3838**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3839 3840**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3841 3842**参数:** 3843 3844| 参数名 | 类型 | 必填 | 说明 | 3845| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | 3846| type | string | 是 | 监听事件,固定为'willClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发前触发。 | 3847| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 是 | 回调函数。可以获得点击事件的ClickEvent和组件的FrameNode。 | 3848 3849**示例:** 3850 3851```ts 3852// 在页面Component中使用 3853import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3854 3855// callback是开发者定义的监听回调函数 3856let callback = (event: ClickEvent, frameNode?: FrameNode) => {}; 3857let observer: UIObserver = this.getUIContext().getUIObserver(); 3858observer.on('willClick', callback); 3859``` 3860 3861### off('willClick')<sup>12+</sup> 3862 3863off(type: 'willClick', callback?: ClickEventListenerCallback): void 3864 3865取消监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3866 3867**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3868 3869**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3870 3871**参数:** 3872 3873| 参数名 | 类型 | 必填 | 说明 | 3874| -------- | ----------------------------------------------------------- | ---- | ----------------------------------------------------- | 3875| type | string | 是 | 监听事件,固定为'willClick',即点击事件指令下发情况。 | 3876| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 否 | 需要被注销的回调函数。 | 3877 3878**示例:** 3879 3880```ts 3881// 在页面Component中使用 3882import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3883 3884// callback是开发者定义的监听回调函数 3885let callback = (event: ClickEvent, frameNode?: FrameNode) => {}; 3886let observer: UIObserver = this.getUIContext().getUIObserver(); 3887observer.off('willClick', callback); 3888``` 3889 3890### on('didClick')<sup>12+</sup> 3891 3892on(type: 'didClick', callback: ClickEventListenerCallback): void 3893 3894监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3895 3896**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3897 3898**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3899 3900**参数:** 3901 3902| 参数名 | 类型 | 必填 | 说明 | 3903| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | 3904| type | string | 是 | 监听事件,固定为'didClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发后触发。 | 3905| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 是 | 回调函数。可以获得点击事件的ClickEvent和组件的FrameNode。 | 3906 3907**示例:** 3908 3909```ts 3910// 在页面Component中使用 3911import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3912 3913// callback是开发者定义的监听回调函数 3914let callback = (event: ClickEvent, frameNode?: FrameNode) => {}; 3915let observer: UIObserver = this.getUIContext().getUIObserver(); 3916observer.on('didClick', callback); 3917``` 3918 3919### off('didClick')<sup>12+</sup> 3920 3921off(type: 'didClick', callback?: ClickEventListenerCallback): void 3922 3923取消监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。 3924 3925**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3926 3927**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3928 3929**参数:** 3930 3931| 参数名 | 类型 | 必填 | 说明 | 3932| -------- | ----------------------------------------------------------- | ---- | ---------------------------------------------------- | 3933| type | string | 是 | 监听事件,固定为'didClick',即点击事件指令下发情况。 | 3934| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 否 | 需要被注销的回调函数。 | 3935 3936**示例:** 3937 3938```ts 3939// 在页面Component中使用 3940import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI'; 3941 3942// callback是开发者定义的监听回调函数 3943let callback = (event: ClickEvent, frameNode?: FrameNode) => {}; 3944let observer: UIObserver = this.getUIContext().getUIObserver(); 3945observer.off('didClick', callback); 3946``` 3947 3948### on('tabContentUpdate')<sup>12+</sup> 3949 3950on(type: 'tabContentUpdate', callback: Callback\<observer.TabContentInfo\>): void 3951 3952监听TabContent页面的切换事件。 3953 3954**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 3955 3956**系统能力:** SystemCapability.ArkUI.ArkUI.Full 3957 3958**参数:** 3959 3960| 参数名 | 类型 | 必填 | 说明 | 3961| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3962| type | string | 是 | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 | 3963| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | 是 | 回调函数。携带TabContentInfo,返回TabContent页面切换事件的信息。 | 3964 3965**示例:** 3966 3967```ts 3968import { uiObserver } from '@kit.ArkUI'; 3969 3970function callbackFunc(info: uiObserver.TabContentInfo) { 3971 console.info('tabContentUpdate', JSON.stringify(info)); 3972} 3973 3974@Entry 3975@Component 3976struct TabsExample { 3977 3978 aboutToAppear(): void { 3979 let observer = this.getUIContext().getUIObserver(); 3980 observer.on('tabContentUpdate', callbackFunc); 3981 } 3982 3983 aboutToDisappear(): void { 3984 let observer = this.getUIContext().getUIObserver(); 3985 observer.off('tabContentUpdate', callbackFunc); 3986 } 3987 3988 build() { 3989 Column() { 3990 Tabs() { 3991 TabContent() { 3992 Column().width('100%').height('100%').backgroundColor('#00CB87') 3993 }.tabBar('green').id('tabContentId0') 3994 3995 TabContent() { 3996 Column().width('100%').height('100%').backgroundColor('#007DFF') 3997 }.tabBar('blue').id('tabContentId1') 3998 3999 TabContent() { 4000 Column().width('100%').height('100%').backgroundColor('#FFBF00') 4001 }.tabBar('yellow').id('tabContentId2') 4002 4003 TabContent() { 4004 Column().width('100%').height('100%').backgroundColor('#E67C92') 4005 }.tabBar('pink').id('tabContentId3') 4006 } 4007 .width(360) 4008 .height(296) 4009 .backgroundColor('#F1F3F5') 4010 .id('tabsId') 4011 }.width('100%') 4012 } 4013} 4014``` 4015 4016### off('tabContentUpdate')<sup>12+</sup> 4017 4018off(type: 'tabContentUpdate', callback?: Callback\<observer.TabContentInfo\>): void 4019 4020取消监听TabContent页面的切换事件。 4021 4022**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 4023 4024**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4025 4026**参数:** 4027 4028| 参数名 | 类型 | 必填 | 说明 | 4029| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 4030| type | string | 是 | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 | 4031| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | 否 | 需要被注销的回调函数。 | 4032 4033**示例:** 4034 4035参考[on('tabContentUpdate')](#ontabcontentupdate12)接口示例。 4036 4037### on('tabContentUpdate')<sup>12+</sup> 4038 4039on(type: 'tabContentUpdate', options: observer.ObserverOptions, callback: Callback\<observer.TabContentInfo\>): void 4040 4041监听TabContent页面的切换事件。 4042 4043**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 4044 4045**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4046 4047**参数:** 4048 4049| 参数名 | 类型 | 必填 | 说明 | 4050| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 4051| type | string | 是 | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 | 4052| options | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是 | 指定监听的Tabs组件的id。 | 4053| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | 是 | 回调函数。携带TabContentInfo,返回TabContent页面切换事件的信息。 | 4054 4055**示例:** 4056 4057```ts 4058import { uiObserver } from '@kit.ArkUI'; 4059 4060function callbackFunc(info: uiObserver.TabContentInfo) { 4061 console.info('tabContentUpdate', JSON.stringify(info)); 4062} 4063 4064@Entry 4065@Component 4066struct TabsExample { 4067 4068 aboutToAppear(): void { 4069 let observer = this.getUIContext().getUIObserver(); 4070 observer.on('tabContentUpdate', { id: 'tabsId' }, callbackFunc); 4071 } 4072 4073 aboutToDisappear(): void { 4074 let observer = this.getUIContext().getUIObserver(); 4075 observer.off('tabContentUpdate', { id: 'tabsId' }, callbackFunc); 4076 } 4077 4078 build() { 4079 Column() { 4080 Tabs() { 4081 TabContent() { 4082 Column().width('100%').height('100%').backgroundColor('#00CB87') 4083 }.tabBar('green').id('tabContentId0') 4084 4085 TabContent() { 4086 Column().width('100%').height('100%').backgroundColor('#007DFF') 4087 }.tabBar('blue').id('tabContentId1') 4088 4089 TabContent() { 4090 Column().width('100%').height('100%').backgroundColor('#FFBF00') 4091 }.tabBar('yellow').id('tabContentId2') 4092 4093 TabContent() { 4094 Column().width('100%').height('100%').backgroundColor('#E67C92') 4095 }.tabBar('pink').id('tabContentId3') 4096 } 4097 .width(360) 4098 .height(296) 4099 .backgroundColor('#F1F3F5') 4100 .id('tabsId') 4101 }.width('100%') 4102 } 4103} 4104``` 4105 4106### off('tabContentUpdate')<sup>12+</sup> 4107 4108off(type: 'tabContentUpdate', options: observer.ObserverOptions, callback?: Callback\<observer.TabContentInfo\>): void 4109 4110取消监听TabContent页面的切换事件。 4111 4112**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 4113 4114**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4115 4116**参数:** 4117 4118| 参数名 | 类型 | 必填 | 说明 | 4119| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 4120| type | string | 是 | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 | 4121| options | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是 | 指定监听的Tabs组件的id。 | 4122| callback | Callback\<observer.[TabContentInfo](js-apis-arkui-observer.md#tabcontentinfo12)\> | 否 | 需要被注销的回调函数。 | 4123 4124**示例:** 4125 4126参考[on('tabContentUpdate')](#ontabcontentupdate12-1)接口示例。 4127 4128## GestureEventListenerCallback<sup>12+</sup> 4129type GestureEventListenerCallback = (event: GestureEvent, node?: FrameNode) => void 4130 4131ArkTS GestureEvent事件监听函数类型。 4132 4133**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 4134 4135**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4136 4137**参数:** 4138 4139| 参数名 | 类型 | 必填 | 说明 | 4140| ------- | ------ | ---- | --------------------------- | 4141| event | [GestureEvent](../apis-arkui/arkui-ts/ts-gesture-settings.md#gestureevent对象说明) | 是 | 触发事件监听的手势事件的相关信息。 | 4142| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | 否 | 触发事件监听的手势事件所绑定的组件。 | 4143 4144## ClickEventListenerCallback<sup>12+</sup> 4145type ClickEventListenerCallback = (event: ClickEvent, node?: FrameNode) => void 4146 4147ArkTS GestureEvent事件监听函数类型。 4148 4149**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 4150 4151**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4152 4153**参数:** 4154 4155| 参数名 | 类型 | 必填 | 说明 | 4156| ------- | ------ | ---- | --------------------------- | 4157| event | [ClickEvent](../apis-arkui/arkui-ts/ts-universal-events-click.md#clickevent对象说明) | 是 | 触发事件监听的点击事件的相关信息。 | 4158| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | 否 | 触发事件监听的点击事件所绑定的组件。 | 4159 4160## MediaQuery 4161 4162以下API需先使用UIContext中的[getMediaQuery()](#getmediaquery)方法获取到MediaQuery对象,再通过该对象调用对应方法。 4163 4164### matchMediaSync 4165 4166matchMediaSync(condition: string): mediaQuery.MediaQueryListener 4167 4168设置媒体查询的查询条件,并返回对应的监听句柄。 4169 4170**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4171 4172**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4173 4174**参数:** 4175 4176| 参数名 | 类型 | 必填 | 说明 | 4177| --------- | ------ | ---- | ---------------------------------------- | 4178| condition | string | 是 | 媒体事件的匹配条件,具体可参考[媒体查询语法规则](../../ui/arkts-layout-development-media-query.md#语法规则)。 | 4179 4180**返回值:** 4181 4182| 类型 | 说明 | 4183| ------------------------------------------------------------ | -------------------------------------------- | 4184| [mediaQuery.MediaQueryListener](js-apis-mediaquery.md#mediaquerylistener) | 媒体事件监听句柄,用于注册和去注册监听回调。 | 4185 4186**示例:** 4187 4188<!--code_no_check--> 4189```ts 4190import { MediaQuery } from '@kit.ArkUI'; 4191 4192let mediaquery: MediaQuery = uiContext.getMediaQuery(); 4193let listener = mediaquery.matchMediaSync('(orientation: landscape)'); //监听横屏事件 4194``` 4195 4196## Router 4197 4198以下API需先使用UIContext中的[getRouter()](#getrouter)方法获取到Router对象,再通过该对象调用对应方法。 4199 4200### pushUrl 4201 4202pushUrl(options: router.RouterOptions): Promise<void> 4203 4204跳转到应用内的指定页面,通过Promise获取跳转异常的返回结果。 4205 4206**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4207 4208**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4209 4210**参数:** 4211 4212| 参数名 | 类型 | 必填 | 说明 | 4213| ------- | ---------------------------------------- | ---- | --------- | 4214| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 | 4215 4216**返回值:** 4217 4218| 类型 | 说明 | 4219| ------------------- | ------- | 4220| Promise<void> | 异常返回结果。 | 4221 4222**错误码:** 4223 4224以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4225 4226| 错误码ID | 错误信息 | 4227| ------ | ---------------------------------- | 4228| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4229| 100001 | Internal error. | 4230| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. | 4231| 100003 | Page stack error. Too many pages are pushed. | 4232 4233**示例:** 4234 4235```ts 4236import { BusinessError } from '@kit.BasicServicesKit' 4237 4238@Entry 4239@Component 4240struct Index { 4241 async routePage() { 4242 this.getUIContext().getRouter().pushUrl({ 4243 url: 'pages/routerpage2', 4244 params: { 4245 data1: 'message', 4246 data2: { 4247 data3: [123, 456, 789] 4248 } 4249 } 4250 }) 4251 .then(() => { 4252 console.info('succeeded') 4253 }) 4254 .catch((error: BusinessError) => { 4255 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4256 }) 4257 } 4258 4259 build() { 4260 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4261 Button() { 4262 Text('next page') 4263 .fontSize(25) 4264 .fontWeight(FontWeight.Bold) 4265 }.type(ButtonType.Capsule) 4266 .margin({ top: 20 }) 4267 .backgroundColor('#ccc') 4268 .onClick(() => { 4269 this.routePage() 4270 }) 4271 } 4272 .width('100%') 4273 .height('100%') 4274 } 4275} 4276``` 4277 4278### pushUrl 4279 4280pushUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void 4281 4282跳转到应用内的指定页面。 4283 4284**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4285 4286**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4287 4288**参数:** 4289 4290| 参数名 | 类型 | 必填 | 说明 | 4291| -------- | ---------------------------------------- | ---- | --------- | 4292| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 | 4293| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 4294 4295**错误码:** 4296 4297以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4298 4299| 错误码ID | 错误信息 | 4300| ------ | ---------------------------------- | 4301| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4302| 100001 | Internal error. | 4303| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. | 4304| 100003 | Page stack error. Too many pages are pushed. | 4305 4306**示例:** 4307 4308```ts 4309import { BusinessError } from '@kit.BasicServicesKit' 4310 4311@Entry 4312@Component 4313struct Index { 4314 async routePage() { 4315 this.getUIContext().getRouter().pushUrl({ 4316 url: 'pages/routerpage2', 4317 params: { 4318 data1: 'message', 4319 data2: { 4320 data3: [123, 456, 789] 4321 } 4322 } 4323 }, (err: Error) => { 4324 if (err) { 4325 let message = (err as BusinessError).message; 4326 let code = (err as BusinessError).code; 4327 console.error(`pushUrl failed, code is ${code}, message is ${message}`); 4328 return; 4329 } 4330 console.info('pushUrl success'); 4331 }) 4332 } 4333 4334 build() { 4335 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4336 Button() { 4337 Text('next page') 4338 .fontSize(25) 4339 .fontWeight(FontWeight.Bold) 4340 }.type(ButtonType.Capsule) 4341 .margin({ top: 20 }) 4342 .backgroundColor('#ccc') 4343 .onClick(() => { 4344 this.routePage() 4345 }) 4346 } 4347 .width('100%') 4348 .height('100%') 4349 } 4350} 4351``` 4352 4353### pushUrl 4354 4355pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void> 4356 4357跳转到应用内的指定页面,通过Promise获取跳转异常的返回结果。 4358 4359**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4360 4361**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4362 4363**参数:** 4364 4365| 参数名 | 类型 | 必填 | 说明 | 4366| ------- | ---------------------------------------- | ---- | ---------- | 4367| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 | 4368| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 4369 4370**返回值:** 4371 4372| 类型 | 说明 | 4373| ------------------- | ------- | 4374| Promise<void> | 异常返回结果。 | 4375 4376**错误码:** 4377 4378以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4379 4380| 错误码ID | 错误信息 | 4381| ------ | ---------------------------------- | 4382| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4383| 100001 | Internal error. | 4384| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. | 4385| 100003 | Page stack error. Too many pages are pushed. | 4386 4387**示例:** 4388 4389```ts 4390import { router } from '@kit.ArkUI'; 4391import { BusinessError } from '@kit.BasicServicesKit' 4392 4393class RouterTmp { 4394 Standard: router.RouterMode = router.RouterMode.Standard 4395} 4396 4397let rtm: RouterTmp = new RouterTmp() 4398 4399@Entry 4400@Component 4401struct Index { 4402 async routePage() { 4403 this.getUIContext().getRouter().pushUrl({ 4404 url: 'pages/routerpage2', 4405 params: { 4406 data1: 'message', 4407 data2: { 4408 data3: [123, 456, 789] 4409 } 4410 } 4411 }, rtm.Standard) 4412 .then(() => { 4413 console.info('succeeded') 4414 }) 4415 .catch((error: BusinessError) => { 4416 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4417 }) 4418 } 4419 4420 build() { 4421 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4422 Button() { 4423 Text('next page') 4424 .fontSize(25) 4425 .fontWeight(FontWeight.Bold) 4426 }.type(ButtonType.Capsule) 4427 .margin({ top: 20 }) 4428 .backgroundColor('#ccc') 4429 .onClick(() => { 4430 this.routePage() 4431 }) 4432 } 4433 .width('100%') 4434 .height('100%') 4435 } 4436} 4437``` 4438 4439### pushUrl 4440 4441pushUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 4442 4443跳转到应用内的指定页面。 4444 4445**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4446 4447**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4448 4449**参数:** 4450 4451| 参数名 | 类型 | 必填 | 说明 | 4452| -------- | ---------------------------------------- | ---- | ---------- | 4453| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 | 4454| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 4455| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 4456 4457**错误码:** 4458 4459以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4460 4461| 错误码ID | 错误信息 | 4462| ------ | ---------------------------------- | 4463| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4464| 100001 | Internal error. | 4465| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. | 4466| 100003 | Page stack error. Too many pages are pushed. | 4467 4468**示例:** 4469 4470```ts 4471import { router } from '@kit.ArkUI'; 4472import { BusinessError } from '@kit.BasicServicesKit' 4473 4474class RouterTmp { 4475 Standard: router.RouterMode = router.RouterMode.Standard 4476} 4477 4478let rtm: RouterTmp = new RouterTmp() 4479 4480@Entry 4481@Component 4482struct Index { 4483 async routePage() { 4484 this.getUIContext().getRouter().pushUrl({ 4485 url: 'pages/routerpage2', 4486 params: { 4487 data1: 'message', 4488 data2: { 4489 data3: [123, 456, 789] 4490 } 4491 } 4492 }, rtm.Standard, (err) => { 4493 if (err) { 4494 let message = (err as BusinessError).message; 4495 let code = (err as BusinessError).code; 4496 console.error(`pushUrl failed, code is ${code}, message is ${message}`); 4497 return; 4498 } 4499 console.info('pushUrl success'); 4500 }) 4501 } 4502 4503 build() { 4504 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4505 Button() { 4506 Text('next page') 4507 .fontSize(25) 4508 .fontWeight(FontWeight.Bold) 4509 }.type(ButtonType.Capsule) 4510 .margin({ top: 20 }) 4511 .backgroundColor('#ccc') 4512 .onClick(() => { 4513 this.routePage() 4514 }) 4515 } 4516 .width('100%') 4517 .height('100%') 4518 } 4519} 4520``` 4521 4522### replaceUrl 4523 4524replaceUrl(options: router.RouterOptions): Promise<void> 4525 4526用应用内的某个页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回的结果。 4527 4528**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4529 4530**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4531 4532**参数:** 4533 4534| 参数名 | 类型 | 必填 | 说明 | 4535| ------- | ---------------------------------------- | ---- | --------- | 4536| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 | 4537 4538**返回值:** 4539 4540| 类型 | 说明 | 4541| ------------------- | ------- | 4542| Promise<void> | 异常返回结果。 | 4543 4544**错误码:** 4545 4546以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4547 4548| 错误码ID | 错误信息 | 4549| ------ | ---------------------------------------- | 4550| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4551| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 4552| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. | 4553 4554**示例:** 4555 4556```ts 4557import { BusinessError } from '@kit.BasicServicesKit' 4558 4559@Entry 4560@Component 4561struct Index { 4562 async routePage() { 4563 this.getUIContext().getRouter().replaceUrl({ 4564 url: 'pages/detail', 4565 params: { 4566 data1: 'message' 4567 } 4568 }) 4569 .then(() => { 4570 console.info('succeeded') 4571 }) 4572 .catch((error: BusinessError) => { 4573 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4574 }) 4575 } 4576 4577 build() { 4578 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4579 Button() { 4580 Text('next page') 4581 .fontSize(25) 4582 .fontWeight(FontWeight.Bold) 4583 }.type(ButtonType.Capsule) 4584 .margin({ top: 20 }) 4585 .backgroundColor('#ccc') 4586 .onClick(() => { 4587 this.routePage() 4588 }) 4589 } 4590 .width('100%') 4591 .height('100%') 4592 } 4593} 4594``` 4595 4596### replaceUrl 4597 4598replaceUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void 4599 4600用应用内的某个页面替换当前页面,并销毁被替换的页面。 4601 4602**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4603 4604**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4605 4606**参数:** 4607 4608| 参数名 | 类型 | 必填 | 说明 | 4609| -------- | ---------------------------------------- | ---- | --------- | 4610| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 | 4611| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 4612 4613**错误码:** 4614 4615以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4616 4617| 错误码ID | 错误信息 | 4618| ------ | ---------------------------------------- | 4619| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4620| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 4621| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. | 4622 4623**示例:** 4624 4625```ts 4626import { BusinessError } from '@kit.BasicServicesKit' 4627 4628@Entry 4629@Component 4630struct Index { 4631 async routePage() { 4632 this.getUIContext().getRouter().replaceUrl({ 4633 url: 'pages/detail', 4634 params: { 4635 data1: 'message' 4636 } 4637 }, (err: Error) => { 4638 if (err) { 4639 let message = (err as BusinessError).message; 4640 let code = (err as BusinessError).code; 4641 console.error(`replaceUrl failed, code is ${code}, message is ${message}`); 4642 return; 4643 } 4644 console.info('replaceUrl success'); 4645 }) 4646 } 4647 4648 build() { 4649 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4650 Button() { 4651 Text('next page') 4652 .fontSize(25) 4653 .fontWeight(FontWeight.Bold) 4654 }.type(ButtonType.Capsule) 4655 .margin({ top: 20 }) 4656 .backgroundColor('#ccc') 4657 .onClick(() => { 4658 this.routePage() 4659 }) 4660 } 4661 .width('100%') 4662 .height('100%') 4663 } 4664} 4665``` 4666 4667### replaceUrl 4668 4669replaceUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void> 4670 4671用应用内的某个页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。 4672 4673**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4674 4675**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4676 4677**参数:** 4678 4679| 参数名 | 类型 | 必填 | 说明 | 4680| ------- | ---------------------------------------- | ---- | ---------- | 4681| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 | 4682| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 4683 4684**返回值:** 4685 4686| 类型 | 说明 | 4687| ------------------- | ------- | 4688| Promise<void> | 异常返回结果。 | 4689 4690**错误码:** 4691 4692以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4693 4694| 错误码ID | 错误信息 | 4695| ------ | ---------------------------------------- | 4696| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4697| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. | 4698| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. | 4699 4700**示例:** 4701 4702```ts 4703import { router } from '@kit.ArkUI'; 4704import { BusinessError } from '@kit.BasicServicesKit' 4705 4706class RouterTmp { 4707 Standard: router.RouterMode = router.RouterMode.Standard 4708} 4709 4710let rtm: RouterTmp = new RouterTmp() 4711 4712@Entry 4713@Component 4714struct Index { 4715 async routePage() { 4716 this.getUIContext().getRouter().replaceUrl({ 4717 url: 'pages/detail', 4718 params: { 4719 data1: 'message' 4720 } 4721 }, rtm.Standard) 4722 .then(() => { 4723 console.info('succeeded') 4724 }) 4725 .catch((error: BusinessError) => { 4726 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4727 }) 4728 } 4729 4730 build() { 4731 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4732 Button() { 4733 Text('next page') 4734 .fontSize(25) 4735 .fontWeight(FontWeight.Bold) 4736 }.type(ButtonType.Capsule) 4737 .margin({ top: 20 }) 4738 .backgroundColor('#ccc') 4739 .onClick(() => { 4740 this.routePage() 4741 }) 4742 } 4743 .width('100%') 4744 .height('100%') 4745 } 4746} 4747``` 4748 4749### replaceUrl 4750 4751replaceUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 4752 4753用应用内的某个页面替换当前页面,并销毁被替换的页面。 4754 4755**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4756 4757**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4758 4759**参数:** 4760 4761| 参数名 | 类型 | 必填 | 说明 | 4762| -------- | ---------------------------------------- | ---- | ---------- | 4763| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 | 4764| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 4765| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 4766 4767**错误码:** 4768 4769以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4770 4771| 错误码ID | 错误信息 | 4772| ------ | ---------------------------------------- | 4773| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4774| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 4775| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. | 4776 4777**示例:** 4778 4779```ts 4780import { router } from '@kit.ArkUI'; 4781import { BusinessError } from '@kit.BasicServicesKit'; 4782 4783class RouterTmp { 4784 Standard: router.RouterMode = router.RouterMode.Standard 4785} 4786 4787let rtm: RouterTmp = new RouterTmp() 4788 4789@Entry 4790@Component 4791struct Index { 4792 async routePage() { 4793 this.getUIContext().getRouter().replaceUrl({ 4794 url: 'pages/detail', 4795 params: { 4796 data1: 'message' 4797 } 4798 }, rtm.Standard, (err: Error) => { 4799 if (err) { 4800 let message = (err as BusinessError).message; 4801 let code = (err as BusinessError).code; 4802 console.error(`replaceUrl failed, code is ${code}, message is ${message}`); 4803 return; 4804 } 4805 console.info('replaceUrl success'); 4806 }); 4807 } 4808 4809 build() { 4810 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4811 Button() { 4812 Text('next page') 4813 .fontSize(25) 4814 .fontWeight(FontWeight.Bold) 4815 }.type(ButtonType.Capsule) 4816 .margin({ top: 20 }) 4817 .backgroundColor('#ccc') 4818 .onClick(() => { 4819 this.routePage() 4820 }) 4821 } 4822 .width('100%') 4823 .height('100%') 4824 } 4825} 4826``` 4827 4828### pushNamedRoute 4829 4830pushNamedRoute(options: router.NamedRouterOptions): Promise<void> 4831 4832跳转到指定的命名路由页面,通过Promise获取跳转异常的返回结果。 4833 4834**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4835 4836**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4837 4838**参数:** 4839 4840| 参数名 | 类型 | 必填 | 说明 | 4841| ------- | ---------------------------------------- | ---- | --------- | 4842| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 | 4843 4844**返回值:** 4845 4846| 类型 | 说明 | 4847| ------------------- | ------- | 4848| Promise<void> | 异常返回结果。 | 4849 4850**错误码:** 4851 4852以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4853 4854| 错误码ID | 错误信息 | 4855| ------ | ---------------------------------- | 4856| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4857| 100001 | Internal error. | 4858| 100003 | Page stack error. Too many pages are pushed. | 4859| 100004 | Named route error. The named route does not exist. | 4860 4861**示例:** 4862 4863```ts 4864import { BusinessError } from '@kit.BasicServicesKit' 4865 4866@Entry 4867@Component 4868struct Index { 4869 async routePage() { 4870 this.getUIContext().getRouter().pushNamedRoute({ 4871 name: 'myPage', 4872 params: { 4873 data1: 'message', 4874 data2: { 4875 data3: [123, 456, 789] 4876 } 4877 } 4878 }) 4879 .then(() => { 4880 console.info('succeeded') 4881 }) 4882 .catch((error: BusinessError) => { 4883 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 4884 }) 4885 } 4886 4887 build() { 4888 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4889 Button() { 4890 Text('next page') 4891 .fontSize(25) 4892 .fontWeight(FontWeight.Bold) 4893 }.type(ButtonType.Capsule) 4894 .margin({ top: 20 }) 4895 .backgroundColor('#ccc') 4896 .onClick(() => { 4897 this.routePage() 4898 }) 4899 } 4900 .width('100%') 4901 .height('100%') 4902 } 4903} 4904``` 4905 4906### pushNamedRoute 4907 4908pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void 4909 4910跳转到指定的命名路由页面。 4911 4912**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4913 4914**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4915 4916**参数:** 4917 4918| 参数名 | 类型 | 必填 | 说明 | 4919| -------- | ---------------------------------------- | ---- | --------- | 4920| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 | 4921| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 4922 4923**错误码:** 4924 4925以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 4926 4927| 错误码ID | 错误信息 | 4928| ------ | ---------------------------------- | 4929| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 4930| 100001 | Internal error. | 4931| 100003 | Page stack error. Too many pages are pushed. | 4932| 100004 | Named route error. The named route does not exist. | 4933 4934**示例:** 4935 4936```ts 4937import { BusinessError } from '@kit.BasicServicesKit'; 4938 4939@Entry 4940@Component 4941struct Index { 4942 async routePage() { 4943 this.getUIContext().getRouter().pushNamedRoute({ 4944 name: 'myPage', 4945 params: { 4946 data1: 'message', 4947 data2: { 4948 data3: [123, 456, 789] 4949 } 4950 } 4951 }, (err: Error) => { 4952 if (err) { 4953 let message = (err as BusinessError).message; 4954 let code = (err as BusinessError).code; 4955 console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); 4956 return; 4957 } 4958 console.info('pushNamedRoute success'); 4959 }) 4960 } 4961 4962 build() { 4963 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 4964 Button() { 4965 Text('next page') 4966 .fontSize(25) 4967 .fontWeight(FontWeight.Bold) 4968 }.type(ButtonType.Capsule) 4969 .margin({ top: 20 }) 4970 .backgroundColor('#ccc') 4971 .onClick(() => { 4972 this.routePage() 4973 }) 4974 } 4975 .width('100%') 4976 .height('100%') 4977 } 4978} 4979``` 4980### pushNamedRoute 4981 4982pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void> 4983 4984跳转到指定的命名路由页面,通过Promise获取跳转异常的返回结果。 4985 4986**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 4987 4988**系统能力:** SystemCapability.ArkUI.ArkUI.Full 4989 4990**参数:** 4991 4992| 参数名 | 类型 | 必填 | 说明 | 4993| ------- | ---------------------------------------- | ---- | ---------- | 4994| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 | 4995| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 4996 4997**返回值:** 4998 4999| 类型 | 说明 | 5000| ------------------- | ------- | 5001| Promise<void> | 异常返回结果。 | 5002 5003**错误码:** 5004 5005以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 5006 5007| 错误码ID | 错误信息 | 5008| ------ | ---------------------------------- | 5009| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5010| 100001 | Internal error. | 5011| 100003 | Page stack error. Too many pages are pushed. | 5012| 100004 | Named route error. The named route does not exist. | 5013 5014**示例:** 5015 5016```ts 5017import { router } from '@kit.ArkUI'; 5018import { BusinessError } from '@kit.BasicServicesKit'; 5019 5020class RouterTmp{ 5021 Standard:router.RouterMode = router.RouterMode.Standard 5022} 5023let rtm:RouterTmp = new RouterTmp() 5024 5025@Entry 5026@Component 5027struct Index { 5028 async routePage() { 5029 this.getUIContext().getRouter().pushNamedRoute({ 5030 name: 'myPage', 5031 params: { 5032 data1: 'message', 5033 data2: { 5034 data3: [123, 456, 789] 5035 } 5036 } 5037 }, rtm.Standard) 5038 .then(() => { 5039 console.info('succeeded') 5040 }) 5041 .catch((error: BusinessError) => { 5042 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 5043 }) 5044 } 5045 5046 build() { 5047 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5048 Button() { 5049 Text('next page') 5050 .fontSize(25) 5051 .fontWeight(FontWeight.Bold) 5052 }.type(ButtonType.Capsule) 5053 .margin({ top: 20 }) 5054 .backgroundColor('#ccc') 5055 .onClick(() => { 5056 this.routePage() 5057 }) 5058 } 5059 .width('100%') 5060 .height('100%') 5061 } 5062} 5063``` 5064 5065### pushNamedRoute 5066 5067pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 5068 5069跳转到指定的命名路由页面。 5070 5071**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5072 5073**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5074 5075**参数:** 5076 5077| 参数名 | 类型 | 必填 | 说明 | 5078| -------- | ---------------------------------------- | ---- | ---------- | 5079| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 | 5080| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 5081| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 5082 5083**错误码:** 5084 5085以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 5086 5087| 错误码ID | 错误信息 | 5088| ------ | ---------------------------------- | 5089| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5090| 100001 | Internal error. | 5091| 100003 | Page stack error. Too many pages are pushed. | 5092| 100004 | Named route error. The named route does not exist. | 5093 5094**示例:** 5095 5096```ts 5097import { router } from '@kit.ArkUI'; 5098import { BusinessError } from '@kit.BasicServicesKit'; 5099 5100class RouterTmp { 5101 Standard: router.RouterMode = router.RouterMode.Standard 5102} 5103 5104let rtm: RouterTmp = new RouterTmp() 5105 5106@Entry 5107@Component 5108struct Index { 5109 async routePage() { 5110 this.getUIContext().getRouter().pushNamedRoute({ 5111 name: 'myPage', 5112 params: { 5113 data1: 'message', 5114 data2: { 5115 data3: [123, 456, 789] 5116 } 5117 } 5118 }, rtm.Standard, (err: Error) => { 5119 if (err) { 5120 let message = (err as BusinessError).message; 5121 let code = (err as BusinessError).code; 5122 console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); 5123 return; 5124 } 5125 console.info('pushNamedRoute success'); 5126 }) 5127 } 5128 5129 build() { 5130 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5131 Button() { 5132 Text('next page') 5133 .fontSize(25) 5134 .fontWeight(FontWeight.Bold) 5135 }.type(ButtonType.Capsule) 5136 .margin({ top: 20 }) 5137 .backgroundColor('#ccc') 5138 .onClick(() => { 5139 this.routePage() 5140 }) 5141 } 5142 .width('100%') 5143 .height('100%') 5144 } 5145} 5146``` 5147 5148### replaceNamedRoute 5149 5150replaceNamedRoute(options: router.NamedRouterOptions): Promise<void> 5151 5152用指定的命名路由页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。 5153 5154**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5155 5156**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5157 5158**参数:** 5159 5160| 参数名 | 类型 | 必填 | 说明 | 5161| ------- | ---------------------------------------- | ---- | --------- | 5162| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 | 5163 5164**返回值:** 5165 5166| 类型 | 说明 | 5167| ------------------- | ------- | 5168| Promise<void> | 异常返回结果。 | 5169 5170**错误码:** 5171 5172以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 5173 5174| 错误码ID | 错误信息 | 5175| ------ | ---------------------------------------- | 5176| 401 | if the number of parameters is less than 1 or the type of the url parameter is not string. | 5177| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 5178| 100004 | Named route error. The named route does not exist. | 5179 5180**示例:** 5181 5182```ts 5183import { BusinessError } from '@kit.BasicServicesKit'; 5184 5185@Entry 5186@Component 5187struct Index { 5188 async routePage() { 5189 this.getUIContext().getRouter().replaceNamedRoute({ 5190 name: 'myPage', 5191 params: { 5192 data1: 'message' 5193 } 5194 }) 5195 .then(() => { 5196 console.info('succeeded') 5197 }) 5198 .catch((error: BusinessError) => { 5199 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 5200 }) 5201 } 5202 5203 build() { 5204 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5205 Button() { 5206 Text('next page') 5207 .fontSize(25) 5208 .fontWeight(FontWeight.Bold) 5209 }.type(ButtonType.Capsule) 5210 .margin({ top: 20 }) 5211 .backgroundColor('#ccc') 5212 .onClick(() => { 5213 this.routePage() 5214 }) 5215 } 5216 .width('100%') 5217 .height('100%') 5218 } 5219} 5220``` 5221 5222### replaceNamedRoute 5223 5224replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void 5225 5226用指定的命名路由页面替换当前页面,并销毁被替换的页面。 5227 5228**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5229 5230**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5231 5232**参数:** 5233 5234| 参数名 | 类型 | 必填 | 说明 | 5235| -------- | ---------------------------------------- | ---- | --------- | 5236| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 | 5237| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 5238 5239**错误码:** 5240 5241以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 5242 5243| 错误码ID | 错误信息 | 5244| ------ | ---------------------------------------- | 5245| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5246| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 5247| 100004 | Named route error. The named route does not exist. | 5248 5249**示例:** 5250 5251```ts 5252import { BusinessError } from '@kit.BasicServicesKit'; 5253 5254@Entry 5255@Component 5256struct Index { 5257 async routePage() { 5258 this.getUIContext().getRouter().replaceNamedRoute({ 5259 name: 'myPage', 5260 params: { 5261 data1: 'message' 5262 } 5263 }, (err: Error) => { 5264 if (err) { 5265 let message = (err as BusinessError).message; 5266 let code = (err as BusinessError).code; 5267 console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`); 5268 return; 5269 } 5270 console.info('replaceNamedRoute success'); 5271 }) 5272 } 5273 5274 build() { 5275 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5276 Button() { 5277 Text('next page') 5278 .fontSize(25) 5279 .fontWeight(FontWeight.Bold) 5280 }.type(ButtonType.Capsule) 5281 .margin({ top: 20 }) 5282 .backgroundColor('#ccc') 5283 .onClick(() => { 5284 this.routePage() 5285 }) 5286 } 5287 .width('100%') 5288 .height('100%') 5289 } 5290} 5291``` 5292 5293### replaceNamedRoute 5294 5295replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void> 5296 5297用指定的命名路由页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。 5298 5299**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5300 5301**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5302 5303**参数:** 5304 5305| 参数名 | 类型 | 必填 | 说明 | 5306| ------- | ---------------------------------------- | ---- | ---------- | 5307| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 | 5308| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 5309 5310 5311**返回值:** 5312 5313| 类型 | 说明 | 5314| ------------------- | ------- | 5315| Promise<void> | 异常返回结果。 | 5316 5317**错误码:** 5318 5319以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 5320 5321| 错误码ID | 错误信息 | 5322| ------ | ---------------------------------------- | 5323| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5324| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. | 5325| 100004 | Named route error. The named route does not exist. | 5326 5327**示例:** 5328 5329```ts 5330import { router } from '@kit.ArkUI'; 5331import { BusinessError } from '@kit.BasicServicesKit'; 5332 5333class RouterTmp { 5334 Standard: router.RouterMode = router.RouterMode.Standard 5335} 5336 5337let rtm: RouterTmp = new RouterTmp() 5338 5339@Entry 5340@Component 5341struct Index { 5342 async routePage() { 5343 this.getUIContext().getRouter().replaceNamedRoute({ 5344 name: 'myPage', 5345 params: { 5346 data1: 'message' 5347 } 5348 }, rtm.Standard) 5349 .then(() => { 5350 console.info('succeeded') 5351 }) 5352 .catch((error: BusinessError) => { 5353 console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`); 5354 }) 5355 } 5356 5357 build() { 5358 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5359 Button() { 5360 Text('next page') 5361 .fontSize(25) 5362 .fontWeight(FontWeight.Bold) 5363 }.type(ButtonType.Capsule) 5364 .margin({ top: 20 }) 5365 .backgroundColor('#ccc') 5366 .onClick(() => { 5367 this.routePage() 5368 }) 5369 } 5370 .width('100%') 5371 .height('100%') 5372 } 5373} 5374``` 5375 5376### replaceNamedRoute 5377 5378replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 5379 5380用指定的命名路由页面替换当前页面,并销毁被替换的页面。 5381 5382**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5383 5384**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5385 5386**参数:** 5387 5388| 参数名 | 类型 | 必填 | 说明 | 5389| -------- | ---------------------------------------- | ---- | ---------- | 5390| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 | 5391| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 5392| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 5393 5394**错误码:** 5395 5396以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 5397 5398| 错误码ID | 错误信息 | 5399| ------ | ---------------------------------------- | 5400| 401 | if the number of parameters is less than 1 or the type of the url parameter is not string. | 5401| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. | 5402| 100004 | Named route error. The named route does not exist. | 5403 5404**示例:** 5405 5406```ts 5407import { router } from '@kit.ArkUI'; 5408import { BusinessError } from '@kit.BasicServicesKit'; 5409 5410class RouterTmp { 5411 Standard: router.RouterMode = router.RouterMode.Standard 5412} 5413 5414let rtm: RouterTmp = new RouterTmp() 5415 5416@Entry 5417@Component 5418struct Index { 5419 async routePage() { 5420 this.getUIContext().getRouter().replaceNamedRoute({ 5421 name: 'myPage', 5422 params: { 5423 data1: 'message' 5424 } 5425 }, rtm.Standard, (err: Error) => { 5426 if (err) { 5427 let message = (err as BusinessError).message; 5428 let code = (err as BusinessError).code; 5429 console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`); 5430 return; 5431 } 5432 console.info('replaceNamedRoute success'); 5433 }) 5434 } 5435 5436 build() { 5437 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 5438 Button() { 5439 Text('next page') 5440 .fontSize(25) 5441 .fontWeight(FontWeight.Bold) 5442 }.type(ButtonType.Capsule) 5443 .margin({ top: 20 }) 5444 .backgroundColor('#ccc') 5445 .onClick(() => { 5446 this.routePage() 5447 }) 5448 } 5449 .width('100%') 5450 .height('100%') 5451 } 5452} 5453``` 5454 5455### back 5456 5457back(options?: router.RouterOptions ): void 5458 5459返回上一页面或指定的页面。 5460 5461**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5462 5463**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5464 5465**参数:** 5466 5467| 参数名 | 类型 | 必填 | 说明 | 5468| ------- | ---------------------------------------- | ---- | ---------------------------------------- | 5469| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 否 | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面不会重新构建,页面栈里面的page不会回收,出栈后会被回收。 | 5470 5471**示例:** 5472 5473```ts 5474import { Router } from '@kit.ArkUI'; 5475let router: Router = uiContext.getRouter(); 5476router.back({url:'pages/detail'}); 5477``` 5478 5479### back<sup>12+</sup> 5480 5481back(index: number, params?: Object): void; 5482 5483返回指定的页面。 5484 5485**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 5486 5487**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5488 5489**参数:** 5490 5491| 参数名 | 类型 | 必填 | 说明 | 5492| ------- | ------------------------------- | ---- | ---------- | 5493| index | number | 是 | 跳转目标页面的索引值。 <br/> 取值范围:[0, +∞) | 5494| params | Object | 否 | 页面返回时携带的参数。 | 5495 5496**示例:** 5497 5498```ts 5499import { Router } from '@kit.ArkUI'; 5500 5501let router: Router = uiContext.getRouter(); 5502router.back(1); 5503``` 5504 5505```ts 5506import { Router } from '@kit.ArkUI'; 5507 5508let router: Router = uiContext.getRouter(); 5509router.back(1, {info:'来自Home页'}); //携带参数返回 5510``` 5511 5512### clear 5513 5514clear(): void 5515 5516清空页面栈中的所有历史页面,仅保留当前页面作为栈顶页面。 5517 5518**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5519 5520**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5521 5522**示例:** 5523 5524```ts 5525import { Router } from '@kit.ArkUI'; 5526 5527let router: Router = uiContext.getRouter(); 5528router.clear(); 5529``` 5530 5531### getLength 5532 5533getLength(): string 5534 5535获取当前在页面栈内的页面数量。 5536 5537**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5538 5539**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5540 5541**返回值:** 5542 5543| 类型 | 说明 | 5544| ------ | ------------------ | 5545| string | 页面数量,页面栈支持最大数值是32。 | 5546 5547**示例:** 5548 5549```ts 5550import { Router } from '@kit.ArkUI'; 5551 5552let router: Router = uiContext.getRouter(); 5553let size = router.getLength(); 5554console.info('pages stack size = ' + size); 5555``` 5556 5557### getState 5558 5559getState(): router.RouterState 5560 5561获取当前页面的状态信息。 5562 5563**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5564 5565**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5566 5567**返回值:** 5568 5569| 类型 | 说明 | 5570| ---------------------------------------- | ------- | 5571| router.[RouterState](js-apis-router.md#routerstate) | 页面状态信息。 | 5572 5573**示例:** 5574 5575<!--code_no_check--> 5576```ts 5577import { Router } from '@kit.ArkUI'; 5578 5579let router: Router = uiContext.getRouter(); 5580let page = router.getState(); 5581console.info('current index = ' + page.index); 5582console.info('current name = ' + page.name); 5583console.info('current path = ' + page.path); 5584``` 5585 5586### getStateByIndex<sup>12+</sup> 5587 5588getStateByIndex(index: number): router.RouterState | undefined 5589 5590通过索引值获取对应页面的状态信息。 5591 5592**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 5593 5594**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5595 5596**参数:** 5597 5598| 参数名 | 类型 | 必填 | 说明 | 5599| ------- | ------------------------------- | ---- | ---------- | 5600| index | number | 是 | 表示要获取的页面索引。 <br/> 取值范围:[0, +∞) | 5601 5602**返回值:** 5603 5604| 类型 | 说明 | 5605| --------------------------- | ------- | 5606| router.[RouterState](js-apis-router.md#outerstate) \| undefined | 返回页面状态信息。索引不存在时返回undefined。 | 5607 5608**示例:** 5609 5610<!--code_no_check--> 5611```ts 5612import { Router } from '@kit.ArkUI'; 5613 5614let router: Router = uiContext.getRouter(); 5615let options: router.RouterState | undefined = router.getStateByIndex(1); 5616if (options != undefined) { 5617 console.info('index = ' + options.index); 5618 console.info('name = ' + options.name); 5619 console.info('path = ' + options.path); 5620 console.info('params = ' + options.params); 5621} 5622``` 5623### getStateByUrl<sup>12+</sup> 5624 5625getStateByUrl(url: string): Array<router.[RouterState](js-apis-router.md#outerstate)> 5626 5627通过url获取当前页面的状态信息。 5628 5629**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 5630 5631**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5632 5633**参数:** 5634 5635| 参数名 | 类型 | 必填 | 说明 | 5636| ------- | ------------------------------- | ---- | ---------- | 5637| url | string | 是 | 表示要获取对应页面信息的url。 | 5638 5639**返回值:** 5640 5641| 类型 | 说明 | 5642| --------------------------- | ------- | 5643| Array<router.[RouterState](js-apis-router.md#outerstate)> | 页面状态信息。 | 5644 5645**示例:** 5646 5647<!--code_no_check--> 5648```ts 5649import { Router } from '@kit.ArkUI'; 5650let router: Router = uiContext.getRouter(); 5651let options:Array<router.RouterState> = router.getStateByUrl('pages/index'); 5652for (let i: number = 0; i < options.length; i++) { 5653 console.info('index = ' + options[i].index); 5654 console.info('name = ' + options[i].name); 5655 console.info('path = ' + options[i].path); 5656 console.info('params = ' + options[i].params); 5657} 5658``` 5659 5660### showAlertBeforeBackPage 5661 5662showAlertBeforeBackPage(options: router.EnableAlertOptions): void 5663 5664开启页面返回询问对话框。 5665 5666**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5667 5668**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5669 5670**参数:** 5671 5672| 参数名 | 类型 | 必填 | 说明 | 5673| ------- | ---------------------------------------- | ---- | --------- | 5674| options | [router.EnableAlertOptions](js-apis-router.md#enablealertoptions) | 是 | 文本弹窗信息描述。 | 5675 5676**错误码:** 5677 5678以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。 5679 5680| 错误码ID | 错误信息 | 5681| ------ | ---------------------------------- | 5682| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5683| 100001 | Internal error. | 5684 5685**示例:** 5686 5687<!--code_no_check--> 5688```ts 5689import { Router } from '@kit.ArkUI'; 5690import { BusinessError } from '@kit.BasicServicesKit'; 5691 5692let router: Router = uiContext.getRouter(); 5693try { 5694 router.showAlertBeforeBackPage({ 5695 message: 'Message Info' 5696 }); 5697} catch(error) { 5698 let message = (error as BusinessError).message; 5699 let code = (error as BusinessError).code; 5700 console.error(`showAlertBeforeBackPage failed, code is ${code}, message is ${message}`); 5701} 5702``` 5703 5704### hideAlertBeforeBackPage 5705 5706hideAlertBeforeBackPage(): void 5707 5708禁用页面返回询问对话框。 5709 5710**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5711 5712**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5713 5714**示例:** 5715 5716<!--code_no_check--> 5717```ts 5718import { Router } from '@kit.ArkUI'; 5719 5720let router: Router = uiContext.getRouter(); 5721router.hideAlertBeforeBackPage(); 5722``` 5723 5724### getParams 5725 5726getParams(): Object 5727 5728获取发起跳转的页面往当前页传入的参数。 5729 5730**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5731 5732**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5733 5734**返回值:** 5735 5736| 类型 | 说明 | 5737| ------ | ----------------- | 5738| Object | 发起跳转的页面往当前页传入的参数。 | 5739 5740**示例:** 5741 5742<!--code_no_check--> 5743 5744```ts 5745import { Router } from '@kit.ArkUI'; 5746 5747let router: Router = uiContext.getRouter(); 5748router.getParams(); 5749``` 5750 5751## CustomBuilderWithId<sup>18+</sup> 5752 5753type CustomBuilderWithId = (id: number) => void 5754 5755组件属性方法参数可使用CustomBuilderWithId类型来自定义UI描述,并且可以指定组件ID生成用户自定义组件。 5756 5757**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 5758 5759**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5760 5761**参数:** 5762 5763| 参数名 | 类型 | 必填 | 说明 | 5764| -------- | -------- | -------- | -------- | 5765| id | number | 是 | 组件ID | 5766 5767## TargetInfo<sup>18+</sup> 5768 5769指定组件绑定的目标节点。 5770 5771**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 5772 5773**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5774 5775**参数:** 5776 5777| 名称 | 类型 | 只读 | 可选 | 说明 | 5778| -------- | -------- | -------- | -------- | -------- | 5779| id | string \| number | 否 | 否 | 指定popup或menu绑定的目标节点。<br/>**说明:** <br/>1. 当id是number时,对应组件实例的UniquelD,此id由系统保证唯一性。<br/>2. 当id是string时,对应[通用属性id](arkui-ts/ts-universal-attributes-component-id.md#id)所指定的组件,此id的唯一性需由开发者确保,但实际可能会有多个。 | 5780| componentId | number | 否 | 是 | 目标节点所在的自定义组件的UniquelD。当上述id指定为string类型时,可通过此属性圈定范围。方便开发者在一定范围内保证id: string的唯一性。 | 5781 5782## PromptAction 5783 5784以下API需先使用UIContext中的[getPromptAction()](#getpromptaction)方法获取到PromptAction对象,再通过该对象调用对应方法。 5785 5786### showToast 5787 5788showToast(options: promptAction.ShowToastOptions): void 5789 5790创建并显示文本提示框。 5791 5792**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5793 5794**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5795 5796**参数:** 5797 5798| 参数名 | 类型 | 必填 | 说明 | 5799| ------- | ---------------------------------------- | ---- | ------- | 5800| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | 是 | 文本弹窗选项。 | 5801 5802**错误码:** 5803 5804以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 5805 5806| 错误码ID | 错误信息 | 5807| ------ | ---------------------------------- | 5808| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5809| 100001 | Internal error. | 5810 5811**示例:** 5812 5813<!--code_no_check--> 5814```ts 5815import { PromptAction } from '@kit.ArkUI'; 5816import { BusinessError } from '@kit.BasicServicesKit'; 5817 5818let promptAction: PromptAction = uiContext.getPromptAction(); 5819try { 5820 promptAction.showToast({ 5821 message: 'Message Info', 5822 duration: 2000 5823 }); 5824} catch (error) { 5825 let message = (error as BusinessError).message; 5826 let code = (error as BusinessError).code; 5827 console.error(`showToast args error code is ${code}, message is ${message}`); 5828}; 5829``` 5830 5831### openToast<sup>18+</sup> 5832 5833openToast(options: promptAction.ShowToastOptions): Promise<number> 5834 5835**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 5836 5837**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5838 5839**参数:** 5840 5841| 参数名 | 类型 | 必填 | 说明 | 5842| ------- | ------------------------------------------------------------ | ---- | -------------- | 5843| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | 是 | 文本弹窗选项。 | 5844 5845**返回值** 5846 5847| 类型 | 说明 | 5848| ---------------- | ------------------------------------ | 5849| Promise<number> | 返回供closeToast使用的文本提示框id。 | 5850 5851**错误码:** 5852 5853以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 5854 5855| 错误码ID | 错误信息 | 5856| -------- | ------------------------------------------------------------ | 5857| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5858| 100001 | Internal error. | 5859 5860**示例:** 5861 5862```ts 5863import { PromptAction } from '@kit.ArkUI'; 5864import { BusinessError } from '@kit.BasicServicesKit'; 5865 5866@Entry 5867@Component 5868struct toastExample { 5869 @State toastId: number = 0; 5870 promptAction: PromptAction = this.getUIContext().getPromptAction() 5871 5872 build() { 5873 Column() { 5874 Button('Open Toast') 5875 .height(100) 5876 .onClick(() => { 5877 this.promptAction.openToast({ 5878 message: 'Toast Massage', 5879 duration: 10000, 5880 }).then((toastId: number) => { 5881 this.toastId = toastId; 5882 }) 5883 .catch((error: BusinessError) => { 5884 console.error(`openToast error code is ${error.code}, message is ${error.message}`) 5885 }) 5886 }) 5887 Blank().height(50); 5888 Button('Close Toast') 5889 .height(100) 5890 .onClick(() => { 5891 try { 5892 this.promptAction.closeToast(this.toastId); 5893 } catch (error) { 5894 let message = (error as BusinessError).message; 5895 let code = (error as BusinessError).code; 5896 console.error(`CloseToast error code is ${code}, message is ${message}`); 5897 }; 5898 }) 5899 }.height('100%').width('100%').justifyContent(FlexAlign.Center) 5900 } 5901} 5902``` 5903 5904### closeToast<sup>18+</sup> 5905 5906closeToast(toastId: number): void 5907 5908**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 5909 5910**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5911 5912**参数** 5913 5914| 参数名 | 类型 | 必填 | 说明 | 5915| ------- | ------ | ---- | ----------------------------- | 5916| toastId | number | 是 | openToast返回的文本提示框id。 | 5917 5918**错误码:** 5919 5920以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 5921 5922| 错误码ID | 错误信息 | 5923| -------- | ------------------------------------------------------------ | 5924| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5925| 100001 | Internal error. | 5926 5927**示例:** 5928 5929示例请看[openToaset18](#opentoast18)的示例。 5930 5931### showDialog 5932 5933showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse>): void 5934 5935创建并显示对话框,对话框响应结果异步返回。 5936 5937**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 5938 5939**系统能力:** SystemCapability.ArkUI.ArkUI.Full 5940 5941**参数:** 5942 5943| 参数名 | 类型 | 必填 | 说明 | 5944| -------- | ---------------------------------------- | ---- | ------------ | 5945| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | 是 | 页面显示对话框信息描述。 | 5946| callback | AsyncCallback<[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | 是 | 对话框响应结果回调。 | 5947 5948**错误码:** 5949 5950以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 5951 5952| 错误码ID | 错误信息 | 5953| ------ | ---------------------------------- | 5954| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 5955| 100001 | Internal error. | 5956 5957**示例:** 5958 5959<!--code_no_check--> 5960 5961```ts 5962import { PromptAction } from '@kit.ArkUI'; 5963import { BusinessError } from '@kit.BasicServicesKit'; 5964 5965let promptAction: PromptAction = uiContext.getPromptAction(); 5966try { 5967 promptAction.showDialog({ 5968 title: 'showDialog Title Info', 5969 message: 'Message Info', 5970 buttons: [ 5971 { 5972 text: 'button1', 5973 color: '#000000' 5974 }, 5975 { 5976 text: 'button2', 5977 color: '#000000' 5978 } 5979 ] 5980 }, (err, data) => { 5981 if (err) { 5982 console.error('showDialog err: ' + err); 5983 return; 5984 } 5985 console.info('showDialog success callback, click button: ' + data.index); 5986 }); 5987} catch (error) { 5988 let message = (error as BusinessError).message; 5989 let code = (error as BusinessError).code; 5990 console.error(`showDialog args error code is ${code}, message is ${message}`); 5991}; 5992``` 5993 5994### showDialog 5995 5996showDialog(options: promptAction.ShowDialogOptions): Promise<promptAction.ShowDialogSuccessResponse> 5997 5998创建并显示对话框,对话框响应后同步返回结果,通过Promise获取对话框响应结果。 5999 6000**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 6001 6002**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6003 6004**参数:** 6005 6006| 参数名 | 类型 | 必填 | 说明 | 6007| ------- | ---------------------------------------- | ---- | ------ | 6008| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | 是 | 对话框选项。 | 6009 6010**返回值:** 6011 6012| 类型 | 说明 | 6013| ---------------------------------------- | -------- | 6014| Promise<[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | 对话框响应结果。 | 6015 6016**错误码:** 6017 6018以下错误码的详细介绍请参见[ 通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6019 6020| 错误码ID | 错误信息 | 6021| ------ | ---------------------------------- | 6022| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6023| 100001 | Internal error. | 6024 6025**示例:** 6026 6027<!--code_no_check--> 6028```ts 6029import { PromptAction } from '@kit.ArkUI'; 6030 6031let promptAction: PromptAction = uiContext.getPromptAction(); 6032promptAction.showDialog({ 6033 title: 'Title Info', 6034 message: 'Message Info', 6035 buttons: [ 6036 { 6037 text: 'button1', 6038 color: '#000000' 6039 }, 6040 { 6041 text: 'button2', 6042 color: '#000000' 6043 } 6044 ], 6045}) 6046 .then(data => { 6047 console.info('showDialog success, click button: ' + data.index); 6048 }) 6049 .catch((err: Error) => { 6050 console.error('showDialog error: ' + err); 6051 }) 6052``` 6053 6054### showActionMenu<sup>11+</sup> 6055 6056showActionMenu(options: promptAction.ActionMenuOptions, callback: AsyncCallback<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)>):void 6057 6058创建并显示操作菜单,菜单响应结果异步返回。 6059 6060**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 6061 6062**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6063 6064**参数:** 6065 6066| 参数名 | 类型 | 必填 | 说明 | 6067| -------- | ------------------------------------------------------------ | ---- | ------------------ | 6068| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是 | 操作菜单选项。 | 6069| callback | AsyncCallback<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | 是 | 菜单响应结果回调。 | 6070 6071**错误码:** 6072 6073以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6074 6075| 错误码ID | 错误信息 | 6076| -------- | ---------------------------------- | 6077| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6078| 100001 | Internal error. | 6079 6080**示例:** 6081 6082<!--code_no_check--> 6083```ts 6084import { PromptAction, promptAction } from '@kit.ArkUI'; 6085import { BusinessError } from '@kit.BasicServicesKit'; 6086 6087let promptActionF: PromptAction = uiContext.getPromptAction(); 6088try { 6089 promptActionF.showActionMenu({ 6090 title: 'Title Info', 6091 buttons: [ 6092 { 6093 text: 'item1', 6094 color: '#666666' 6095 }, 6096 { 6097 text: 'item2', 6098 color: '#000000' 6099 } 6100 ] 6101 }, (err:BusinessError, data:promptAction.ActionMenuSuccessResponse) => { 6102 if (err) { 6103 console.error('showDialog err: ' + err); 6104 return; 6105 } 6106 console.info('showDialog success callback, click button: ' + data.index); 6107 }); 6108} catch (error) { 6109 let message = (error as BusinessError).message; 6110 let code = (error as BusinessError).code; 6111 console.error(`showActionMenu args error code is ${code}, message is ${message}`); 6112}; 6113``` 6114 6115### showActionMenu<sup>(deprecated)</sup> 6116 6117showActionMenu(options: promptAction.ActionMenuOptions, callback: [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)):void 6118 6119创建并显示操作菜单,菜单响应结果异步返回。 6120 6121从API version11开始不再维护,建议使用[showActionMenu](#showactionmenu11)。 6122 6123**系统能力:** SystemCapability.ArkUI.ArkUI.Full。 6124 6125**参数:** 6126 6127| 参数名 | 类型 | 必填 | 说明 | 6128| -------- | ------------------------------------------------------------ | ---- | ------------------ | 6129| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是 | 操作菜单选项。 | 6130| callback | [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse) | 是 | 菜单响应结果回调。 | 6131 6132**错误码:** 6133 6134以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6135 6136| 错误码ID | 错误信息 | 6137| ------ | ---------------------------------- | 6138| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6139| 100001 | Internal error. | 6140 6141**示例:** 6142 6143<!--code_no_check--> 6144```ts 6145import { PromptAction,promptAction } from '@kit.ArkUI'; 6146import { BusinessError } from '@kit.BasicServicesKit'; 6147 6148let promptActionF: PromptAction = uiContext.getPromptAction(); 6149try { 6150 promptActionF.showActionMenu({ 6151 title: 'Title Info', 6152 buttons: [ 6153 { 6154 text: 'item1', 6155 color: '#666666' 6156 }, 6157 { 6158 text: 'item2', 6159 color: '#000000' 6160 } 6161 ] 6162 }, { index:0 }); 6163} catch (error) { 6164 let message = (error as BusinessError).message; 6165 let code = (error as BusinessError).code; 6166 console.error(`showActionMenu args error code is ${code}, message is ${message}`); 6167}; 6168``` 6169 6170### showActionMenu 6171 6172showActionMenu(options: promptAction.ActionMenuOptions): Promise<promptAction.ActionMenuSuccessResponse> 6173 6174创建并显示操作菜单,通过Promise获取菜单响应结果。 6175 6176**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 6177 6178**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6179 6180**参数:** 6181 6182| 参数名 | 类型 | 必填 | 说明 | 6183| ------- | ---------------------------------------- | ---- | ------- | 6184| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是 | 操作菜单选项。 | 6185 6186**返回值:** 6187 6188| 类型 | 说明 | 6189| ---------------------------------------- | ------- | 6190| Promise<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | 菜单响应结果。 | 6191 6192**错误码:** 6193 6194以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6195 6196| 错误码ID | 错误信息 | 6197| ------ | ---------------------------------- | 6198| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6199| 100001 | Internal error. | 6200 6201**示例:** 6202 6203<!--code_no_check--> 6204```ts 6205import { PromptAction } from '@kit.ArkUI'; 6206 6207let promptAction: PromptAction = uiContext.getPromptAction(); 6208promptAction.showActionMenu({ 6209 title: 'showActionMenu Title Info', 6210 buttons: [ 6211 { 6212 text: 'item1', 6213 color: '#666666' 6214 }, 6215 { 6216 text: 'item2', 6217 color: '#000000' 6218 }, 6219 ] 6220}) 6221 .then(data => { 6222 console.info('showActionMenu success, click button: ' + data.index); 6223 }) 6224 .catch((err: Error) => { 6225 console.error('showActionMenu error: ' + err); 6226 }) 6227``` 6228 6229### openCustomDialog<sup>12+</sup> 6230 6231openCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>, options?: promptAction.BaseDialogOptions): Promise<void> 6232 6233创建并弹出dialogContent对应的自定义弹窗,使用Promise异步回调。通过该接口弹出的弹窗内容样式完全按照dialogContent中设置的样式显示,即相当于customdialog设置customStyle为true时的显示效果。暂不支持[isModal](js-apis-promptAction.md#basedialogoptions11) = true与[showInSubWindow](js-apis-promptAction.md#basedialogoptions11) = true同时使用。 6234 6235**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6236 6237**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6238 6239**参数:** 6240 6241| 参数名 | 类型 | 必填 | 说明 | 6242| ------- | ---------------------------------------- | ---- | ------- | 6243| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 | 6244| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | 否 | 弹窗样式。 | 6245 6246**返回值:** 6247 6248| 类型 | 说明 | 6249| ---------------------------------------- | ------- | 6250| Promise<void> | 异常返回Promise对象。 | 6251 6252**错误码:** 6253 6254以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6255 6256| 错误码ID | 错误信息 | 6257| ------ | ---------------------------------- | 6258| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6259| 103301 | The ComponentContent is incorrect. | 6260| 103302 | Dialog content already exists.| 6261 6262**示例:** 6263 6264```ts 6265import { BusinessError } from '@kit.BasicServicesKit'; 6266import { ComponentContent } from '@kit.ArkUI'; 6267 6268class Params { 6269 text: string = "" 6270 6271 constructor(text: string) { 6272 this.text = text; 6273 } 6274} 6275 6276@Builder 6277function buildText(params: Params) { 6278 Column() { 6279 Text(params.text) 6280 .fontSize(50) 6281 .fontWeight(FontWeight.Bold) 6282 .margin({ bottom: 36 }) 6283 }.backgroundColor('#FFF0F0F0') 6284} 6285 6286@Entry 6287@Component 6288struct Index { 6289 @State message: string = "hello" 6290 6291 build() { 6292 Row() { 6293 Column() { 6294 Button("click me") 6295 .onClick(() => { 6296 let uiContext = this.getUIContext(); 6297 let promptAction = uiContext.getPromptAction(); 6298 let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); 6299 promptAction.openCustomDialog(contentNode) 6300 .then(() => { 6301 console.info('succeeded') 6302 }) 6303 .catch((error: BusinessError) => { 6304 console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`); 6305 }) 6306 }) 6307 } 6308 .width('100%') 6309 .height('100%') 6310 } 6311 .height('100%') 6312 } 6313} 6314``` 6315 6316### openCustomDialogWithController<sup>18+</sup> 6317 6318openCustomDialogWithController\<T extends Object>(dialogContent: ComponentContent\<T>, controller: promptAction.DialogController, options?: promptAction.BaseDialogOptions): Promise<void> 6319 6320创建并弹出dialogContent对应的自定义弹窗,使用Promise异步回调。支持传入弹窗控制器与自定义弹窗绑定,后续可以通过控制器控制自定义弹窗。 6321 6322通过该接口弹出的弹窗内容样式完全按照dialogContent中设置的样式显示,即相当于customdialog设置customStyle为true时的显示效果。 6323 6324暂不支持[isModal](js-apis-promptAction.md#basedialogoptions11) = true与[showInSubWindow](js-apis-promptAction.md#basedialogoptions11) = true同时使用。 6325 6326**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 6327 6328**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6329 6330**参数:** 6331 6332| 参数名 | 类型 | 必填 | 说明 | 6333| ------- | ---------------------------------------- | ---- | ------- | 6334| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 | 6335| controller | [promptAction.DialogController](js-apis-promptAction.md#dialogcontroller18) | 是 | 自定义弹窗的控制器。 | 6336| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | 否 | 自定义弹窗的样式。 | 6337 6338**返回值:** 6339 6340| 类型 | 说明 | 6341| ---------------------------------------- | ------- | 6342| Promise<void> | 异常返回Promise对象。 | 6343 6344**错误码:** 6345 6346以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6347 6348| 错误码ID | 错误信息 | 6349| ------ | ---------------------------------- | 6350| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6351| 103301 | The ComponentContent is incorrect. | 6352| 103302 | Dialog content already exists.| 6353 6354**示例:** 6355 6356```ts 6357import { BusinessError } from '@kit.BasicServicesKit'; 6358import { ComponentContent, promptAction } from '@kit.ArkUI'; 6359 6360class Params { 6361 text: string = "" 6362 dialogController: promptAction.DialogController = new promptAction.DialogController(); 6363 6364 constructor(text: string, dialogController: promptAction.DialogController) { 6365 this.text = text; 6366 this.dialogController = dialogController; 6367 } 6368} 6369 6370@Builder 6371function buildText(params: Params) { 6372 Column() { 6373 Text(params.text) 6374 .fontSize(50) 6375 .fontWeight(FontWeight.Bold) 6376 .margin({ bottom: 36 }) 6377 Button('点我关闭弹窗:通过外部传递的DialogController') 6378 .onClick(() => { 6379 if (params.dialogController != undefined) { 6380 params.dialogController.close() 6381 } 6382 }) 6383 }.backgroundColor('#FFF0F0F0') 6384} 6385 6386@Entry 6387@ComponentV2 6388struct Index { 6389 @Local message: string = "hello" 6390 private dialogController: promptAction.DialogController = new promptAction.DialogController() 6391 6392 build() { 6393 Row() { 6394 Column() { 6395 Button("click me") 6396 .onClick(() => { 6397 let uiContext = this.getUIContext(); 6398 let promptAction = uiContext.getPromptAction(); 6399 let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), 6400 new Params(this.message, this.dialogController)); 6401 promptAction.openCustomDialogWithController(contentNode, this.dialogController) 6402 .then(() => { 6403 console.info('succeeded') 6404 }) 6405 .catch((error: BusinessError) => { 6406 console.error(`OpenCustomDialogWithController args error code is ${error.code}, message is ${error.message}`); 6407 }) 6408 }) 6409 } 6410 .width('100%') 6411 .height('100%') 6412 } 6413 .height('100%') 6414 } 6415} 6416``` 6417 6418### closeCustomDialog<sup>12+</sup> 6419 6420closeCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>): Promise<void> 6421 6422关闭已弹出的dialogContent对应的自定义弹窗,使用Promise异步回调。 6423 6424**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6425 6426**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6427 6428**参数:** 6429 6430| 参数名 | 类型 | 必填 | 说明 | 6431| ------- | ---------------------------------------- | ---- | ------- | 6432| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 | 6433 6434**返回值:** 6435 6436| 类型 | 说明 | 6437| ---------------------------------------- | ------- | 6438| Promise<void> | 异常返回Promise对象。 | 6439 6440**错误码:** 6441 6442以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6443 6444| 错误码ID | 错误信息 | 6445| ------ | ---------------------------------- | 6446| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6447| 103301 | The ComponentContent is incorrect. | 6448| 103303 | The ComponentContent cannot be found. | 6449 6450**示例:** 6451 6452```ts 6453import { BusinessError } from '@kit.BasicServicesKit'; 6454import { ComponentContent } from '@kit.ArkUI'; 6455 6456class Params { 6457 text: string = "" 6458 6459 constructor(text: string) { 6460 this.text = text; 6461 } 6462} 6463 6464@Builder 6465function buildText(params: Params) { 6466 Column() { 6467 Text(params.text) 6468 .fontSize(50) 6469 .fontWeight(FontWeight.Bold) 6470 .margin({ bottom: 36 }) 6471 }.backgroundColor('#FFF0F0F0') 6472} 6473 6474@Entry 6475@Component 6476struct Index { 6477 @State message: string = "hello" 6478 6479 build() { 6480 Row() { 6481 Column() { 6482 Button("click me") 6483 .onClick(() => { 6484 let uiContext = this.getUIContext(); 6485 let promptAction = uiContext.getPromptAction(); 6486 let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); 6487 promptAction.openCustomDialog(contentNode) 6488 .then(() => { 6489 console.info('succeeded') 6490 }) 6491 .catch((error: BusinessError) => { 6492 console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`); 6493 }) 6494 setTimeout(() => { 6495 promptAction.closeCustomDialog(contentNode) 6496 .then(() => { 6497 console.info('succeeded') 6498 }) 6499 .catch((error: BusinessError) => { 6500 console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`); 6501 }) 6502 }, 2000); //2秒后自动关闭 6503 }) 6504 } 6505 .width('100%') 6506 .height('100%') 6507 } 6508 .height('100%') 6509 } 6510} 6511``` 6512 6513### updateCustomDialog<sup>12+</sup> 6514 6515updateCustomDialog\<T extends Object>(dialogContent: ComponentContent\<T>, options: promptAction.BaseDialogOptions): Promise<void> 6516 6517更新已弹出的dialogContent对应的自定义弹窗的样式,使用Promise异步回调。 6518 6519**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6520 6521**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6522 6523**参数:** 6524 6525| 参数名 | 类型 | 必填 | 说明 | 6526| ------- | ---------------------------------------- | ---- | ------- | 6527| dialogContent | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 | 6528| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | 是 | 弹窗样式,目前仅支持更新alignment、offset、autoCancel、maskColor。 | 6529 6530**返回值:** 6531 6532| 类型 | 说明 | 6533| ---------------------------------------- | ------- | 6534| Promise<void> | 异常返回Promise对象。 | 6535 6536**错误码:** 6537 6538以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6539 6540| 错误码ID | 错误信息 | 6541| ------ | ---------------------------------- | 6542| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6543| 103301 | The ComponentContent is incorrect. | 6544| 103303 | The ComponentContent cannot be found. | 6545 6546**示例:** 6547 6548```ts 6549import { BusinessError } from '@kit.BasicServicesKit'; 6550import { ComponentContent } from '@kit.ArkUI'; 6551 6552class Params { 6553 text: string = "" 6554 6555 constructor(text: string) { 6556 this.text = text; 6557 } 6558} 6559 6560@Builder 6561function buildText(params: Params) { 6562 Column() { 6563 Text(params.text) 6564 .fontSize(50) 6565 .fontWeight(FontWeight.Bold) 6566 .margin({ bottom: 36 }) 6567 }.backgroundColor('#FFF0F0F0') 6568} 6569 6570@Entry 6571@Component 6572struct Index { 6573 @State message: string = "hello" 6574 6575 build() { 6576 Row() { 6577 Column() { 6578 Button("click me") 6579 .onClick(() => { 6580 let uiContext = this.getUIContext(); 6581 let promptAction = uiContext.getPromptAction(); 6582 let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)) 6583 promptAction.openCustomDialog(contentNode) 6584 .then(() => { 6585 console.info('succeeded') 6586 }) 6587 .catch((error: BusinessError) => { 6588 console.error(`updateCustomDialog args error code is ${error.code}, message is ${error.message}`) 6589 }) 6590 6591 setTimeout(() => { 6592 promptAction.updateCustomDialog(contentNode, { alignment: DialogAlignment.CenterEnd }) 6593 .then(() => { 6594 console.info('succeeded') 6595 }) 6596 .catch((error: BusinessError) => { 6597 console.error(`updateCustomDialog args error code is ${error.code}, message is ${error.message}`) 6598 }) 6599 }, 2000); //2秒后自动更新弹窗位置 6600 }) 6601 } 6602 .width('100%') 6603 .height('100%') 6604 } 6605 .height('100%') 6606 } 6607} 6608``` 6609 6610### openCustomDialog<sup>12+</sup> 6611 6612openCustomDialog(options: promptAction.CustomDialogOptions): Promise\<number> 6613 6614创建并弹出自定义弹窗。使用Promise异步回调,返回供closeCustomDialog使用的对话框id。暂不支持isModal = true与showInSubWindow = true同时使用。 6615 6616**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6617 6618**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6619 6620**参数:** 6621 6622| 参数名 | 类型 | 必填 | 说明 | 6623| ------- | ------------------------------------------------------------ | ---- | ------------------ | 6624| options | [promptAction.CustomDialogOptions](js-apis-promptAction.md#customdialogoptions11) | 是 | 自定义弹窗的内容。 | 6625 6626**返回值:** 6627 6628| 类型 | 说明 | 6629| ------------------- | --------------------------------------- | 6630| Promise<void> | 返回供closeCustomDialog使用的对话框id。 | 6631 6632**错误码:** 6633 6634以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6635 6636| 错误码ID | 错误信息 | 6637| -------- | ------------------------------------------------------------ | 6638| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6639| 100001 | Internal error. | 6640 6641### presentCustomDialog<sup>18+</sup> 6642 6643presentCustomDialog(builder: CustomBuilder \| CustomBuilderWithId, controller?: promptAction.DialogController, options?: promptAction.DialogOptions): Promise\<number> 6644 6645创建并弹出自定义弹窗。使用Promise异步回调,返回供closeCustomDialog使用的对话框id。 6646 6647支持在自定义弹窗内容中持有弹窗ID进行对应操作。支持传入弹窗控制器与自定义弹窗绑定,后续可以通过控制器控制自定义弹窗。 6648 6649暂不支持isModal = true与showInSubWindow = true同时使用。 6650 6651**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 6652 6653**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6654 6655**参数:** 6656 6657| 参数名 | 类型 | 必填 | 说明 | 6658| ------- | ------------------------------------------------------------ | ---- | ------------------ | 6659| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [CustomBuilderWithId](#custombuilderwithid18) | 是 | 自定义弹窗的内容。 | 6660| controller | [promptAction.DialogController](js-apis-promptAction.md#dialogcontroller18) | 否 | 自定义弹窗的控制器。 | 6661| options | [promptAction.DialogOptions](js-apis-promptAction.md#dialogoptions18) | 否 | 自定义弹窗的样式。 | 6662 6663**返回值:** 6664 6665| 类型 | 说明 | 6666| ------------------- | --------------------------------------- | 6667| Promise<number> | 返回自定义弹窗ID。 | 6668 6669**错误码:** 6670 6671以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6672 6673| 错误码ID | 错误信息 | 6674| -------- | ------------------------------------------------------------ | 6675| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6676| 100001 | Internal error. | 6677 6678**示例:** 6679 6680```ts 6681import { BusinessError } from '@kit.BasicServicesKit'; 6682import { PromptAction, promptAction } from '@kit.ArkUI'; 6683 6684@Entry 6685@ComponentV2 6686struct Index { 6687 @Local message: string = "hello" 6688 private ctx: UIContext = this.getUIContext() 6689 private promptAction: PromptAction = this.ctx.getPromptAction() 6690 private dialogController: promptAction.DialogController = new promptAction.DialogController() 6691 6692 private customDialogComponentId: number = 0 6693 @Builder customDialogComponent() { 6694 Column() { 6695 Text(this.message).fontSize(30) 6696 Row({ space: 10 }) { 6697 Button("通过DialogId关闭").onClick(() => { 6698 this.promptAction.closeCustomDialog(this.customDialogComponentId) 6699 }) 6700 Button("通过DialogController关闭").onClick(() => { 6701 this.dialogController.close() 6702 }) 6703 } 6704 }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween) 6705 } 6706 6707 @Builder customDialogComponentWithId(dialogId: number) { 6708 Column() { 6709 Text(this.message).fontSize(30) 6710 Row({ space: 10 }) { 6711 Button("通过DialogId关闭").onClick(() => { 6712 this.promptAction.closeCustomDialog(dialogId) 6713 }) 6714 Button("通过DialogController关闭").onClick(() => { 6715 this.dialogController.close() 6716 }) 6717 } 6718 }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween) 6719 } 6720 6721 build() { 6722 Row() { 6723 Column({ space: 10 }) { 6724 Button('presentCustomDialog') 6725 .fontSize(20) 6726 .onClick(() => { 6727 this.promptAction.presentCustomDialog(() => { 6728 this.customDialogComponent() 6729 }, this.dialogController) 6730 .then((dialogId: number) => { 6731 this.customDialogComponentId = dialogId 6732 }) 6733 .catch((err: BusinessError) => { 6734 console.error("presentCustomDialog error: " + err.code + " " + err.message) 6735 }) 6736 }) 6737 Button('presentCustomDialog with id') 6738 .fontSize(20) 6739 .onClick(() => { 6740 this.promptAction.presentCustomDialog((dialogId: number) => { 6741 this.customDialogComponentWithId(dialogId) 6742 }, this.dialogController) 6743 .catch((err: BusinessError) => { 6744 console.error("presentCustomDialog with id error: " + err.code + " " + err.message) 6745 }) 6746 }) 6747 } 6748 .width('100%') 6749 .height('100%') 6750 } 6751 .height('100%') 6752 } 6753} 6754``` 6755 6756### closeCustomDialog<sup>12+</sup> 6757 6758closeCustomDialog(dialogId: number): void 6759 6760关闭自定义弹窗。 6761 6762**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 6763 6764**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6765 6766**参数:** 6767 6768| 参数名 | 类型 | 必填 | 说明 | 6769| -------- | ------ | ---- | -------------------------------- | 6770| dialogId | number | 是 | openCustomDialog返回的对话框id。 | 6771 6772**错误码:** 6773 6774以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 6775 6776| 错误码ID | 错误信息 | 6777| -------- | ------------------------------------------------------------ | 6778| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 6779| 100001 | Internal error. | 6780 6781**示例:** 6782 6783```ts 6784import { PromptAction } from '@kit.ArkUI'; 6785 6786@Entry 6787@Component 6788struct Index { 6789 promptAction: PromptAction = this.getUIContext().getPromptAction() 6790 private customDialogComponentId: number = 0 6791 6792 @Builder 6793 customDialogComponent() { 6794 Column() { 6795 Text('弹窗').fontSize(30) 6796 Row({ space: 50 }) { 6797 Button("确认").onClick(() => { 6798 this.promptAction.closeCustomDialog(this.customDialogComponentId) 6799 }) 6800 Button("取消").onClick(() => { 6801 this.promptAction.closeCustomDialog(this.customDialogComponentId) 6802 }) 6803 } 6804 }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween) 6805 } 6806 6807 build() { 6808 Row() { 6809 Column() { 6810 Button("click me") 6811 .onClick(() => { 6812 this.promptAction.openCustomDialog({ 6813 builder: () => { 6814 this.customDialogComponent() 6815 }, 6816 onWillDismiss: (dismissDialogAction: DismissDialogAction) => { 6817 console.info("reason" + JSON.stringify(dismissDialogAction.reason)) 6818 console.log("dialog onWillDismiss") 6819 if (dismissDialogAction.reason == DismissReason.PRESS_BACK) { 6820 dismissDialogAction.dismiss() 6821 } 6822 if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) { 6823 dismissDialogAction.dismiss() 6824 } 6825 } 6826 }).then((dialogId: number) => { 6827 this.customDialogComponentId = dialogId 6828 }) 6829 }) 6830 } 6831 .width('100%') 6832 .height('100%') 6833 } 6834 .height('100%') 6835 } 6836} 6837``` 6838 6839### getTopOrder<sup>18+</sup> 6840 6841getTopOrder(): LevelOrder 6842 6843返回最顶层显示的弹窗的顺序。 6844 6845获取最顶层显示的弹窗的顺序,可以在下一个弹窗时指定期望的顺序。 6846 6847**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 6848 6849**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6850 6851**返回值:** 6852 6853| 类型 | 说明 | 6854| ------------------- | --------------------------------------- | 6855| [LevelOrder](js-apis-promptAction.md#levelorder18) | 返回弹窗层级信息。 | 6856 6857**示例:** 6858 6859该示例通过调用getTopOrder接口,展示了获取最顶层显示的弹窗的顺序的功能。 6860 6861```ts 6862import { ComponentContent, PromptAction, LevelOrder, promptAction, UIContext } from '@kit.ArkUI'; 6863import { BusinessError } from '@kit.BasicServicesKit'; 6864 6865class Params { 6866 text: string = "" 6867 constructor(text: string) { 6868 this.text = text; 6869 } 6870} 6871 6872@Builder 6873function buildText(params: Params) { 6874 Column({ space: 20 }) { 6875 Text(params.text) 6876 .fontSize(50) 6877 .fontWeight(FontWeight.Bold) 6878 .margin({ bottom: 36 }) 6879 }.backgroundColor('#FFF0F0F0') 6880} 6881 6882@Entry 6883@Component 6884struct Index { 6885 @State message: string = '弹窗' 6886 private ctx: UIContext = this.getUIContext() 6887 private promptAction: PromptAction = this.ctx.getPromptAction() 6888 private contentNode: ComponentContent<Object> = 6889 new ComponentContent(this.ctx, wrapBuilder(buildText), new Params(this.message)) 6890 6891 private baseDialogOptions: promptAction.BaseDialogOptions = { 6892 showInSubWindow: false, 6893 levelOrder: LevelOrder.clamp(30.1), 6894 } 6895 6896 build() { 6897 Row() { 6898 Column({ space: 10 }) { 6899 Button('openCustomDialog弹窗') 6900 .fontSize(20) 6901 .onClick(() => { 6902 this.promptAction.openCustomDialog(this.contentNode, this.baseDialogOptions) 6903 .catch((err: BusinessError) => { 6904 console.error("openCustomDialog error: " + err.code + " " + err.message) 6905 }) 6906 .then(() => { 6907 let topOrder: LevelOrder = this.promptAction.getTopOrder(); 6908 if (topOrder !== undefined) { 6909 console.error('topOrder: ' + topOrder.getOrder()); 6910 } 6911 }) 6912 }) 6913 }.width('100%') 6914 }.height('100%') 6915 } 6916} 6917``` 6918 6919### getBottomOrder<sup>18+</sup> 6920 6921getBottomOrder(): LevelOrder 6922 6923返回最底层显示的弹窗的顺序。 6924 6925获取最底层显示的弹窗的顺序,可以在下一个弹窗时指定期望的顺序。 6926 6927**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 6928 6929**系统能力:** SystemCapability.ArkUI.ArkUI.Full 6930 6931**返回值:** 6932 6933| 类型 | 说明 | 6934| ------------------- | --------------------------------------- | 6935| [LevelOrder](js-apis-promptAction.md#levelorder18) | 返回弹窗层级信息。 | 6936 6937**示例:** 6938 6939该示例通过调用getBottomOrder接口,展示了获取最底层显示的弹窗的顺序的功能。 6940 6941```ts 6942import { ComponentContent, PromptAction, LevelOrder, promptAction, UIContext } from '@kit.ArkUI'; 6943import { BusinessError } from '@kit.BasicServicesKit'; 6944 6945class Params { 6946 text: string = "" 6947 constructor(text: string) { 6948 this.text = text; 6949 } 6950} 6951 6952@Builder 6953function buildText(params: Params) { 6954 Column({ space: 20 }) { 6955 Text(params.text) 6956 .fontSize(50) 6957 .fontWeight(FontWeight.Bold) 6958 .margin({ bottom: 36 }) 6959 }.backgroundColor('#FFF0F0F0') 6960} 6961 6962@Entry 6963@Component 6964struct Index { 6965 @State message: string = '弹窗' 6966 private ctx: UIContext = this.getUIContext() 6967 private promptAction: PromptAction = this.ctx.getPromptAction() 6968 private contentNode: ComponentContent<Object> = 6969 new ComponentContent(this.ctx, wrapBuilder(buildText), new Params(this.message)) 6970 6971 private baseDialogOptions: promptAction.BaseDialogOptions = { 6972 showInSubWindow: false, 6973 levelOrder: LevelOrder.clamp(30.1), 6974 } 6975 6976 build() { 6977 Row() { 6978 Column({ space: 10 }) { 6979 Button('openCustomDialog弹窗') 6980 .fontSize(20) 6981 .onClick(() => { 6982 this.promptAction.openCustomDialog(this.contentNode, this.baseDialogOptions) 6983 .catch((err: BusinessError) => { 6984 console.error("openCustomDialog error: " + err.code + " " + err.message) 6985 }) 6986 .then(() => { 6987 let bottomOrder: LevelOrder = this.promptAction.getBottomOrder(); 6988 if (bottomOrder !== undefined) { 6989 console.error('bottomOrder: ' + bottomOrder.getOrder()); 6990 } 6991 }) 6992 }) 6993 }.width('100%') 6994 }.height('100%') 6995 } 6996} 6997``` 6998 6999### openPopup<sup>18+</sup> 7000 7001openPopup\<T extends Object>(content: ComponentContent\<T>, target: TargetInfo, options?: PopupCommonOptions): Promise<void> 7002 7003创建并弹出以content作为内容的popup弹窗,使用Promise异步回调。 7004 7005> **说明:** 7006> 7007> 1. 使用该接口时,若未传入有效的target,则无法弹出popup弹窗。 7008> 7009> 2. 由于[updatePopup](#updatepopup18)和[closePopup](#closepopup18)依赖content去更新或者关闭指定的popup弹窗,开发者需自行维护传入的content。 7010> 7011> 3. 如果在wrapBuilder中包含其他组件(例如:[Popup](arkui-ts/ohos-arkui-advanced-Popup.md#popup)、[Chip](arkui-ts/ohos-arkui-advanced-Chip.md#chip)组件),则[ComponentContent](./js-apis-arkui-ComponentContent.md#componentcontent-1)应采用带有四个参数的构造函数constructor,其中options参数应传递{ nestingBuilderSupported: true }。 7012 7013**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 7014 7015**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7016 7017**参数:** 7018 7019| 参数名 | 类型 | 必填 | 说明 | 7020| ------- | ---------------------------------------- | ---- | ------- | 7021| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | popup弹窗中显示的组件内容。 | 7022| target | [TargetInfo](#targetinfo18) | 是 | 需要绑定组件的信息。 | 7023| options | [PopupCommonOptions](arkui-ts/ts-universal-attributes-popup.md#popupcommonoptions18类型说明) | 否 | popup弹窗样式。 | 7024 7025**返回值:** 7026 7027| 类型 | 说明 | 7028| ---------------------------------------- | ------- | 7029| Promise<void> | 异常返回Promise对象。 | 7030 7031**错误码:** 7032 7033以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 7034 7035| 错误码ID | 错误信息 | 7036| ------ | ---------------------------------- | 7037| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7038| 103301 | The ComponentContent is incorrect. | 7039| 103302 | The ComponentContent already exists. | 7040| 103304 | The targetId does not exist. | 7041| 103305 | The node of targetId is not in the component tree. | 7042 7043**示例:** 7044 7045```ts 7046import { ComponentContent, FrameNode } from '@kit.ArkUI'; 7047import { BusinessError } from '@kit.BasicServicesKit'; 7048 7049interface PopupParam { 7050 updateFunc?: () => void 7051 closeFunc?: () => void 7052} 7053 7054export function showPopup(context: UIContext, uniqueId: number, contentNode: ComponentContent<PopupParam>, 7055 popupParam: PopupParam) { 7056 const promptAction = context.getPromptAction(); 7057 let frameNode: FrameNode | null = context.getFrameNodeByUniqueId(uniqueId); 7058 let targetId = frameNode?.getFirstChild()?.getUniqueId(); 7059 promptAction.openPopup(contentNode, { id: targetId }, { 7060 radius: 16, 7061 mask: { color: Color.Pink }, 7062 enableArrow: true, 7063 }) 7064 .then(() => { 7065 console.info('openPopup success'); 7066 }) 7067 .catch((err: BusinessError) => { 7068 console.info('openPopup error: ' + err.code + ' ' + err.message); 7069 }) 7070 popupParam.updateFunc = () => { 7071 promptAction.updatePopup(contentNode, { 7072 enableArrow: false 7073 }, true) 7074 .then(() => { 7075 console.info('updatePopup success'); 7076 }) 7077 .catch((err: BusinessError) => { 7078 console.info('updatePopup error: ' + err.code + ' ' + err.message); 7079 }) 7080 } 7081 popupParam.closeFunc = () => { 7082 promptAction.closePopup(contentNode) 7083 .then(() => { 7084 console.info('closePopup success'); 7085 }) 7086 .catch((err: BusinessError) => { 7087 console.info('closePopup error: ' + err.code + ' ' + err.message); 7088 }) 7089 } 7090} 7091 7092@Builder 7093function buildText(param?: PopupParam) { 7094 Column() { 7095 Text('popup') 7096 Button('Update Popup') 7097 .fontSize(20) 7098 .onClick(() => { 7099 param?.updateFunc?.(); 7100 }) 7101 Button('Close Popup') 7102 .fontSize(20) 7103 .onClick(() => { 7104 param?.closeFunc?.(); 7105 }) 7106 } 7107} 7108 7109@Entry 7110@Component 7111struct Index { 7112 build() { 7113 Column() { 7114 Button('Open Popup') 7115 .fontSize(20) 7116 .onClick(() => { 7117 let context = this.getUIContext() 7118 const popupParam: PopupParam = {}; 7119 const contentNode = new ComponentContent(context, wrapBuilder(buildText), popupParam); 7120 showPopup(context, this.getUniqueId(), contentNode, popupParam) 7121 }) 7122 } 7123 } 7124} 7125``` 7126 7127### updatePopup<sup>18+</sup> 7128 7129updatePopup\<T extends Object>(content: ComponentContent\<T>, options: PopupCommonOptions, partialUpdate?: boolean ): Promise<void> 7130 7131更新content对应的popup弹窗的样式,使用Promise异步回调。 7132 7133> **说明:** 7134> 7135> 不支持更新showInSubWindow、focusable、onStateChange、onWillDismiss、transition。 7136> 7137 7138**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 7139 7140**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7141 7142**参数:** 7143 7144| 参数名 | 类型 | 必填 | 说明 | 7145| ------- | ---------------------------------------- | ---- | ------- | 7146| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | popup弹窗中显示的组件内容。 | 7147| options | [PopupCommonOptions](arkui-ts/ts-universal-attributes-popup.md#popupcommonoptions18类型说明) | 是 | popup弹窗样式。<br/>**说明:** <br/>不支持更新showInSubWindow、focusable、onStateChange、onWillDismiss、transition。 | 7148| partialUpdate | boolean | 否 | popup弹窗更新方式, 默认值为false。<br/>**说明:** <br/>1. true为增量更新,保留当前值,更新options中的指定属性。 <br/>2. false为全量更新,除options中的指定属性,其他属性恢复默认值。 | 7149 7150**返回值:** 7151 7152| 类型 | 说明 | 7153| ---------------------------------------- | ------- | 7154| Promise<void> | 异常返回Promise对象。 | 7155 7156**错误码:** 7157 7158以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 7159 7160| 错误码ID | 错误信息 | 7161| ------ | ---------------------------------- | 7162| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7163| 103301 | The ComponentContent is incorrect. | 7164| 103303 | The ComponentContent cannot be found. | 7165 7166**示例:** 7167 7168请参考[openPopup](#openpopup18)示例。 7169 7170### closePopup<sup>18+</sup> 7171 7172closePopup\<T extends Object>(content: ComponentContent\<T>): Promise<void> 7173 7174关闭content对应的popup弹窗,使用Promise异步回调。 7175 7176**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 7177 7178**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7179 7180**参数:** 7181 7182| 参数名 | 类型 | 必填 | 说明 | 7183| ------- | ---------------------------------------- | ---- | ------- | 7184| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | popup弹窗中显示的组件内容。 | 7185 7186**返回值:** 7187 7188| 类型 | 说明 | 7189| ---------------------------------------- | ------- | 7190| Promise<void> | 异常返回Promise对象。 | 7191 7192**错误码:** 7193 7194以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 7195 7196| 错误码ID | 错误信息 | 7197| ------ | ---------------------------------- | 7198| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7199| 103301 | The ComponentContent is incorrect. | 7200| 103303 | The ComponentContent cannot be found. | 7201 7202**示例:** 7203 7204请参考[openPopup](#openpopup18)示例。 7205 7206### openMenu<sup>18+</sup> 7207 7208openMenu\<T extends Object>(content: ComponentContent\<T>, target: TargetInfo, options?: MenuOptions): Promise<void> 7209 7210创建并弹出以content作为内容的menu弹窗。使用Promise异步回调。 7211 7212> **说明:** 7213> 7214> 1. 使用该接口时,若未传入有效的target,则无法弹出menu弹窗。 7215> 7216> 2. 由于[updateMenu](#updatemenu18)和[closeMenu](#closemenu18)依赖content去更新或者关闭指定的menu弹窗,开发者需自行维护传入的content。 7217> 7218> 3. 如果在wrapBuilder中包含其他组件(例如:[Popup](arkui-ts/ohos-arkui-advanced-Popup.md#popup)、[Chip](arkui-ts/ohos-arkui-advanced-Chip.md#chip)组件),则[ComponentContent](./js-apis-arkui-ComponentContent.md#componentcontent-1)应采用带有四个参数的构造函数constructor,其中options参数应传递{ nestingBuilderSupported: true }。 7219 7220**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 7221 7222**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7223 7224**参数:** 7225 7226| 参数名 | 类型 | 必填 | 说明 | 7227| ------- | ---------------------------------------- | ---- | ------- | 7228| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | menu弹窗中显示的组件内容。 | 7229| target | [TargetInfo](#targetinfo18) | 是 | 需要绑定组件的信息。 | 7230| options | [MenuOptions](./arkui-ts/ts-universal-attributes-menu.md#menuoptions10) | 否 | menu弹窗样式。<br/>**说明:**<br/>title属性不生效。<br/>preview参数仅支持设置MenuPreviewMode类型。 | 7231 7232**返回值:** 7233 7234| 类型 | 说明 | 7235| ---------------------------------------- | ------- | 7236| Promise<void> | 异常返回Promise对象。 | 7237 7238**错误码:** 7239 7240以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 7241 7242| 错误码ID | 错误信息 | 7243| ------ | ---------------------------------- | 7244| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7245| 103301 | The ComponentContent is incorrect. | 7246| 103302 | The ComponentContent already exists. | 7247| 103304 | The targetId does not exist. | 7248| 103305 | The node of targetId is not in the component tree. | 7249 7250**示例:** 7251 7252```ts 7253import { ComponentContent, FrameNode } from '@kit.ArkUI'; 7254 7255export function doSomething(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) { 7256 showMenu(context, uniqueId, contentNode); 7257} 7258 7259@Builder 7260function MyMenu() { 7261 Column() { 7262 Menu() { 7263 MenuItem({ startIcon: $r("app.media.startIcon"), content: "菜单选项1" }) 7264 MenuItem({ startIcon: $r("app.media.startIcon"), content: "菜单选项2" }) 7265 } 7266 } 7267 .width('80%') 7268 .padding('20lpx') 7269} 7270 7271export function showMenu(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) { 7272 const promptAction = context.getPromptAction(); 7273 let frameNode: FrameNode | null = context.getFrameNodeByUniqueId(uniqueId); 7274 let frameNodeTarget = frameNode?.getFirstChild(); 7275 frameNodeTarget = frameNodeTarget?.getChild(0); 7276 let targetId = frameNodeTarget?.getUniqueId(); 7277 promptAction.openMenu(contentNode, { id: targetId }, { 7278 enableArrow: true, 7279 }); 7280} 7281 7282@Entry 7283@Component 7284struct Index { 7285 build() { 7286 Column() { 7287 Button('OpenMenu', { type: ButtonType.Normal, stateEffect: true }) 7288 .borderRadius('16lpx') 7289 .width('80%') 7290 .margin(10) 7291 .onClick(() => { 7292 let context = this.getUIContext() 7293 const contentNode = new ComponentContent(context, wrapBuilder(MyMenu)); 7294 doSomething(context, this.getUniqueId(), contentNode) 7295 }) 7296 } 7297 } 7298} 7299``` 7300 7301### updateMenu<sup>18+</sup> 7302 7303updateMenu\<T extends Object>(content: ComponentContent\<T>, options: MenuOptions, partialUpdate?: boolean ): Promise<void> 7304 7305更新content对应的menu弹窗的样式。使用Promise异步回调。 7306 7307> **说明:** 7308> 7309> 不支持更新showInSubWindow、preview、previewAnimationOptions、transition、onAppear、aboutToAppear、onDisappear、aboutToDisappear。 7310> 7311 7312**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 7313 7314**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7315 7316**参数:** 7317 7318| 参数名 | 类型 | 必填 | 说明 | 7319| ------- | ---------------------------------------- | ---- | ------- | 7320| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | menu弹窗中显示的组件内容。 | 7321| options | [MenuOptions](./arkui-ts/ts-universal-attributes-menu.md#menuoptions10) | 是 | menu弹窗样式。<br/>**说明:** <br/>不支持更新showInSubWindow、preview、previewAnimationOptions、transition、onAppear、aboutToAppear、onDisappear、aboutToDisappear。 | 7322| partialUpdate | boolean | 否 | menu弹窗更新方式,默认值为false。<br/>**说明:** <br/>1. true为增量更新,保留当前值,更新options中的指定属性。 <br/>2. false为全量更新,除options中的指定属性,其他属性恢复默认值。 | 7323 7324**返回值:** 7325 7326| 类型 | 说明 | 7327| ---------------------------------------- | ------- | 7328| Promise<void> | 异常返回Promise对象。 | 7329 7330**错误码:** 7331 7332以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 7333 7334| 错误码ID | 错误信息 | 7335| ------ | ---------------------------------- | 7336| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7337| 103301 | The ComponentContent is incorrect. | 7338| 103303 | The ComponentContent cannot be found. | 7339 7340**示例:** 7341 7342```ts 7343import { ComponentContent, FrameNode } from '@kit.ArkUI'; 7344 7345export function doSomething(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) { 7346 showMenu(context, uniqueId, contentNode); 7347} 7348 7349@Builder 7350function MyMenu() { 7351 Column() { 7352 Menu() { 7353 MenuItem({ startIcon: $r("app.media.startIcon"), content: "菜单选项1" }) 7354 MenuItem({ startIcon: $r("app.media.startIcon"), content: "菜单选项2" }) 7355 } 7356 } 7357 .width('80%') 7358 .padding('20lpx') 7359} 7360 7361export function showMenu(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) { 7362 const promptAction = context.getPromptAction(); 7363 let frameNode: FrameNode | null = context.getFrameNodeByUniqueId(uniqueId); 7364 let frameNodeTarget = frameNode?.getFirstChild(); 7365 frameNodeTarget = frameNodeTarget?.getChild(0); 7366 let targetId = frameNodeTarget?.getUniqueId(); 7367 promptAction.openMenu(contentNode, { id: targetId }, { 7368 enableArrow: true, 7369 }); 7370 setTimeout(() => { 7371 promptAction.updateMenu(contentNode, { 7372 enableArrow: false, 7373 }); 7374 }, 2000) 7375} 7376 7377@Entry 7378@Component 7379struct Index { 7380 build() { 7381 Column() { 7382 Button('OpenMenu', { type: ButtonType.Normal, stateEffect: true }) 7383 .borderRadius('16lpx') 7384 .width('80%') 7385 .margin(10) 7386 .onClick(() => { 7387 let context = this.getUIContext() 7388 const contentNode = new ComponentContent(context, wrapBuilder(MyMenu)); 7389 doSomething(context, this.getUniqueId(), contentNode) 7390 }) 7391 } 7392 } 7393} 7394``` 7395 7396### closeMenu<sup>18+</sup> 7397 7398closeMenu\<T extends Object>(content: ComponentContent\<T>): Promise<void> 7399 7400关闭content对应的menu弹窗。使用Promise异步回调。 7401 7402**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 7403 7404**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7405 7406**参数:** 7407 7408| 参数名 | 类型 | 必填 | 说明 | 7409| ------- | ---------------------------------------- | ---- | ------- | 7410| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | menu弹窗中显示的组件内容。 | 7411 7412**返回值:** 7413 7414| 类型 | 说明 | 7415| ---------------------------------------- | ------- | 7416| Promise<void> | 异常返回Promise对象。 | 7417 7418**错误码:** 7419 7420以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 7421 7422| 错误码ID | 错误信息 | 7423| ------ | ---------------------------------- | 7424| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7425| 103301 | The ComponentContent is incorrect. | 7426| 103303 | The ComponentContent cannot be found. | 7427 7428**示例:** 7429 7430```ts 7431import { ComponentContent, FrameNode } from '@kit.ArkUI'; 7432 7433export function doSomething(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) { 7434 showMenu(context, uniqueId, contentNode); 7435} 7436 7437@Builder 7438function MyMenu() { 7439 Column() { 7440 Menu() { 7441 MenuItem({ startIcon: $r("app.media.startIcon"), content: "菜单选项1" }) 7442 MenuItem({ startIcon: $r("app.media.startIcon"), content: "菜单选项2" }) 7443 } 7444 } 7445 .width('80%') 7446 .padding('20lpx') 7447} 7448 7449export function showMenu(context: UIContext, uniqueId: number, contentNode: ComponentContent<Object>) { 7450 const promptAction = context.getPromptAction(); 7451 let frameNode: FrameNode | null = context.getFrameNodeByUniqueId(uniqueId); 7452 let frameNodeTarget = frameNode?.getFirstChild(); 7453 frameNodeTarget = frameNodeTarget?.getChild(0); 7454 let targetId = frameNodeTarget?.getUniqueId(); 7455 promptAction.openMenu(contentNode, { id: targetId }, { 7456 enableArrow: true, 7457 }); 7458 setTimeout(() => { 7459 promptAction.closeMenu(contentNode); 7460 }, 2000) 7461} 7462 7463@Entry 7464@Component 7465struct Index { 7466 build() { 7467 Column() { 7468 Button('OpenMenu', { type: ButtonType.Normal, stateEffect: true }) 7469 .borderRadius('16lpx') 7470 .width('80%') 7471 .margin(10) 7472 .onClick(() => { 7473 let context = this.getUIContext() 7474 const contentNode = new ComponentContent(context, wrapBuilder(MyMenu)); 7475 doSomething(context, this.getUniqueId(), contentNode) 7476 }) 7477 } 7478 } 7479} 7480``` 7481 7482## DragController<sup>11+</sup> 7483以下API需先使用UIContext中的[getDragController()](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取UIContext实例,再通过此实例调用对应方法。 7484 7485### executeDrag<sup>11+</sup> 7486 7487executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo, callback: AsyncCallback<dragController.DragEventParam>): void 7488 7489主动发起拖拽能力,传入拖拽发起后跟手效果所拖拽的对象以及携带拖拽信息。通过回调返回拖拽事件结果。 7490 7491**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7492 7493**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7494 7495**参数:** 7496 7497| 参数名 | 类型 | 必填 | 说明 | 7498| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 7499| custom | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明) | 是 | 拖拽发起后跟手效果所拖拽的对象。 <br/> **说明:** <br/>不支持全局builder。如果builder中使用了[Image](arkui-ts/ts-basic-components-image.md)组件,应尽量开启同步加载,即配置Image的[syncLoad](arkui-ts/ts-basic-components-image.md#syncload8)为true。该builder只用于生成当次拖拽中显示的图片,builder的修改不会同步到当前正在拖拽的图片,对builder的修改需要在下一次拖拽时生效。 | 7500| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | 是 | 拖拽信息。 | 7501| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<[dragController.DragEventParam](js-apis-arkui-dragController.md#drageventparam12)> | 是 | 拖拽结束返回结果的回调<br/>- event:拖拽事件信息,仅包括拖拽结果。<br/>- extraParams:拖拽事件额外信息。 | 7502 7503**错误码:** 7504以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 7505 7506| 错误码ID | 错误信息 | 7507| -------- | ------------- | 7508| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7509| 100001 | Internal handling failed. | 7510 7511**示例:** 7512 7513```ts 7514import { dragController } from "@kit.ArkUI" 7515import { unifiedDataChannel } from '@kit.ArkData'; 7516 7517@Entry 7518@Component 7519struct DragControllerPage { 7520 @Builder DraggingBuilder() { 7521 Column() { 7522 Text("DraggingBuilder") 7523 } 7524 .width(100) 7525 .height(100) 7526 .backgroundColor(Color.Blue) 7527 } 7528 7529 build() { 7530 Column() { 7531 Button('touch to execute drag') 7532 .onTouch((event?:TouchEvent) => { 7533 if(event){ 7534 if (event.type == TouchType.Down) { 7535 let text = new unifiedDataChannel.Text() 7536 let unifiedData = new unifiedDataChannel.UnifiedData(text) 7537 7538 let dragInfo: dragController.DragInfo = { 7539 pointerId: 0, 7540 data: unifiedData, 7541 extraParams: '' 7542 } 7543 class tmp{ 7544 event:DragEvent|undefined = undefined 7545 extraParams:string = '' 7546 } 7547 let eve:tmp = new tmp() 7548 this.getUIContext().getDragController().executeDrag(()=>{this.DraggingBuilder()}, dragInfo, (err, eve) => { 7549 if(eve.event){ 7550 if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) { 7551 // ... 7552 } else if (eve.event.getResult() == DragResult.DRAG_FAILED) { 7553 // ... 7554 } 7555 } 7556 }) 7557 } 7558 } 7559 }) 7560 } 7561 } 7562} 7563``` 7564 7565### executeDrag<sup>11+</sup> 7566 7567executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo): Promise<dragController.DragEventParam> 7568 7569主动发起拖拽能力,传入拖拽发起后跟手效果所拖拽的对象以及携带拖拽信息。通过Promise返回拖拽事件结果。 7570 7571**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7572 7573**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7574 7575**参数:** 7576 7577| 参数名 | 类型 | 必填 | 说明 | 7578| -------- | ------------------------------------------------------------ | ---- | -------------------------------- | 7579| custom | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明) | 是 | 拖拽发起后跟手效果所拖拽的对象。 | 7580| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | 是 | 拖拽信息。 | 7581 7582**返回值:** 7583 7584| 类型 | 说明 | 7585| ------------------------------------------------------------ | ------------------------------------------------------------ | 7586| Promise<[dragController.DragEventParam](js-apis-arkui-dragController.md#drageventparam12)> | 拖拽结束返回结果的回调<br/>- event:拖拽事件信息,仅包括拖拽结果。<br/>- extraParams:拖拽事件额外信息。 | 7587 7588**错误码:** 7589以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 7590 7591| 错误码ID | 错误信息 | 7592| -------- | ------------- | 7593| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7594| 100001 | Internal handling failed. | 7595 7596**示例:** 7597 7598```ts 7599import { dragController } from "@kit.ArkUI" 7600import { image } from '@kit.ImageKit'; 7601import { unifiedDataChannel } from '@kit.ArkData'; 7602 7603@Entry 7604@Component 7605struct DragControllerPage { 7606 @State pixmap: image.PixelMap|null = null 7607 7608 @Builder DraggingBuilder() { 7609 Column() { 7610 Text("DraggingBuilder") 7611 } 7612 .width(100) 7613 .height(100) 7614 .backgroundColor(Color.Blue) 7615 } 7616 7617 @Builder PixmapBuilder() { 7618 Column() { 7619 Text("PixmapBuilder") 7620 } 7621 .width(100) 7622 .height(100) 7623 .backgroundColor(Color.Blue) 7624 } 7625 7626 build() { 7627 Column() { 7628 Button('touch to execute drag') 7629 .onTouch((event?:TouchEvent) => { 7630 if(event){ 7631 if (event.type == TouchType.Down) { 7632 let text = new unifiedDataChannel.Text() 7633 let unifiedData = new unifiedDataChannel.UnifiedData(text) 7634 7635 let dragInfo: dragController.DragInfo = { 7636 pointerId: 0, 7637 data: unifiedData, 7638 extraParams: '' 7639 } 7640 let pb:CustomBuilder = ():void=>{this.PixmapBuilder()} 7641 this.getUIContext().getComponentSnapshot().createFromBuilder(pb).then((pix: image.PixelMap) => { 7642 this.pixmap = pix; 7643 let dragItemInfo: DragItemInfo = { 7644 pixelMap: this.pixmap, 7645 builder: ()=>{this.DraggingBuilder()}, 7646 extraInfo: "DragItemInfoTest" 7647 } 7648 7649 class tmp{ 7650 event:DragResult|undefined = undefined 7651 extraParams:string = '' 7652 } 7653 let eve:tmp = new tmp() 7654 this.getUIContext().getDragController().executeDrag(dragItemInfo, dragInfo) 7655 .then((eve) => { 7656 if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) { 7657 // ... 7658 } else if (eve.event.getResult() == DragResult.DRAG_FAILED) { 7659 // ... 7660 } 7661 }) 7662 .catch((err:Error) => { 7663 }) 7664 }) 7665 } 7666 } 7667 }) 7668 } 7669 .width('100%') 7670 .height('100%') 7671 } 7672} 7673``` 7674 7675### createDragAction<sup>11+</sup> 7676 7677createDragAction(customArray: Array<CustomBuilder \| DragItemInfo>, dragInfo: dragController.DragInfo): dragController.DragAction 7678 7679创建拖拽的Action对象,需要显式指定拖拽背板图(可多个),以及拖拽的数据,跟手点等信息;当通过一个已创建的 Action 对象发起的拖拽未结束时,无法再次创建新的 Action 对象,接口会抛出异常;当Action对象的生命周期结束后,注册在该对象上的回调函数会失效,因此需要在一个尽量长的作用域下持有该对象,并在每次发起拖拽前通过createDragAction返回新的对象覆盖旧值。 7680 7681**说明:** 建议控制传递的拖拽背板数量,传递过多容易导致拖起的效率问题。 7682 7683**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7684 7685**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7686 7687**参数:** 7688 7689| 参数名 | 类型 | 必填 | 说明 | 7690| -------- | ------------------------------------------------------------ | ---- | -------------------------------- | 7691| customArray | Array<[CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明)> | 是 | 拖拽发起后跟手效果所拖拽的对象。 | 7692| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | 是 | 拖拽信息。 | 7693 7694**返回值:** 7695 7696| 类型 | 说明 | 7697| ------------------------------------------------------ | ------------------ | 7698| [dragController.DragAction](js-apis-arkui-dragController.md#dragaction11)| 创建拖拽Action对象,主要用于后面实现注册监听拖拽状态改变事件和启动拖拽服务。 | 7699 7700**错误码:** 7701以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 7702 7703| 错误码ID | 错误信息 | 7704| -------- | ------------- | 7705| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 7706| 100001 | Internal handling failed. | 7707 7708**示例:** 77091.在EntryAbility.ets中获取UI上下文并保存至LocalStorage中。 7710```ts 7711import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 7712import { hilog } from '@kit.PerformanceAnalysisKit'; 7713import { window, UIContext } from '@kit.ArkUI'; 7714 7715let uiContext: UIContext; 7716let localStorage: LocalStorage = new LocalStorage('uiContext'); 7717 7718export default class EntryAbility extends UIAbility { 7719 storage: LocalStorage = localStorage; 7720 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 7721 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 7722 } 7723 7724 onDestroy(): void { 7725 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); 7726 } 7727 7728 onWindowStageCreate(windowStage: window.WindowStage): void { 7729 // Main window is created, set main page for this ability 7730 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 7731 7732 windowStage.loadContent('pages/Index', this.storage, (err, data) => { 7733 if (err.code) { 7734 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 7735 return; 7736 } 7737 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 7738 windowStage.getMainWindow((err, data) => 7739 { 7740 if (err.code) { 7741 console.error('Failed to abtain the main window. Cause:' + err.message); 7742 return; 7743 } 7744 let windowClass: window.Window = data; 7745 uiContext = windowClass.getUIContext(); 7746 this.storage.setOrCreate<UIContext>('uiContext', uiContext); 7747 // 获取UIContext实例 7748 }) 7749 }); 7750 } 7751 7752 onWindowStageDestroy(): void { 7753 // Main window is destroyed, release UI related resources 7754 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); 7755 } 7756 7757 onForeground(): void { 7758 // Ability has brought to foreground 7759 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); 7760 } 7761 7762 onBackground(): void { 7763 // Ability has back to background 7764 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); 7765 } 7766} 7767``` 77682.通过this.getUIContext().getSharedLocalStorage()获取上下文,进而获取DragController对象实施后续操作。 7769```ts 7770import { dragController, componentSnapshot, UIContext, DragController } from "@kit.ArkUI" 7771import { image } from '@kit.ImageKit'; 7772import { unifiedDataChannel } from '@kit.ArkData'; 7773 7774@Entry() 7775@Component 7776struct DragControllerPage { 7777 @State pixmap: image.PixelMap|null = null 7778 private dragAction: dragController.DragAction|null = null; 7779 customBuilders:Array<CustomBuilder | DragItemInfo> = new Array<CustomBuilder | DragItemInfo>(); 7780 storages = this.getUIContext().getSharedLocalStorage() 7781 7782 @Builder DraggingBuilder() { 7783 Column() { 7784 Text("DraggingBuilder") 7785 } 7786 .width(100) 7787 .height(100) 7788 .backgroundColor(Color.Blue) 7789 } 7790 7791 build() { 7792 Column() { 7793 7794 Column() { 7795 Text("测试") 7796 } 7797 .width(100) 7798 .height(100) 7799 .backgroundColor(Color.Red) 7800 7801 Button('多对象dragAction customBuilder拖拽').onTouch((event?:TouchEvent) => { 7802 if(event){ 7803 if (event.type == TouchType.Down) { 7804 console.info("muti drag Down by listener"); 7805 this.customBuilders.push(()=>{this.DraggingBuilder()}); 7806 this.customBuilders.push(()=>{this.DraggingBuilder()}); 7807 this.customBuilders.push(()=>{this.DraggingBuilder()}); 7808 let text = new unifiedDataChannel.Text() 7809 let unifiedData = new unifiedDataChannel.UnifiedData(text) 7810 let dragInfo: dragController.DragInfo = { 7811 pointerId: 0, 7812 data: unifiedData, 7813 extraParams: '' 7814 } 7815 try{ 7816 let uiContext: UIContext = this.storages?.get<UIContext>('uiContext') as UIContext; 7817 this.dragAction = uiContext.getDragController().createDragAction(this.customBuilders, dragInfo) 7818 if(!this.dragAction){ 7819 console.info("listener dragAction is null"); 7820 return 7821 } 7822 this.dragAction.on('statusChange', (dragAndDropInfo)=>{ 7823 if (dragAndDropInfo.status == dragController.DragStatus.STARTED) { 7824 console.info("drag has start"); 7825 } else if (dragAndDropInfo.status == dragController.DragStatus.ENDED){ 7826 console.info("drag has end"); 7827 if (!this.dragAction) { 7828 return 7829 } 7830 this.customBuilders.splice(0, this.customBuilders.length) 7831 this.dragAction.off('statusChange') 7832 } 7833 }) 7834 this.dragAction.startDrag().then(()=>{}).catch((err:Error)=>{ 7835 console.error("start drag Error:" + err.message); 7836 }) 7837 } catch(err) { 7838 console.error("create dragAction Error:" + err.message); 7839 } 7840 } 7841 } 7842 }).margin({top:20}) 7843 } 7844 } 7845} 7846``` 7847 7848### getDragPreview<sup>11+</sup> 7849 7850getDragPreview(): dragController.DragPreview 7851 7852返回一个代表拖拽背板的对象。 7853 7854**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7855 7856**系统能力:** SystemCapability.ArkUI.ArkUI.Full 7857 7858**返回值:** 7859 7860| 类型 | 说明 | 7861| ------------------------------------------------------------ | ------------------------------------------------------------ | 7862| [dragController.DragPreview](js-apis-arkui-dragController.md#dragpreview11) | 一个代表拖拽背板的对象,提供背板样式设置的接口,在OnDrop和OnDragEnd回调中使用不生效。 | 7863 7864**错误码:** 通用错误码请参考[通用错误码说明文档](../errorcode-universal.md)。 7865 7866**示例:** 7867 7868请参考[animate](js-apis-arkui-dragController.md#animate11) 7869 7870### setDragEventStrictReportingEnabled<sup>12+</sup> 7871 7872setDragEventStrictReportingEnabled(enable: boolean): void 7873 7874当目标从父组件拖拽到子组件时,通过该方法设置是否会触发父组件的onDragLeave的回调。 7875 7876**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 7877 7878**系统能力:** : SystemCapability.ArkUI.ArkUI.Full 7879 7880**参数:** 7881 7882| 参数名 | 类型 | 必填 | 说明 | 7883| ------ | ------- | ---- | ------------------------------------------------------------ | 7884| enable | boolean | 是 | 将目标从父组件拖拽到子组件时,是否会触发父组件的onDragLeave的回调。true表示触发父组件的onDragLeave的回调,false表示不触发。 | 7885 7886**示例:** 7887 7888```ts 7889import { UIAbility } from '@kit.AbilityKit'; 7890import { window, UIContext } from '@kit.ArkUI'; 7891 7892 export default class EntryAbility extends UIAbility { 7893 onWindowStageCreate(windowStage: window.WindowStage): void { 7894 windowStage.loadContent('pages/Index', (err, data) => { 7895 if (err.code) { 7896 return; 7897 } 7898 windowStage.getMainWindow((err, data) => { 7899 if (err.code) { 7900 return; 7901 } 7902 let windowClass: window.Window = data; 7903 let uiContext: UIContext = windowClass.getUIContext(); 7904 uiContext.getDragController().setDragEventStrictReportingEnabled(true); 7905 }); 7906 }); 7907 } 7908} 7909``` 7910 7911### cancelDataLoading<sup>15+</sup> 7912 7913cancelDataLoading(key: string): void 7914 7915当使用[startDataLoading](arkui-ts/ts-universal-events-drag-drop.md#dragevent7)获取拖拽数据时,可调用该接口取消数据传输。 7916 7917**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 7918 7919**系统能力:** : SystemCapability.ArkUI.ArkUI.Full 7920 7921**参数:** 7922 7923| 参数名 | 类型 | 必填 | 说明 | 7924| ------ | ------- | ---- | ------------------------------------------------------------ | 7925| key | string | 是 | 拖拽数据的标识,用于区分每次拖拽。key可通过startDataLoading接口获取。 | 7926 7927**错误码:** 7928 7929以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[拖拽事件错误码](./errorcode-drag-event.md)。 7930 7931| 错误码ID | 错误信息 | 7932| -------- | ------------------------------------------------------------ | 7933| 401 | Parameter error. | 7934| 190004 | Operation failed. | 7935 7936### notifyDragStartRequest<sup>18+</sup> 7937 7938notifyDragStartRequest(requestStatus: dragController.DragStartRequestStatus): void 7939 7940控制应用是否可以发起拖拽。 7941 7942**原子化服务API**: 从API version 18开始,该接口支持在原子化服务中使用。 7943 7944**系统能力**: SystemCapability.ArkUI.ArkUI.Full 7945 7946**参数:** 7947 7948| 参数名 | 类型 | 必填| 说明 | 7949| ------ | ------- | ---- | ------------------------------------------------------------ | 7950| requestStatus | [dragController.DragStartRequestStatus](js-apis-arkui-dragController.md#dragstartrequeststatus18) | 是 |定义应用是否可以发起拖拽。| 7951 7952**示例:** 7953 7954```ts 7955import { unifiedDataChannel } from '@kit.ArkData'; 7956import { image } from '@kit.ImageKit'; 7957import { dragController } from "@kit.ArkUI"; 7958 7959// xxx.ets 7960@Entry 7961@Component 7962struct NormalEts { 7963 @State finished: boolean = false 7964 @State timeout1: number = 1 7965 @State pixmap: image.PixelMap | undefined = undefined 7966 @State unifiedData1: unifiedDataChannel.UnifiedData | undefined = undefined 7967 @State previewData: DragItemInfo | undefined = undefined 7968 7969 loadData() { 7970 let timeout = setTimeout(() => { 7971 this.getUIContext().getComponentSnapshot().get("image1", (error: Error, pixmap: image.PixelMap) => { 7972 this.pixmap = pixmap 7973 this.previewData = { 7974 pixelMap: this.pixmap 7975 } 7976 }) 7977 7978 let data: unifiedDataChannel.Image = new unifiedDataChannel.Image(); 7979 data.imageUri = "app.media.startIcon"; 7980 let unifiedData = new unifiedDataChannel.UnifiedData(data); 7981 this.unifiedData1 = unifiedData 7982 7983 this.getUIContext().getDragController().notifyDragStartRequest(dragController.DragStartRequestStatus.READY) 7984 }, 4000); 7985 this.timeout1 = timeout 7986 } 7987 7988 7989 build() { 7990 Column({space: 20}) { 7991 Image($r("app.media.startIcon")) 7992 .width(300) 7993 .height(200) 7994 .id("image1") 7995 .draggable(true) 7996 .dragPreview(this.previewData) 7997 .onPreDrag((status: PreDragStatus) => { 7998 if (status == PreDragStatus.PREPARING_FOR_DRAG_DETECTION) { 7999 this.loadData() 8000 } else { 8001 clearTimeout(this.timeout1); 8002 } 8003 }) 8004 .onDragStart((event: DragEvent) => { 8005 if (this.finished == false) { 8006 this.getUIContext().getDragController().notifyDragStartRequest(dragController.DragStartRequestStatus.WAITING) 8007 } else { 8008 event.setData(this.unifiedData1); 8009 } 8010 }) 8011 .onDragEnd(()=>{ 8012 this.finished = false 8013 }) 8014 } 8015 .height(400) 8016 .backgroundColor(Color.Pink) 8017 } 8018} 8019``` 8020 8021## OverlayManager<sup>12+</sup> 8022 8023以下API需先使用UIContext中的[getOverlayManager()](#getoverlaymanager12)方法获取到OverlayManager对象,再通过该对象调用对应方法。 8024> **说明:** 8025> 8026> OverlayManager上节点的层级在Page页面层级之上,在Dialog、Popup、Menu、BindSheet、BindContentCover和Toast等之下。 8027> 8028> OverlayManager上节点安全区域内外的绘制方式与Page一致,键盘避让方式与Page一致。 8029> 8030> 与OverlayManager相关的属性推荐采用AppStorage来进行应用全局存储,以免切换页面后属性值发生变化从而导致业务错误。 8031 8032### addComponentContent<sup>12+</sup> 8033 8034addComponentContent(content: ComponentContent, index?: number): void 8035 8036在OverlayManager上新增指定节点。 8037 8038**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8039 8040**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8041 8042**参数:** 8043 8044| 参数名 | 类型 | 必填 | 说明 | 8045| ------- | ---------------------------------------- | ---- | ----------- | 8046| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是 | 在OverlayManager上新增指定节点上添加此content。 <br>**说明:** <br/> 新增的节点默认处于页面居中,按层级堆叠。| 8047| index | number | 否 | 新增节点在OverlayManager上的层级位置。<br>**说明:** <br/> 当index ≥ 0时,若index的值越大,则ComponentContent的层级越高;当多个ComponentContent的index相同时,若ComponentContent添加的时间越晚,则层级越高。<br/> 当index < 0、index = null或index = undefined时,ComponentContent默认添加至最高层。<br/>当同一个ComponentContent被添加多次时,只保留最后一次添加的ComponentContent。<br/> 8048 8049**示例:** 8050 8051```ts 8052import { ComponentContent, OverlayManager } from '@kit.ArkUI'; 8053 8054class Params { 8055 text: string = ""; 8056 offset: Position; 8057 8058 constructor(text: string, offset: Position) { 8059 this.text = text; 8060 this.offset = offset; 8061 } 8062} 8063 8064@Builder 8065function builderText(params: Params) { 8066 Column() { 8067 Text(params.text) 8068 .fontSize(30) 8069 .fontWeight(FontWeight.Bold) 8070 }.offset(params.offset) 8071} 8072 8073@Entry 8074@Component 8075struct OverlayExample { 8076 @State message: string = 'ComponentContent'; 8077 private uiContext: UIContext = this.getUIContext(); 8078 private overlayNode: OverlayManager = this.uiContext.getOverlayManager(); 8079 @StorageLink('contentArray') contentArray: ComponentContent<Params>[] = []; 8080 @StorageLink('componentContentIndex') componentContentIndex: number = 0; 8081 @StorageLink('arrayIndex') arrayIndex: number = 0; 8082 @StorageLink("componentOffset") componentOffset: Position = { x: 0, y: 80 }; 8083 8084 build() { 8085 Column() { 8086 Button("++componentContentIndex: " + this.componentContentIndex).onClick(() => { 8087 ++this.componentContentIndex; 8088 }) 8089 Button("--componentContentIndex: " + this.componentContentIndex).onClick(() => { 8090 --this.componentContentIndex; 8091 }) 8092 Button("增加ComponentContent" + this.contentArray.length).onClick(() => { 8093 let componentContent = new ComponentContent( 8094 this.uiContext, wrapBuilder<[Params]>(builderText), 8095 new Params(this.message + (this.contentArray.length), this.componentOffset) 8096 ); 8097 this.contentArray.push(componentContent); 8098 this.overlayNode.addComponentContent(componentContent, this.componentContentIndex); 8099 }) 8100 Button("++arrayIndex: " + this.arrayIndex).onClick(() => { 8101 ++this.arrayIndex; 8102 }) 8103 Button("--arrayIndex: " + this.arrayIndex).onClick(() => { 8104 --this.arrayIndex; 8105 }) 8106 Button("删除ComponentContent" + this.arrayIndex).onClick(() => { 8107 if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) { 8108 let componentContent = this.contentArray.splice(this.arrayIndex, 1); 8109 this.overlayNode.removeComponentContent(componentContent.pop()); 8110 } else { 8111 console.info("arrayIndex有误"); 8112 } 8113 }) 8114 Button("显示ComponentContent" + this.arrayIndex).onClick(() => { 8115 if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) { 8116 let componentContent = this.contentArray[this.arrayIndex]; 8117 this.overlayNode.showComponentContent(componentContent); 8118 } else { 8119 console.info("arrayIndex有误"); 8120 } 8121 }) 8122 Button("隐藏ComponentContent" + this.arrayIndex).onClick(() => { 8123 if (this.arrayIndex >= 0 && this.arrayIndex < this.contentArray.length) { 8124 let componentContent = this.contentArray[this.arrayIndex]; 8125 this.overlayNode.hideComponentContent(componentContent); 8126 } else { 8127 console.info("arrayIndex有误"); 8128 } 8129 }) 8130 Button("显示所有ComponentContent").onClick(() => { 8131 this.overlayNode.showAllComponentContents(); 8132 }) 8133 Button("隐藏所有ComponentContent").onClick(() => { 8134 this.overlayNode.hideAllComponentContents(); 8135 }) 8136 8137 Button("跳转页面").onClick(() => { 8138 this.getUIContext().getRouter().pushUrl({ 8139 url: 'pages/Second' 8140 }) 8141 }) 8142 } 8143 .width('100%') 8144 .height('100%') 8145 } 8146} 8147``` 8148 8149### addComponentContentWithOrder<sup>18+</sup> 8150 8151addComponentContentWithOrder(content: ComponentContent, levelOrder?: LevelOrder): void 8152 8153指定显示顺序创建浮层节点。 8154 8155支持在浮层节点创建时指定显示的顺序。 8156 8157**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 8158 8159**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8160 8161**参数:** 8162 8163| 参数名 | 类型 | 必填 | 说明 | 8164| ------- | ---------------------------------------- | ---- | ----------- | 8165| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是 | 在OverlayManager上新增指定节点上添加此content。 <br>**说明:** <br/> 新增的节点默认处于页面居中位置,按层级堆叠。| 8166| levelOrder | [LevelOrder](js-apis-promptAction.md#levelorder18) | 否 | 新增浮层节点的显示顺序。<br />**说明:**<br />- 默认值:LevelOrder.clamp(0)。| 8167 8168**示例:** 8169 8170该示例通过调用addComponentContentWithOrder接口,展示了指定显示顺序创建浮层节点的功能。 8171 8172```ts 8173import { ComponentContent, PromptAction, LevelOrder, UIContext, OverlayManager } from '@kit.ArkUI'; 8174 8175class Params { 8176 text: string = "" 8177 offset: Position 8178 constructor(text: string, offset: Position) { 8179 this.text = text 8180 this.offset = offset 8181 } 8182} 8183@Builder 8184function builderText(params: Params) { 8185 Column() { 8186 Text(params.text) 8187 .fontSize(30) 8188 .fontWeight(FontWeight.Bold) 8189 }.offset(params.offset) 8190} 8191 8192@Entry 8193@Component 8194struct Index { 8195 @State message: string = '弹窗' 8196 private ctx: UIContext = this.getUIContext() 8197 private promptAction: PromptAction = this.ctx.getPromptAction() 8198 private overlayNode: OverlayManager = this.ctx.getOverlayManager() 8199 @StorageLink('contentArray') contentArray: ComponentContent<Params>[] = [] 8200 @StorageLink('componentContentIndex') componentContentIndex: number = 0 8201 @StorageLink('arrayIndex') arrayIndex: number = 0 8202 @StorageLink("componentOffset") componentOffset: Position = {x: 0, y: 80} 8203 8204 build() { 8205 Row() { 8206 Column({ space: 10 }) { 8207 Button('OverlayManager下面弹窗') 8208 .fontSize(20) 8209 .onClick(() => { 8210 let componentContent = new ComponentContent( 8211 this.ctx, wrapBuilder<[Params]>(builderText), 8212 new Params(this.message + (this.contentArray.length), this.componentOffset) 8213 ) 8214 this.contentArray.push(componentContent) 8215 this.overlayNode.addComponentContentWithOrder(componentContent, LevelOrder.clamp(100.1)) 8216 let topOrder: LevelOrder = this.promptAction.getTopOrder(); 8217 if (topOrder !== undefined) { 8218 console.error('topOrder: ' + topOrder.getOrder()); 8219 } 8220 let bottomOrder: LevelOrder = this.promptAction.getBottomOrder(); 8221 if (bottomOrder !== undefined) { 8222 console.error('bottomOrder: ' + bottomOrder.getOrder()); 8223 } 8224 }) 8225 Button('OverlayManager上面弹窗') 8226 .fontSize(20) 8227 .onClick(() => { 8228 let componentContent = new ComponentContent( 8229 this.ctx, wrapBuilder<[Params]>(builderText), 8230 new Params(this.message + (this.contentArray.length), this.componentOffset) 8231 ) 8232 this.contentArray.push(componentContent) 8233 this.overlayNode.addComponentContentWithOrder(componentContent, LevelOrder.clamp(100.2)) 8234 let topOrder: LevelOrder = this.promptAction.getTopOrder(); 8235 if (topOrder !== undefined) { 8236 console.error('topOrder: ' + topOrder.getOrder()); 8237 } 8238 let bottomOrder: LevelOrder = this.promptAction.getBottomOrder(); 8239 if (bottomOrder !== undefined) { 8240 console.error('bottomOrder: ' + bottomOrder.getOrder()); 8241 } 8242 }) 8243 }.width('100%') 8244 }.height('100%') 8245 } 8246} 8247``` 8248 8249### removeComponentContent<sup>12+</sup> 8250 8251removeComponentContent(content: ComponentContent): void 8252 8253在overlay上删除指定节点。 8254 8255**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8256 8257**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8258 8259**参数:** 8260 8261| 参数名 | 类型 | 必填 | 说明 | 8262| ------- | ---------------------------------------- | ---- | ----------- | 8263| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是 | 在OverlayManager上删除此content。 | 8264 8265**示例:** 8266 8267请参考[addComponentContent示例](#addcomponentcontent12) 8268 8269### showComponentContent<sup>12+</sup> 8270 8271showComponentContent(content: ComponentContent): void 8272 8273在OverlayManager上显示指定节点。 8274 8275**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8276 8277**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8278 8279**参数:** 8280 8281| 参数名 | 类型 | 必填 | 说明 | 8282| ------- | ---------------------------------------- | ---- | ----------- | 8283| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是 | 在OverlayManager上显示此content。| 8284 8285**示例:** 8286 8287请参考[addComponentContent示例](#addcomponentcontent12) 8288 8289### hideComponentContent<sup>12+</sup> 8290 8291hideComponentContent(content: ComponentContent): void 8292 8293在OverlayManager上隐藏指定节点。 8294 8295**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8296 8297**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8298 8299**参数:** 8300 8301| 参数名 | 类型 | 必填 | 说明 | 8302| ------- | ---------------------------------------- | ---- | ----------- | 8303| content | [ComponentContent](js-apis-arkui-ComponentContent.md) | 是 | 在OverlayManager上隐藏此content。 | 8304 8305**示例:** 8306 8307请参考[addComponentContent示例](#addcomponentcontent12) 8308 8309### showAllComponentContents<sup>12+</sup> 8310 8311showAllComponentContents(): void 8312 8313显示OverlayManager上所有的ComponentContent。 8314 8315**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8316 8317**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8318 8319**示例:** 8320 8321请参考[addComponentContent示例](#addcomponentcontent12) 8322 8323### hideAllComponentContents<sup>12+</sup> 8324 8325hideAllComponentContents(): void 8326 8327隐藏OverlayManager上的所有ComponentContent。 8328 8329**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8330 8331**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8332 8333**示例:** 8334 8335请参考[addComponentContent示例](#addcomponentcontent12) 8336 8337## OverlayManagerOptions<sup>15+</sup> 8338 8339初始化[OverlayManager](#overlaymanager12)时所用参数。 8340 8341**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 8342 8343**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8344 8345| 名称 | 类型 | 必填 | 说明 | 8346| --------------- | ---------------------- | ------------ | --------------------- | 8347| renderRootOverlay | boolean | 否 | 是否渲染overlay根节点,true表示渲染overlay根节点,false表示不渲染overlay根节点,默认值为true。| 8348 8349## AtomicServiceBar<sup>11+</sup> 8350 8351以下接口需要先使用UIContext中的[getAtomicServiceBar](#getatomicservicebar11)方法获取到AtomicServiceBar对象,再通过该对象调用对应方法。 8352> **说明:** 8353> 8354> 从API version 12开始原子化服务menuBar样式变更,以下接口将失效。 8355 8356### setVisible<sup>11+</sup> 8357 8358setVisible(visible: boolean): void 8359 8360通过该方法设置原子化服务menuBar是否可见。 8361> **说明:** 8362> 8363> 从API version 12开始原子化服务menuBar样式变更,menuBar默认隐藏,变为悬浮按钮,通过该接口无法改变menuBar的可见性。 8364 8365**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 8366 8367**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8368 8369**参数:** 8370 8371| 参数名 | 类型 | 必填 | 说明 | 8372| ------- | ------- | ------- | ------- | 8373| visible | boolean | 是 | 原子化服务menuBar是否可见。true表示设置menuBar可见,false表示设置menuBar不可见。| 8374 8375 8376**示例:** 8377 8378```ts 8379import {UIContext, AtomicServiceBar, window } from '@kit.ArkUI'; 8380import { hilog } from '@kit.PerformanceAnalysisKit'; 8381 8382onWindowStageCreate(windowStage: window.WindowStage) { 8383 // Main window is created, set main page for this ability 8384 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 8385 windowStage.loadContent('pages/Index', (err, data) => { 8386 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 8387 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 8388 if (atomicServiceBar != undefined) { 8389 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 8390 atomicServiceBar.setVisible(false); 8391 } else { 8392 hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 8393 } 8394 }); 8395} 8396``` 8397 8398### setBackgroundColor<sup>11+</sup> 8399 8400setBackgroundColor(color:Nullable<Color | number | string>): void 8401 8402通过该方法设置原子化服务menuBar的背景颜色。 8403> **说明:** 8404> 8405> 从API version 12开始原子化服务menuBar样式变更,menuBar的背景默认隐藏,通过该接口无法改变menuBar的背景颜色。 8406 8407**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8408 8409**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8410 8411**参数:** 8412 8413| 参数名 | 类型 | 必填 | 说明 | 8414| ------ | ------ | ------ | ------ | 8415| color | Nullable\<[Color](arkui-ts/ts-appendix-enums.md#color) \| number \| string> | 是 | 通过该方法设置原子化服务menuBar的背景颜色,undefined代表使用默认颜色。number为HEX格式颜色,支持rgb或者argb,示例:0xffffff。string为rgb或者argb格式颜色,示例:'#ffffff'。| 8416 8417**示例:** 8418 8419```ts 8420import {UIContext, AtomicServiceBar,window } from '@kit.ArkUI'; 8421import { hilog } from '@kit.PerformanceAnalysisKit'; 8422onWindowStageCreate(windowStage: window.WindowStage) { 8423 // Main window is created, set main page for this ability 8424 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 8425 windowStage.loadContent('pages/Index', (err, data) => { 8426 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 8427 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 8428 if (atomicServiceBar != undefined) { 8429 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 8430 atomicServiceBar.setBackgroundColor(0x88888888); 8431 } else { 8432 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 8433 } 8434 }); 8435} 8436``` 8437 8438### setTitleContent<sup>11+</sup> 8439 8440setTitleContent(content:string): void 8441 8442通过该方法设置原子化服务menuBar的标题内容。 8443> **说明:** 8444> 8445> 从API version 12开始原子化服务menuBar样式变更,menuBar的标题默认隐藏,通过该接口无法改变menuBar的标题内容。 8446 8447**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8448 8449**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8450 8451**参数:** 8452 8453|参数名|类型|必填|说明 | 8454| ------- | ------- | ------- | ------- | 8455| content | string | 是 | 原子化服务menuBar中的标题内容。| 8456 8457**示例:** 8458 8459```ts 8460import {UIContext, AtomicServiceBar,window } from '@kit.ArkUI'; 8461import { hilog } from '@kit.PerformanceAnalysisKit'; 8462 8463onWindowStageCreate(windowStage: window.WindowStage) { 8464 // Main window is created, set main page for this ability 8465 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 8466 windowStage.loadContent('pages/Index', (err, data) => { 8467 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 8468 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 8469 if (atomicServiceBar != undefined) { 8470 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 8471 atomicServiceBar.setTitleContent('text2'); 8472 } else { 8473 hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 8474 } 8475 }); 8476} 8477``` 8478 8479### setTitleFontStyle<sup>11+</sup> 8480 8481setTitleFontStyle(font:FontStyle):void 8482 8483通过该方法设置原子化服务menuBar的字体样式。 8484> **说明:** 8485> 8486> 从API version 12开始原子化服务menuBar样式变更,menuBar的标题默认隐藏,通过该接口无法改变menuBar的字体样式。 8487 8488**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8489 8490**系统能力:** SystemCapability.ArkUI.ArkUI.Full。 8491 8492**参数:** 8493 8494| 参数名 | 类型 | 必填 | 说明 | 8495| ------ | ------ | ------ | ------ | 8496| font | [FontStyle](arkui-ts/ts-appendix-enums.md#fontstyle) | 是 | 原子化服务menuBar中的字体样式。 | 8497 8498**示例:** 8499 8500```ts 8501import {UIContext, Font, AtomicServiceBar } from '@kit.ArkUI'; 8502import { hilog } from '@kit.PerformanceAnalysisKit'; 8503 8504onWindowStageCreate(windowStage: window.WindowStage) { 8505 // Main window is created, set main page for this ability 8506 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 8507 windowStage.loadContent('pages/Index', (err, data) => { 8508 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 8509 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 8510 if (atomicServiceBar != undefined) { 8511 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 8512 atomicServiceBar.setTitleFontStyle(FontStyle.Normal); 8513 } else { 8514 hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 8515 } 8516 }); 8517} 8518``` 8519 8520### setIconColor<sup>11+</sup> 8521 8522setIconColor(color:Nullable<Color | number | string>): void 8523 8524通过该方法设置原子化服务图标的颜色。 8525> **说明:** 8526> 8527> 从API version 12开始原子化服务menuBar样式变更,menuBar默认隐藏,悬浮按钮图标不予用户设置,通过该接口无法改变menuBar的图标颜色。 8528 8529**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8530 8531**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8532 8533**参数:** 8534 8535| 参数名 | 类型 | 必填 | 说明 | 8536| ------- | ------- | ------- | ------- | 8537| color | Nullable\<[Color](arkui-ts/ts-appendix-enums.md#color) \| number \| string> | 是 | 原子化服务图标的颜色,undefined代表使用默认颜色。number为HEX格式颜色,支持rgb或者argb,示例:0xffffff。string为rgb或者argb格式颜色,示例:'#ffffff'。 | 8538 8539 8540**示例:** 8541 8542```ts 8543import {UIContext, Font, window } from '@kit.ArkUI'; 8544import { hilog } from '@kit.PerformanceAnalysisKit'; 8545 8546onWindowStageCreate(windowStage: window.WindowStage) { 8547 // Main window is created, set main page for this ability 8548 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 8549 windowStage.loadContent('pages/Index', (err, data) => { 8550 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 8551 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 8552 if (atomicServiceBar != undefined) { 8553 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 8554 atomicServiceBar.setIconColor(0x12345678); 8555 } else { 8556 hilog.info(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 8557 } 8558 }); 8559} 8560``` 8561 8562### getBarRect<sup>15+</sup> 8563 8564getBarRect(): Frame 8565 8566获取原子化服务menuBar相对窗口的布局信息。 8567> **说明:** 8568> 8569> 布局信息包含了原子化服务menuBar的左右margin。 8570 8571**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 8572 8573**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8574 8575**返回值:** 8576 8577| 类型 | 说明 | 8578| ----------------- | ------------- | 8579| [Frame](./js-apis-arkui-graphics.md#frame) | 原子化服务menuBar的大小和位置。 | 8580 8581**示例:** 8582 8583```ts 8584import { AtomicServiceBar } from '@kit.ArkUI'; 8585import { hilog } from '@kit.PerformanceAnalysisKit'; 8586@Entry 8587@Component 8588struct Index { 8589 build() { 8590 Button("getBarRect") 8591 .onClick(() => { 8592 let uiContext: UIContext = this.getUIContext(); 8593 let currentBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 8594 if (currentBar != undefined) { 8595 let rect = currentBar.getBarRect(); 8596 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully. x:' + 8597 rect.x + ' y:' + rect.y + ' width:' + rect.width + ' height:' + rect.height); 8598 } else { 8599 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar failed.'); 8600 } 8601 }) 8602 } 8603} 8604``` 8605 8606## KeyboardAvoidMode<sup>11+</sup> 8607 8608配置键盘避让时页面的避让模式。 8609 8610**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8611 8612| 名称 | 值 | 说明 | 8613| ------ | ---- | ---------- | 8614| OFFSET | 0 | 上抬模式。 <br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。| 8615| RESIZE | 1 | 压缩模式。 <br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。| 8616| OFFSET_WITH_CARET<sup>14+</sup> | 2 | 上抬模式,输入框光标位置发生变化时候也会触发避让。<br/>**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。| 8617| RESIZE_WITH_CARET<sup>14+</sup> | 3 | 压缩模式,输入框光标位置发生变化时候也会触发避让。<br/>**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。| 8618| NONE<sup>14+</sup> | 4 | 不避让键盘。<br/>**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。| 8619 8620 8621## FocusController<sup>12+</sup> 8622以下API需先使用UIContext中的[getFocusController()](js-apis-arkui-UIContext.md#getFocusController12)方法获取UIContext实例,再通过此实例调用对应方法。 8623 8624### clearFocus<sup>12+</sup> 8625 8626clearFocus(): void 8627 8628清除焦点,将焦点强制转移到页面根容器节点,焦点链路上其他节点失焦。 8629 8630**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8631 8632**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8633 8634**示例:** 8635 8636```ts 8637@Entry 8638@Component 8639struct ClearFocusExample { 8640 @State inputValue: string = '' 8641 @State btColor: Color = Color.Blue 8642 8643 build() { 8644 Column({ space: 20 }) { 8645 Column({ space: 5 }) { 8646 Button('button1') 8647 .width(200) 8648 .height(70) 8649 .fontColor(Color.White) 8650 .focusOnTouch(true) 8651 .backgroundColor(Color.Blue) 8652 Button('button2') 8653 .width(200) 8654 .height(70) 8655 .fontColor(Color.White) 8656 .focusOnTouch(true) 8657 .backgroundColor(this.btColor) 8658 .defaultFocus(true) 8659 .onFocus(() => { 8660 this.btColor = Color.Red 8661 }) 8662 .onBlur(() => { 8663 this.btColor = Color.Blue 8664 }) 8665 Button('clearFocus') 8666 .width(200) 8667 .height(70) 8668 .fontColor(Color.White) 8669 .backgroundColor(Color.Blue) 8670 .onClick(() => { 8671 this.getUIContext().getFocusController().clearFocus() 8672 }) 8673 } 8674 } 8675 .width('100%') 8676 .height('100%') 8677 } 8678} 8679``` 8680 8681### requestFocus<sup>12+</sup> 8682 8683requestFocus(key: string): void 8684 8685通过组件的id将焦点转移到组件树对应的实体节点。当前帧生效。 8686 8687**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8688 8689**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8690 8691**参数:** 8692 8693| 参数名 | 类型 | 必填 | 说明 | 8694| ------- | ------- | ------- | ------- | 8695| key | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。| 8696 8697**错误码:** 8698 8699以下错误码的详细介绍请参见[焦点错误码](errorcode-focus.md)。 8700 8701| 错误码ID | 错误信息 | 8702| -------- | ----------------------------------------------- | 8703| 150001 | the component cannot be focused. | 8704| 150002 | This component has an unfocusable ancestor. | 8705| 150003 | the component is not on tree or does not exist. | 8706 8707**示例:** 8708 8709```ts 8710@Entry 8711@Component 8712struct RequestExample { 8713 @State btColor: Color = Color.Blue 8714 8715 build() { 8716 Column({ space: 20 }) { 8717 Column({ space: 5 }) { 8718 Button('Button') 8719 .width(200) 8720 .height(70) 8721 .fontColor(Color.White) 8722 .focusOnTouch(true) 8723 .backgroundColor(this.btColor) 8724 .onFocus(() => { 8725 this.btColor = Color.Red 8726 }) 8727 .onBlur(() => { 8728 this.btColor = Color.Blue 8729 }) 8730 .id("testButton") 8731 8732 Divider() 8733 .vertical(false) 8734 .width("80%") 8735 .backgroundColor(Color.Black) 8736 .height(10) 8737 8738 Button('requestFocus') 8739 .width(200) 8740 .height(70) 8741 .onClick(() => { 8742 this.getUIContext().getFocusController().requestFocus("testButton") 8743 }) 8744 8745 Button('requestFocus fail') 8746 .width(200) 8747 .height(70) 8748 .onClick(() => { 8749 try { 8750 this.getUIContext().getFocusController().requestFocus("eee") 8751 } catch (error) { 8752 console.error('requestFocus failed code is ' + error.code + ' message is ' + error.message) 8753 } 8754 }) 8755 } 8756 } 8757 .width('100%') 8758 .height('100%') 8759 } 8760} 8761``` 8762 8763### activate<sup>14+</sup> 8764 8765activate(isActive: boolean, autoInactive?: boolean): void 8766 8767设置当前界面的[焦点激活态](../../ui/arkts-common-events-focus-event.md)。 8768 8769**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。 8770 8771**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8772 8773**参数:** 8774 8775| 参数名 | 类型 | 必填 | 说明 | 8776| ------- | ------- | ------- | ------- | 8777| isActive| boolean| 是 | 设置是否进入/退出焦点激活态。<br/>true表示设置进入焦点激活态,false表示设置退出焦点激活态。 | 8778| autoInactive | boolean | 否 | 设置焦点激活态退出逻辑。<br/>为true时,会自动在触摸事件、鼠标事件触发时退出,为false时,仅受开发者API控制。<br/>默认值:true | 8779 8780```ts 8781// 该示例表示在页面加载完成时进入焦点激活态,可按方向键在button间走焦 8782@Entry 8783@Component 8784struct ActivateExample { 8785 aboutToAppear() { 8786 this.getUIContext().getFocusController().activate(true, false) 8787 } 8788 8789 aboutToDisappear() { 8790 this.getUIContext().getFocusController().activate(false) 8791 } 8792 8793 build() { 8794 Row() { 8795 Button('Button1') 8796 .width(200) 8797 .height(70) 8798 .defaultFocus(true) 8799 8800 Button('Button2') 8801 .width(200) 8802 .height(70) 8803 8804 Button('Button3') 8805 .width(200) 8806 .height(70) 8807 } 8808 .padding(10) 8809 .justifyContent(FlexAlign.SpaceBetween) 8810 .width(800) 8811 } 8812} 8813``` 8814 8815### setAutoFocusTransfer<sup>14+</sup> 8816 8817setAutoFocusTransfer(isAutoFocusTransfer: boolean): void; 8818 8819设置页面切换时,新的页面是否需要主动获取焦点。 8820 8821**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。 8822 8823**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8824 8825**参数:** 8826 8827| 参数名 | 类型 | 必填 | 说明 | 8828| ------- | ------- | ------- | ------- | 8829| isAutoFocusTransfer | boolean| 是 | 设置页面切换时,新的页面是否需要主动获取焦点,例如[Router](js-apis-router.md#routerpushurldeprecated)、[Navigation](arkui-ts/ts-basic-components-navigation.md#navigation)、[Menu](arkui-ts/ts-basic-components-menu.md#menu)、[Dialog](arkui-ts/ohos-arkui-advanced-Dialog.md)、[Popup](arkui-ts/ohos-arkui-advanced-Popup.md#popup)等。true表示需要主动获取焦点,false表示不需要主动获取焦点。默认值为true。 | 8830 8831```ts 8832@CustomDialog 8833struct CustomDialogExample { 8834 controller?: CustomDialogController 8835 build() { 8836 Column() { 8837 Text('这是自定义弹窗') 8838 .fontSize(30) 8839 .height(100) 8840 Text('弹窗不能主动获取焦点') 8841 .fontSize(20) 8842 .height(100) 8843 Button('点我关闭弹窗') 8844 .onClick(() => { 8845 if (this.controller != undefined) { 8846 this.getUIContext().getFocusController().setAutoFocusTransfer(true) 8847 this.controller.close() 8848 } 8849 }) 8850 .margin(20) 8851 } 8852 } 8853} 8854@Entry 8855@Component 8856struct CustomDialogUser { 8857 dialogController: CustomDialogController | null = new CustomDialogController({ 8858 builder: CustomDialogExample({ 8859 }), 8860 }) 8861 aboutToDisappear() { 8862 this.dialogController = null 8863 } 8864 8865 build() { 8866 Column() { 8867 Button('click me') 8868 .onClick(() => { 8869 if (this.dialogController != null) { 8870 this.getUIContext().getFocusController().setAutoFocusTransfer(false) 8871 this.dialogController.open() 8872 } 8873 }).backgroundColor(0x317aff) 8874 }.width('100%').margin({ top: 5 }) 8875 } 8876} 8877``` 8878 8879### setKeyProcessingMode<sup>15+</sup> 8880 8881setKeyProcessingMode(mode: KeyProcessingMode): void 8882 8883设置按键事件处理的优先级。 8884 8885**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 8886 8887**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8888 8889**参数:** 8890 8891| 参数名 | 类型 | 必填 | 说明 | 8892| ------- | ------- | ------- | ------- | 8893| mode | [KeyProcessingMode](./arkui-ts/ts-universal-attributes-focus.md#keyprocessingmode15)| 是 | 按键处理模式。 | 8894 8895```ts 8896 8897// 该示例演示了在页面加载完成后设置走焦类型的实现方式。 8898@Entry 8899@Component 8900struct Index { 8901 8902 aboutToAppear() { 8903 this.getUIContext().getFocusController().setKeyProcessingMode(KeyProcessingMode.ANCESTOR_EVENT) 8904 } 8905 8906 build() { 8907 Row() { 8908 Row() { 8909 Button('Button1').id('Button1').onKeyEvent((event) => { 8910 console.log("Button1"); 8911 return true 8912 }) 8913 Button('Button2').id('Button2').onKeyEvent((event) => { 8914 console.log("Button2"); 8915 return true 8916 }) 8917 } 8918 .width('100%') 8919 .height('100%') 8920 .id('Row1') 8921 .onKeyEventDispatch((event) => { 8922 let context = this.getUIContext(); 8923 context.getFocusController().requestFocus('Button1'); 8924 return context.dispatchKeyEvent('Button1', event); 8925 }) 8926 } 8927 .height('100%') 8928 .width('100%') 8929 .onKeyEventDispatch((event) => { 8930 if (event.type == KeyType.Down) { 8931 let context = this.getUIContext(); 8932 context.getFocusController().requestFocus('Row1'); 8933 return context.dispatchKeyEvent('Row1', event); 8934 } 8935 return true; 8936 }) 8937 } 8938} 8939``` 8940 8941## PointerStyle<sup>12+</sup> 8942 8943type PointerStyle = pointer.PointerStyle 8944 8945光标样式。 8946 8947**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8948 8949**系统能力:** SystemCapability.MultimodalInput.Input.Pointer 8950 8951|类型|说明| 8952| -- | -- | 8953|[pointer.PointerStyle](../apis-input-kit/js-apis-pointer.md#pointerstyle) |光标样式。| 8954 8955## CursorController<sup>12+</sup> 8956以下API需先使用UIContext中的[getCursorController()](js-apis-arkui-UIContext.md#getcursorcontroller12)方法获取CursorController实例,再通过此实例调用对应方法。 8957 8958### restoreDefault<sup>12+</sup> 8959 8960restoreDefault(): void 8961 8962恢复默认的光标样式 8963 8964**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 8965 8966**系统能力:** SystemCapability.ArkUI.ArkUI.Full 8967 8968**示例:** 8969当光标移出绿框时,通过CursorController的restoreDefault方法恢复默认光标样式 8970 8971```ts 8972import { pointer } from '@kit.InputKit'; 8973import { UIContext, CursorController } from '@kit.ArkUI'; 8974 8975@Entry 8976@Component 8977struct CursorControlExample { 8978 @State text: string = '' 8979 cursorCustom: CursorController = this.getUIContext().getCursorController(); 8980 8981 build() { 8982 Column() { 8983 Row().height(200).width(200).backgroundColor(Color.Green).position({x: 150 ,y:70}) 8984 .onHover((flag) => { 8985 if (flag) { 8986 this.cursorCustom.setCursor(pointer.PointerStyle.EAST) 8987 } else { 8988 console.info("restoreDefault"); 8989 this.cursorCustom.restoreDefault(); 8990 } 8991 }) 8992 }.width('100%') 8993 } 8994} 8995``` 8996 8997 8998### setCursor<sup>12+</sup> 8999 9000setCursor(value: PointerStyle): void 9001 9002更改当前的鼠标光标样式 9003 9004**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 9005 9006**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9007 9008**参数:** 9009 9010| 参数名 | 类型 | 必填 | 说明 | 9011| ------- | ---------------------------------------- | ---- | ------- | 9012| value | [PointerStyle](#pointerstyle12) | 是 | 光标样式 | 9013 9014**示例:** 9015当光标进入蓝框时,通过CursorController的setCursor方法修改光标样式为PointerStyle.WEST 9016 9017```ts 9018import { pointer } from '@kit.InputKit'; 9019import { UIContext, CursorController } from '@kit.ArkUI'; 9020 9021@Entry 9022@Component 9023struct CursorControlExample { 9024 @State text: string = '' 9025 cursorCustom: CursorController = this.getUIContext().getCursorController(); 9026 9027 build() { 9028 Column() { 9029 Row().height(200).width(200).backgroundColor(Color.Blue).position({x: 100 ,y:70}) 9030 .onHover((flag) => { 9031 if (flag) { 9032 this.cursorCustom.setCursor(pointer.PointerStyle.WEST) 9033 } else { 9034 this.cursorCustom.restoreDefault(); 9035 } 9036 }) 9037 }.width('100%') 9038 } 9039} 9040``` 9041 9042 9043## ContextMenuController<sup>12+</sup> 9044以下API需先使用UIContext中的[getContextMenuController()](js-apis-arkui-UIContext.md#getcontextmenucontroller12)方法获取ContextMenuController实例,再通过此实例调用对应方法。 9045 9046### close<sup>12+</sup> 9047 9048close(): void 9049 9050关闭菜单 9051 9052**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 9053 9054**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9055 9056**示例:** 9057通过定时器触发,调用ContextMenuController的close方法关闭菜单 9058 9059```ts 9060import { ContextMenuController } from '@kit.ArkUI'; 9061 9062@Entry 9063@Component 9064struct Index { 9065 menu: ContextMenuController = this.getUIContext().getContextMenuController(); 9066 9067 @Builder MenuBuilder() { 9068 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 9069 Button('Test ContextMenu1 Close') 9070 Divider().strokeWidth(2).margin(5).color(Color.Black) 9071 Button('Test ContextMenu2') 9072 Divider().strokeWidth(2).margin(5).color(Color.Black) 9073 Button('Test ContextMenu3') 9074 } 9075 .width(200) 9076 .height(160) 9077 } 9078 9079 build() { 9080 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 9081 Button("启动定时器").onClick(()=> 9082 { 9083 setTimeout(() => { 9084 this.menu.close(); 9085 }, 10000); 9086 }) 9087 9088 Column() { 9089 Text("Test ContextMenu close") 9090 .fontSize(20) 9091 .width('100%') 9092 .height(500) 9093 .backgroundColor(0xAFEEEE) 9094 .textAlign(TextAlign.Center) 9095 } 9096 .bindContextMenu(this.MenuBuilder, ResponseType.LongPress) 9097 } 9098 .width('100%') 9099 .height('100%') 9100 } 9101} 9102``` 9103 9104 9105 9106## MeasureUtils<sup>12+</sup> 9107 9108以下API需先使用UIContext中的[getMeasureUtils()](js-apis-arkui-UIContext.md#getmeasureutils12)方法获取MeasureUtils实例,再通过此实例调用对应方法。 9109 9110### measureText<sup>12+</sup> 9111 9112measureText(options: MeasureOptions): number 9113 9114计算指定文本单行布局下的宽度。 9115 9116**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 9117 9118**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9119 9120**参数:** 9121 9122| 参数名 | 类型 | 必填 | 说明 | 9123| ------- | ------------------------------- | ---- | --------- | 9124| options | [MeasureOptions](js-apis-measure.md#measureoptions) | 是 | 被计算文本描述信息。 | 9125 9126**返回值:** 9127 9128| 类型 | 说明 | 9129| ------------ | --------- | 9130| number | 文本宽度。<br/>**说明:**<br/>单位px。 | 9131 9132 9133**示例:** 9134通过MeasureUtils的measureText方法获取"Hello World"文字的宽度。 9135 9136```ts 9137import { MeasureUtils } from '@kit.ArkUI'; 9138 9139@Entry 9140@Component 9141struct Index { 9142 @State uiContext: UIContext = this.getUIContext(); 9143 @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils(); 9144 @State textWidth: number = this.uiContextMeasure.measureText({ 9145 textContent: "Hello World", 9146 fontSize: '50px' 9147 }) 9148 9149 build() { 9150 Row() { 9151 Column() { 9152 Text(`The width of 'Hello World': ${this.textWidth}`) 9153 } 9154 .width('100%') 9155 } 9156 .height('100%') 9157 } 9158} 9159``` 9160 9161### measureTextSize<sup>12+</sup> 9162 9163measureTextSize(options: MeasureOptions): SizeOptions 9164 9165计算指定文本单行布局下的宽度和高度。 9166 9167**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 9168 9169**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9170 9171**参数:** 9172 9173| 参数名 | 类型 | 必填 | 说明 | 9174| ------- | ------------------------------- | ---- | --------- | 9175| options | [MeasureOptions](js-apis-measure.md#measureoptions) | 是 | 被计算文本描述信息。 | 9176 9177**返回值:** 9178 9179| 类型 | 说明 | 9180| ------------ | --------- | 9181| [SizeOption](arkui-ts/ts-types.md#sizeoptions) | 返回文本所占布局宽度和高度。<br/>**说明:**<br/> 文本宽度以及高度返回值单位均为px。 | 9182 9183 9184**示例:** 9185通过MeasureUtils的measureTextSize方法获取"Hello World"文字的宽度和高度 9186 9187```ts 9188import { MeasureUtils } from '@kit.ArkUI'; 9189 9190@Entry 9191@Component 9192struct Index { 9193 @State uiContext: UIContext = this.getUIContext(); 9194 @State uiContextMeasure: MeasureUtils = this.uiContext.getMeasureUtils(); 9195 textSize : SizeOptions = this.uiContextMeasure.measureTextSize({ 9196 textContent: "Hello World", 9197 fontSize: '50px' 9198 }) 9199 build() { 9200 Row() { 9201 Column() { 9202 Text(`The width of 'Hello World': ${this.textSize.width}`) 9203 Text(`The height of 'Hello World': ${this.textSize.height}`) 9204 } 9205 .width('100%') 9206 } 9207 .height('100%') 9208 } 9209} 9210``` 9211 9212## ComponentSnapshot<sup>12+</sup> 9213 9214以下API需先使用UIContext中的[getComponentSnapshot()](js-apis-arkui-UIContext.md#getcomponentsnapshot12)方法获取ComponentSnapshot对象,再通过此实例调用对应方法。 9215 9216缩放、平移、旋转等图形变换属性只对被截图组件的子组件生效;对目标组件本身应用图形变换属性不生效,显示的是还是图形变换前的效果。 9217 9218### get<sup>12+</sup> 9219 9220get(id: string, callback: AsyncCallback<image.PixelMap>, options?: componentSnapshot.SnapshotOptions): void 9221 9222获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过回调返回结果。 9223 9224> **说明:** 9225> 9226> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 9227 9228**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 9229 9230**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9231 9232**参数:** 9233 9234| 参数名 | 类型 | 必填 | 说明 | 9235| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 9236| id | string | 是 | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识)。 | 9237| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | 是 | 截图返回结果的回调。 | 9238| options<sup>12+</sup> | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 9239 9240**错误码:** 9241 9242以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 9243 9244| 错误码ID | 错误信息 | 9245| -------- | ------------------------------------------------------------ | 9246| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 9247| 100001 | Invalid ID. | 9248 9249**示例:** 9250 9251```ts 9252import { image } from '@kit.ImageKit'; 9253import { UIContext } from '@kit.ArkUI'; 9254 9255@Entry 9256@Component 9257struct SnapshotExample { 9258 @State pixmap: image.PixelMap | undefined = undefined 9259 uiContext: UIContext = this.getUIContext(); 9260 build() { 9261 Column() { 9262 Row() { 9263 Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5) 9264 Image($r('app.media.img')).autoResize(true).width(150).height(150).margin(5).id("root") 9265 } 9266 Button("click to generate UI snapshot") 9267 .onClick(() => { 9268 this.uiContext.getComponentSnapshot().get("root", (error: Error, pixmap: image.PixelMap) => { 9269 if (error) { 9270 console.error("error: " + JSON.stringify(error)) 9271 return; 9272 } 9273 this.pixmap = pixmap 9274 }, {scale : 2, waitUntilRenderFinished : true}) 9275 }).margin(10) 9276 } 9277 .width('100%') 9278 .height('100%') 9279 .alignItems(HorizontalAlign.Center) 9280 } 9281} 9282``` 9283 9284### get<sup>12+</sup> 9285 9286get(id: string, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap> 9287 9288获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。通过Promise返回结果。 9289 9290> **说明:** 9291> 9292> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 9293 9294**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 9295 9296**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9297 9298**参数:** 9299 9300| 参数名 | 类型 | 必填 | 说明 | 9301| ------ | ------ | ---- | ------------------------------------------------------------ | 9302| id | string | 是 | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识)。 | 9303| options<sup>12+</sup> | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 9304 9305**返回值:** 9306 9307| 类型 | 说明 | 9308| ------------------------------------------------------------ | ---------------- | 9309| Promise<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | 截图返回的结果。 | 9310 9311**错误码:** 9312 9313以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 9314 9315| 错误码ID | 错误信息 | 9316| -------- | ------------------------------------------------------------ | 9317| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 9318| 100001 | Invalid ID. | 9319 9320**示例:** 9321 9322```ts 9323import { image } from '@kit.ImageKit'; 9324import { UIContext } from '@kit.ArkUI'; 9325 9326@Entry 9327@Component 9328struct SnapshotExample { 9329 @State pixmap: image.PixelMap | undefined = undefined 9330 uiContext: UIContext = this.getUIContext(); 9331 9332 build() { 9333 Column() { 9334 Row() { 9335 Image(this.pixmap).width(150).height(150).border({ color: Color.Black, width: 2 }).margin(5) 9336 Image($r('app.media.icon')).autoResize(true).width(150).height(150).margin(5).id("root") 9337 } 9338 Button("click to generate UI snapshot") 9339 .onClick(() => { 9340 this.uiContext.getComponentSnapshot() 9341 .get("root", {scale : 2, waitUntilRenderFinished : true}) 9342 .then((pixmap: image.PixelMap) => { 9343 this.pixmap = pixmap 9344 }) 9345 .catch((err: Error) => { 9346 console.error("error: " + err) 9347 }) 9348 }).margin(10) 9349 } 9350 .width('100%') 9351 .height('100%') 9352 .alignItems(HorizontalAlign.Center) 9353 } 9354} 9355``` 9356 9357### createFromBuilder<sup>12+</sup> 9358 9359createFromBuilder(builder: CustomBuilder, callback: AsyncCallback<image.PixelMap>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): void 9360 9361在应用后台渲染[CustomBuilder](arkui-ts/ts-types.md#custombuilder8)自定义组件,并输出其截图。通过回调返回结果。 9362> **说明:** 9363> 9364> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。 9365> 9366> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/ts-basic-components-web.md)组件。 9367 9368**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 9369 9370**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9371 9372**参数:** 9373 9374| 参数名 | 类型 | 必填 | 说明 | 9375| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 9376| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | 是 | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。 | 9377| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | 是 | 截图返回结果的回调。支持在回调中获取离屏组件绘制区域坐标和大小。 | 9378| delay<sup>12+</sup> | number | 否 | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 默认值:300 <br/> 单位:毫秒 <br/> 取值范围:[0, +∞),小于0时按默认值处理。 | 9379| checkImageStatus<sup>12+</sup> | boolean | 否 | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false| 9380| options<sup>12+</sup> | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 9381 9382**错误码:** 9383 9384以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 9385 9386| 错误码ID | 错误信息 | 9387| -------- | ------------------------------------------------------------ | 9388| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 9389| 100001 | The builder is not a valid build function. | 9390| 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. | 9391 9392**示例:** 9393 9394```ts 9395import { image } from '@kit.ImageKit'; 9396import { UIContext } from '@kit.ArkUI'; 9397 9398@Entry 9399@Component 9400struct ComponentSnapshotExample { 9401 @State pixmap: image.PixelMap | undefined = undefined 9402 uiContext: UIContext = this.getUIContext(); 9403 @Builder 9404 RandomBuilder() { 9405 Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { 9406 Text('Test menu item 1') 9407 .fontSize(20) 9408 .width(100) 9409 .height(50) 9410 .textAlign(TextAlign.Center) 9411 Divider().height(10) 9412 Text('Test menu item 2') 9413 .fontSize(20) 9414 .width(100) 9415 .height(50) 9416 .textAlign(TextAlign.Center) 9417 } 9418 .width(100) 9419 .id("builder") 9420 } 9421 9422 build() { 9423 Column() { 9424 Button("click to generate UI snapshot") 9425 .onClick(() => { 9426 this.uiContext.getComponentSnapshot().createFromBuilder(() => { 9427 this.RandomBuilder() 9428 }, 9429 (error: Error, pixmap: image.PixelMap) => { 9430 if (error) { 9431 console.error("error: " + JSON.stringify(error)) 9432 return; 9433 } 9434 this.pixmap = pixmap 9435 }, 320, true, {scale : 2, waitUntilRenderFinished : true}) 9436 }) 9437 Image(this.pixmap) 9438 .margin(10) 9439 .height(200) 9440 .width(200) 9441 .border({ color: Color.Black, width: 2 }) 9442 }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300) 9443 } 9444} 9445``` 9446 9447### createFromBuilder<sup>12+</sup> 9448 9449createFromBuilder(builder: CustomBuilder, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap> 9450 9451在应用后台渲染[CustomBuilder](arkui-ts/ts-types.md#custombuilder8)自定义组件,并输出其截图。通过Promise返回结果。 9452 9453> **说明:** 9454> 9455> 由于需要等待组件构建、渲染成功,离屏截图的回调有500ms以内的延迟。 9456> 9457> 部分执行耗时任务的组件可能无法及时在截图前加载完成,因此会截取不到加载成功后的图像。例如:加载网络图片的[Image](arkui-ts/ts-basic-components-image.md)组件、[Web](../apis-arkweb/ts-basic-components-web.md)组件。 9458 9459**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 9460 9461**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9462 9463**参数:** 9464 9465| 参数名 | 类型 | 必填 | 说明 | 9466| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- | 9467| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) | 是 | 自定义组件构建函数。<br/>**说明:** 不支持全局builder。 | 9468| delay<sup>12+</sup> | number | 否 | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 默认值:300 <br/> 单位:毫秒| 9469| checkImageStatus<sup>12+</sup> | boolean | 否 | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false| 9470| options<sup>12+</sup> | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 9471 9472**返回值:** 9473 9474| 类型 | 说明 | 9475| ------------------------------------------------------------ | ---------------- | 9476| Promise<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | 截图返回的结果。 | 9477 9478**错误码:** 9479 9480以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 9481 9482| 错误码ID | 错误信息 | 9483| -------- | ------------------------------------------------------------ | 9484| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 9485| 100001 | The builder is not a valid build function. | 9486| 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. | 9487 9488**示例:** 9489 9490```ts 9491import { image } from '@kit.ImageKit'; 9492import { UIContext } from '@kit.ArkUI'; 9493 9494@Entry 9495@Component 9496struct ComponentSnapshotExample { 9497 @State pixmap: image.PixelMap | undefined = undefined 9498 uiContext: UIContext = this.getUIContext(); 9499 @Builder 9500 RandomBuilder() { 9501 Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) { 9502 Text('Test menu item 1') 9503 .fontSize(20) 9504 .width(100) 9505 .height(50) 9506 .textAlign(TextAlign.Center) 9507 Divider().height(10) 9508 Text('Test menu item 2') 9509 .fontSize(20) 9510 .width(100) 9511 .height(50) 9512 .textAlign(TextAlign.Center) 9513 } 9514 .width(100) 9515 .id("builder") 9516 } 9517 build() { 9518 Column() { 9519 Button("click to generate UI snapshot") 9520 .onClick(() => { 9521 this.uiContext.getComponentSnapshot() 9522 .createFromBuilder(() => { 9523 this.RandomBuilder() 9524 }, 320, true, {scale : 2, waitUntilRenderFinished : true}) 9525 .then((pixmap: image.PixelMap) => { 9526 this.pixmap = pixmap 9527 }) 9528 .catch((err: Error) => { 9529 console.error("error: " + err) 9530 }) 9531 }) 9532 Image(this.pixmap) 9533 .margin(10) 9534 .height(200) 9535 .width(200) 9536 .border({ color: Color.Black, width: 2 }) 9537 }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300) 9538 } 9539} 9540``` 9541 9542### getSync<sup>12+</sup> 9543 9544getSync(id: string, options?: componentSnapshot.SnapshotOptions): image.PixelMap 9545 9546获取已加载的组件的截图,传入组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识),找到对应组件进行截图。同步等待截图完成返回[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)。 9547 9548> **说明:** 9549> 9550> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 9551 9552**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 9553 9554**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9555 9556**参数:** 9557 9558| 参数名 | 类型 | 必填 | 说明 | 9559| ---- | ------ | ---- | ---------------------------------------- | 9560| id | string | 是 | 目标组件的[组件标识](arkui-ts/ts-universal-attributes-component-id.md#组件标识)。 | 9561| options | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 9562 9563**返回值:** 9564 9565| 类型 | 说明 | 9566| ----------------------------- | -------- | 9567| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | 截图返回的结果。 | 9568 9569**错误码:** 9570 9571以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 9572 9573| 错误码ID | 错误信息 | 9574| ------ | ------------------- | 9575| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 9576| 100001 | Invalid ID. | 9577| 160002 | Timeout. | 9578 9579**示例:** 9580 9581```ts 9582import { image } from '@kit.ImageKit'; 9583import { UIContext } from '@kit.ArkUI'; 9584 9585@Entry 9586@Component 9587struct SnapshotExample { 9588 @State pixmap: image.PixelMap | undefined = undefined 9589 9590 build() { 9591 Column() { 9592 Row() { 9593 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 9594 Image($r('app.media.img')).autoResize(true).width(200).height(200).margin(5).id("root") 9595 } 9596 Button("click to generate UI snapshot") 9597 .onClick(() => { 9598 try { 9599 let pixelmap = this.getUIContext().getComponentSnapshot().getSync("root", {scale : 2, waitUntilRenderFinished : true}) 9600 this.pixmap = pixelmap 9601 } catch (error) { 9602 console.error("getSync errorCode: " + error.code + " message: " + error.message) 9603 } 9604 }).margin(10) 9605 } 9606 .width('100%') 9607 .height('100%') 9608 .alignItems(HorizontalAlign.Center) 9609 } 9610} 9611``` 9612 9613### getWithUniqueId<sup>15+</sup> 9614 9615getWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap> 9616 9617获取已加载的组件的截图,传入组件的[uniqueId](js-apis-arkui-frameNode.md#getuniqueid12),找到对应组件进行截图。通过Promise返回结果。 9618 9619> **说明:** 9620> 9621> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 9622 9623**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 9624 9625**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9626 9627**参数:** 9628 9629| 参数名 | 类型 | 必填 | 说明 | 9630| ---- | ------ | ---- | ---------------------------------------- | 9631| uniqueId | number | 是 | 目标组件的[uniqueId](js-apis-arkui-frameNode.md#getuniqueid12) | 9632| options | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 9633 9634**返回值:** 9635 9636| 类型 | 说明 | 9637| ------------------------------------------------------------ | ---------------- | 9638| Promise<image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)> | 截图返回的结果。 | 9639 9640**错误码:** 9641 9642以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 9643 9644| 错误码ID | 错误信息 | 9645| -------- | ------------------------------------------------------------ | 9646| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 9647| 100001 | Invalid ID. | 9648 9649**示例:** 9650 9651```ts 9652import { NodeController, FrameNode, typeNode } from '@kit.ArkUI'; 9653import { image } from '@kit.ImageKit'; 9654import { UIContext } from '@kit.ArkUI'; 9655 9656class MyNodeController extends NodeController { 9657 public node: FrameNode | null = null; 9658 9659 public imageNode: FrameNode | null = null; 9660 9661 makeNode(uiContext: UIContext): FrameNode | null { 9662 this.node = new FrameNode(uiContext); 9663 this.node.commonAttribute.width('100%').height('100%') 9664 9665 let image = typeNode.createNode(uiContext, 'Image'); 9666 image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true) 9667 this.imageNode = image; 9668 9669 this.node.appendChild(image); 9670 return this.node; 9671 } 9672} 9673 9674@Entry 9675@Component 9676struct SnapshotExample { 9677 private myNodeController: MyNodeController = new MyNodeController(); 9678 9679 @State pixmap: image.PixelMap | undefined = undefined 9680 9681 build() { 9682 Column() { 9683 Row() { 9684 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 9685 NodeContainer(this.myNodeController).width(200).height(200).margin(5) 9686 } 9687 Button("UniqueId get snapshot") 9688 .onClick(() => { 9689 try { 9690 this.getUIContext() 9691 .getComponentSnapshot() 9692 .getWithUniqueId(this.myNodeController.imageNode?.getUniqueId(), {scale: 2, waitUntilRenderFinished: true}) 9693 .then((pixmap: image.PixelMap) => { 9694 this.pixmap = pixmap 9695 }) 9696 .catch((err: Error) => { 9697 console.log("error: " + err) 9698 }) 9699 } catch (error) { 9700 console.error("UniqueId get snapshot Error: " + JSON.stringify(error)) 9701 } 9702 }).margin(10) 9703 } 9704 .width('100%') 9705 .height('100%') 9706 .alignItems(HorizontalAlign.Center) 9707 } 9708} 9709``` 9710 9711### getSyncWithUniqueId<sup>15+</sup> 9712 9713getSyncWithUniqueId(uniqueId: number, options?: componentSnapshot.SnapshotOptions): image.PixelMap 9714 9715获取已加载的组件的截图,传入组件的[uniqueId](js-apis-arkui-frameNode.md#getuniqueid12),找到对应组件进行截图。同步等待截图完成返回[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7)。 9716 9717> **说明:** 9718> 9719> 截图会获取最近一帧的绘制内容。如果在组件触发更新的同时调用截图,更新的渲染内容不会被截取到,截图会返回上一帧的绘制内容。 9720 9721**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 9722 9723**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9724 9725**参数:** 9726 9727| 参数名 | 类型 | 必填 | 说明 | 9728| ---- | ------ | ---- | ---------------------------------------- | 9729| uniqueId | number | 是 | 目标组件的[uniqueId](js-apis-arkui-frameNode.md#getuniqueid12)。 | 9730| options | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。 | 9731 9732**返回值:** 9733 9734| 类型 | 说明 | 9735| ----------------------------- | -------- | 9736| image.[PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | 截图返回的结果。 | 9737 9738**错误码:** 9739 9740以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。 9741 9742| 错误码ID | 错误信息 | 9743| ------ | ------------------- | 9744| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 9745| 100001 | Invalid ID. | 9746| 160002 | Timeout. | 9747 9748**示例:** 9749 9750```ts 9751import { NodeController, FrameNode, typeNode } from '@kit.ArkUI'; 9752import { image } from '@kit.ImageKit'; 9753import { UIContext } from '@kit.ArkUI'; 9754 9755class MyNodeController extends NodeController { 9756 public node: FrameNode | null = null; 9757 9758 public imageNode: FrameNode | null = null; 9759 9760 makeNode(uiContext: UIContext): FrameNode | null { 9761 this.node = new FrameNode(uiContext); 9762 this.node.commonAttribute.width('100%').height('100%') 9763 9764 let image = typeNode.createNode(uiContext, 'Image'); 9765 image.initialize($r('app.media.img')).width('100%').height('100%').autoResize(true) 9766 this.imageNode = image; 9767 9768 this.node.appendChild(image); 9769 return this.node; 9770 } 9771} 9772 9773@Entry 9774@Component 9775struct SnapshotExample { 9776 private myNodeController: MyNodeController = new MyNodeController(); 9777 9778 @State pixmap: image.PixelMap | undefined = undefined 9779 9780 build() { 9781 Column() { 9782 Row() { 9783 Image(this.pixmap).width(200).height(200).border({ color: Color.Black, width: 2 }).margin(5) 9784 NodeContainer(this.myNodeController).width(200).height(200).margin(5) 9785 } 9786 Button("UniqueId getSync snapshot") 9787 .onClick(() => { 9788 try { 9789 this.pixmap = this.getUIContext() 9790 .getComponentSnapshot() 9791 .getSyncWithUniqueId(this.myNodeController.imageNode?.getUniqueId(), {scale: 2, waitUntilRenderFinished: true}) 9792 } catch (error) { 9793 console.error("UniqueId getSync snapshot Error: " + JSON.stringify(error)) 9794 } 9795 }).margin(10) 9796 } 9797 .width('100%') 9798 .height('100%') 9799 .alignItems(HorizontalAlign.Center) 9800 } 9801} 9802``` 9803 9804### createFromComponent<sup>18+</sup> 9805 9806createFromComponent\<T extends Object>(content: ComponentContent\<T>, delay?: number, checkImageStatus?: boolean, options?: componentSnapshot.SnapshotOptions): Promise<image.PixelMap> 9807 9808将传入的content对象进行截图,并通过Promise返回结果。 9809 9810**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 9811 9812**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9813 9814**参数:** 9815 9816| 参数名 | 类型 | 必填 | 说明 | 9817| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 9818| content | [ComponentContent\<T>](./js-apis-arkui-ComponentContent.md) | 是 | 当前UIContext显示的组件内容。 | 9819| delay | number | 否 | 指定触发截图指令的延迟时间。当布局中使用了图片组件时,需要指定延迟时间,以便系统解码图片资源。资源越大,解码需要的时间越长,建议尽量使用不需要解码的PixelMap资源。<br/> 当使用PixelMap资源或对Image组件设置syncload为true时,可以配置delay为0,强制不等待触发截图。该延迟时间并非指接口从调用到返回的时间,由于系统需要对传入的builder进行临时离屏构建,因此返回的时间通常要比该延迟时间长。<br/>**说明:** 截图接口传入的builder中,不应使用状态变量控制子组件的构建,如果必须要使用,在调用截图接口时,也不应再有变化,以避免出现截图不符合预期的情况。<br/> 取值范围:[0,+∞) ,小于0时按默认值处理。<br/>默认值:300 <br/> 单位:毫秒| 9820| checkImageStatus | boolean | 否 | 指定是否允许在截图之前,校验图片解码状态。如果为true,则会在截图之前检查所有Image组件是否已经解码完成,如果没有完成检查,则会放弃截图并返回异常。<br/>默认值:false| 9821| options | [componentSnapshot.SnapshotOptions](js-apis-arkui-componentSnapshot.md#snapshotoptions12) | 否 | 截图相关的自定义参数。可以指定截图时图形侧绘制pixelmap的缩放比例与是否强制等待系统执行截图指令前所有绘制指令都执行完成之后再截图。 | 9822 9823**错误码:** 9824 9825以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码和[截图错误码](errorcode-snapshot.md)。 9826 9827| 错误码ID | 错误信息 | 9828| -------- | ------------------------------------------------------------ | 9829| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. | 9830| 100001 | The builder is not a valid build function. | 9831| 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. | 9832 9833**示例:** 9834 9835```ts 9836import { image } from '@kit.ImageKit'; 9837import { ComponentContent } from '@kit.ArkUI'; 9838 9839class Params { 9840 text: string | undefined | null = ""; 9841 9842 constructor(text: string | undefined | null ) { 9843 this.text = text; 9844 } 9845} 9846 9847@Builder 9848function buildText(params: Params) { 9849 ReusableChildComponent({ text: params.text }); 9850} 9851 9852@Component 9853struct ReusableChildComponent { 9854 @Prop text: string | undefined | null = ""; 9855 9856 aboutToReuse(params: Record<string, object>) { 9857 console.log("ReusableChildComponent Reusable " + JSON.stringify(params)); 9858 } 9859 9860 aboutToRecycle(): void { 9861 console.log("ReusableChildComponent aboutToRecycle " + this.text); 9862 } 9863 9864 build() { 9865 Column() { 9866 Text(this.text) 9867 .fontSize(90) 9868 .fontWeight(FontWeight.Bold) 9869 .margin({ bottom: 36 }) 9870 .width('100%') 9871 .height('100%') 9872 }.backgroundColor('#FFF0F0F0') 9873 } 9874} 9875 9876@Entry 9877@Component 9878struct Index { 9879 @State pixmap: image.PixelMap | undefined = undefined 9880 @State message: string | undefined | null = "hello" 9881 uiContext: UIContext = this.getUIContext(); 9882 9883 build() { 9884 Row() { 9885 Column() { 9886 Button("点击生成组件截图") 9887 .onClick(() => { 9888 let uiContext = this.getUIContext(); 9889 let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message)); 9890 this.uiContext.getComponentSnapshot() 9891 .createFromComponent(contentNode 9892 , 320, true, {scale : 2, waitUntilRenderFinished : true}) 9893 .then((pixmap: image.PixelMap) => { 9894 this.pixmap = pixmap 9895 }) 9896 .catch((err: Error) => { 9897 console.error("error: " + err) 9898 }) 9899 }) 9900 Image(this.pixmap) 9901 .margin(10) 9902 .height(200) 9903 .width(200) 9904 .border({ color: Color.Black, width: 2 }) 9905 }.width('100%').margin({ left: 10, top: 5, bottom: 5 }).height(300) 9906 } 9907 .width('100%') 9908 .height('100%') 9909 } 9910} 9911``` 9912 9913## FrameCallback<sup>12+</sup> 9914 9915用于设置下一帧渲染时需要执行的任务。需要配合[UIContext](#uicontext)中的[postFrameCallback](#postframecallback12)和[postDelayedFrameCallback](#postdelayedframecallback12)使用。开发者需要继承该类并重写[onFrame](#onframe12)或[onIdle](#onidle12)方法,实现具体的业务逻辑。 9916 9917### onFrame<sup>12+</sup> 9918 9919onFrame(frameTimeInNano: number): void 9920 9921在下一帧进行渲染时,该方法将被执行。 9922 9923**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 9924 9925**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9926 9927**参数:** 9928 9929| 参数名 | 类型 | 必填 | 说明 | 9930| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- | 9931| frameTimeInNano | number | 是 | 下一帧渲染开始执行的时间,以纳秒为单位。<br/>取值范围:[0, +∞) | 9932 9933**示例:** 9934 9935```ts 9936import {FrameCallback } from '@kit.ArkUI'; 9937 9938class MyFrameCallback extends FrameCallback { 9939 private tag: string; 9940 9941 constructor(tag: string) { 9942 super() 9943 this.tag = tag; 9944 } 9945 9946 onFrame(frameTimeNanos: number) { 9947 console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString()); 9948 } 9949} 9950 9951@Entry 9952@Component 9953struct Index { 9954 build() { 9955 Row() { 9956 Column() { 9957 Button('点击触发postFrameCallback') 9958 .onClick(() => { 9959 this.getUIContext().postFrameCallback(new MyFrameCallback("normTask")); 9960 }) 9961 Button('点击触发postDelayedFrameCallback') 9962 .onClick(() => { 9963 this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5); 9964 }) 9965 } 9966 .width('100%') 9967 } 9968 .height('100%') 9969 } 9970} 9971``` 9972 9973### onIdle<sup>12+</sup> 9974 9975onIdle(timeLeftInNano: number): void 9976 9977在下一帧渲染结束时,如果距离下一个Vsync信号到来还有1ms以上的剩余时间,该方法将被执行,否则将顺延至后面的帧。 9978 9979**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 9980 9981**系统能力:** SystemCapability.ArkUI.ArkUI.Full 9982 9983**参数:** 9984 9985| 参数名 | 类型 | 必填 | 说明 | 9986| ------- | ---------------------------------------------------- | ---- | ------------------------------------------------------- | 9987| timeLeftInNano | number | 是 | 这一帧剩余的空闲时间,以纳秒为单位。<br/>取值范围:[0, +∞) | 9988 9989**示例:** 9990 9991```ts 9992import { FrameCallback } from '@ohos.arkui.UIContext'; 9993 9994class MyIdleCallback extends FrameCallback { 9995 private tag: string; 9996 9997 constructor(tag: string) { 9998 super() 9999 this.tag = tag; 10000 } 10001 10002 onIdle(timeLeftInNano: number) { 10003 console.info('MyIdleCallback ' + this.tag + ' ' + timeLeftInNano.toString()); 10004 } 10005} 10006 10007@Entry 10008@Component 10009struct Index { 10010 build() { 10011 Row() { 10012 Column() { 10013 Button('点击触发postFrameCallback') 10014 .onClick(() => { 10015 this.getUIContext().postFrameCallback(new MyIdleCallback("normTask")); 10016 }) 10017 Button('点击触发postDelayedFrameCallback') 10018 .onClick(() => { 10019 this.getUIContext().postDelayedFrameCallback(new MyIdleCallback("delayTask"), 5); 10020 }) 10021 } 10022 .width('100%') 10023 } 10024 .height('100%') 10025 } 10026} 10027``` 10028 10029## DynamicSyncScene<sup>12+</sup> 10030 10031以下接口需先使用UIContext中的requireDynamicSyncScene()方法获取DynamicSyncScene对象,再通过此实例调用对应方法。 10032 10033### setFrameRateRange<sup>12+</sup> 10034 10035setFrameRateRange(range: ExpectedFrameRateRange): void 10036 10037设置期望帧率范围。 10038 10039最终结果不一定是设置的帧率,会由系统能力做综合决策,尽量满足开发者的设置帧率。 10040 10041**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 10042 10043**系统能力:** SystemCapability.ArkUI.ArkUI.Full 10044 10045**参数:** 10046 10047| 参数名 | 类型 | 必填 | 说明 | 10048| -------- | ---------- | ---- | ---- | 10049| range | [ExpectedFrameRateRange](../apis-arkui/arkui-ts/ts-explicit-animation.md#expectedframeraterange11)| 是 | 设置期望的帧率范围。<br />默认值:{min:0, max:120, expected: 120} | 10050 10051**示例:** 10052 10053```ts 10054import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI' 10055 10056@Entry 10057@Component 10058struct Frame { 10059 @State ANIMATION:ExpectedFrameRateRange = {min:0, max:120, expected: 90} 10060 @State GESTURE:ExpectedFrameRateRange = {min:0, max:120, expected: 30} 10061 private scenes: SwiperDynamicSyncScene[] = [] 10062 10063 build() { 10064 Column() { 10065 Text("动画"+ JSON.stringify(this.ANIMATION)) 10066 Text("跟手"+ JSON.stringify(this.GESTURE)) 10067 Row(){ 10068 Swiper() { 10069 Text("one") 10070 Text("two") 10071 Text("three") 10072 } 10073 .width('100%') 10074 .height('300vp') 10075 .id("dynamicSwiper") 10076 .backgroundColor(Color.Blue) 10077 .autoPlay(true) 10078 .onAppear(()=>{ 10079 this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[] 10080 }) 10081 } 10082 10083 Button("set frame") 10084 .onClick(()=>{ 10085 this.scenes.forEach((scenes: SwiperDynamicSyncScene) => { 10086 10087 if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) { 10088 scenes.setFrameRateRange(this.ANIMATION) 10089 } 10090 10091 if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) { 10092 scenes.setFrameRateRange(this.GESTURE) 10093 } 10094 }); 10095 }) 10096 } 10097 } 10098} 10099``` 10100 10101### getFrameRateRange<sup>12+</sup> 10102 10103getFrameRateRange(): ExpectedFrameRateRange 10104 10105获取期望帧率范围。 10106 10107**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 10108 10109**系统能力:** SystemCapability.ArkUI.ArkUI.Full 10110 10111**返回值:** 10112 10113| 类型 | 说明 | 10114| ------------------- | ------- | 10115| [ExpectedFrameRateRange](../apis-arkui/arkui-ts/ts-explicit-animation.md#expectedframeraterange11) | 期望帧率范围。| 10116 10117**示例:** 10118 10119```ts 10120import { SwiperDynamicSyncSceneType, SwiperDynamicSyncScene } from '@kit.ArkUI' 10121 10122@Entry 10123@Component 10124struct Frame { 10125 @State ANIMATION:ExpectedFrameRateRange = {min:0, max:120, expected: 90} 10126 @State GESTURE:ExpectedFrameRateRange = {min:0, max:120, expected: 30} 10127 private scenes: SwiperDynamicSyncScene[] = [] 10128 10129 build() { 10130 Column() { 10131 Text("动画"+ JSON.stringify(this.ANIMATION)) 10132 Text("跟手"+ JSON.stringify(this.GESTURE)) 10133 Row(){ 10134 Swiper() { 10135 Text("one") 10136 Text("two") 10137 Text("three") 10138 } 10139 .width('100%') 10140 .height('300vp') 10141 .id("dynamicSwiper") 10142 .backgroundColor(Color.Blue) 10143 .autoPlay(true) 10144 .onAppear(()=>{ 10145 this.scenes = this.getUIContext().requireDynamicSyncScene("dynamicSwiper") as SwiperDynamicSyncScene[] 10146 }) 10147 } 10148 10149 Button("set frame") 10150 .onClick(()=>{ 10151 this.scenes.forEach((scenes: SwiperDynamicSyncScene) => { 10152 10153 if (scenes.type == SwiperDynamicSyncSceneType.ANIMATION) { 10154 scenes.setFrameRateRange(this.ANIMATION) 10155 scenes.getFrameRateRange() 10156 } 10157 10158 if (scenes.type == SwiperDynamicSyncSceneType.GESTURE) { 10159 scenes.setFrameRateRange(this.GESTURE) 10160 scenes.getFrameRateRange() 10161 } 10162 }); 10163 }) 10164 } 10165 } 10166} 10167``` 10168## SwiperDynamicSyncScene<sup>12+</sup> 10169 10170SwiperDynamicSyncScene继承自[DynamicSyncScene](#dynamicsyncscene12),对应Swiper的动态帧率场景。 10171 10172**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 10173 10174**系统能力:** SystemCapability.ArkUI.ArkUI.Full 10175 10176| 名称 | 类型 | 只读 | 可选 | 说明 | 10177| --------- | --------------------------------------------------------- | ---- | ---- | ---------------------------------- | 10178| type | [SwiperDynamicSyncSceneType](#swiperdynamicsyncscenetype12) | 是 | 否 | Swiper的动态帧率场景。 | 10179 10180## SwiperDynamicSyncSceneType<sup>12+</sup> 10181 10182枚举值,表示动态帧率场景的类型。 10183 10184**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 10185 10186**系统能力:** SystemCapability.ArkUI.ArkUI.Full 10187 10188| 名称 | 值 | 说明 | 10189| -------- | ---- | ---------------------- | 10190| GESTURE | 0 | 手势操作场景 | 10191| ANIMATION | 1 | 动画过度场景 | 10192 10193## MarqueeDynamicSyncScene<sup>14+</sup> 10194 10195MarqueeDynamicSyncScene继承自[DynamicSyncScene](#dynamicsyncscene12),对应[Marquee](arkui-ts/ts-basic-components-marquee.md)的动态帧率场景。 10196 10197**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。 10198 10199**系统能力:** SystemCapability.ArkUI.ArkUI.Full 10200 10201| 名称 | 类型 | 只读 | 可选 | 说明 | 10202| --------- | --------------------------------------------------------- | ---- | ---- | ---------------------------------- | 10203| type | [MarqueeDynamicSyncSceneType](#marqueedynamicsyncscenetype14) | 是 | 否 | Marquee的动态帧率场景。 | 10204 10205## MarqueeDynamicSyncSceneType<sup>14+</sup> 10206 10207枚举值,表示Marquee的动态帧率场景的类型。 10208 10209**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。 10210 10211**系统能力:** SystemCapability.ArkUI.ArkUI.Full 10212 10213| 名称 | 值 | 说明 | 10214| -------- | ---- | ---------------------- | 10215| ANIMATION | 1 | 动画过度场景 | 10216 10217**示例:** 10218 10219```ts 10220import { MarqueeDynamicSyncSceneType, MarqueeDynamicSyncScene } from '@kit.ArkUI'; 10221 10222@Entry 10223@Component 10224struct MarqueeExample { 10225 @State start: boolean = false 10226 @State src: string = '' 10227 @State marqueeText: string = 'Running Marquee' 10228 private fromStart: boolean = true 10229 private step: number = 10 10230 private loop: number = Number.POSITIVE_INFINITY 10231 controller: TextClockController = new TextClockController() 10232 convert2time(value: number): string{ 10233 let date = new Date(Number(value+'000')); 10234 let hours = date.getHours().toString().padStart(2, '0'); 10235 let minutes = date.getMinutes().toString().padStart(2, '0'); 10236 let seconds = date.getSeconds().toString().padStart(2, '0'); 10237 return hours+ ":" + minutes + ":" + seconds; 10238 } 10239 @State ANIMATION: ExpectedFrameRateRange = {min:0, max:120, expected:30} 10240 private scenes: MarqueeDynamicSyncScene[] = [] 10241 10242 build() { 10243 Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { 10244 Marquee({ 10245 start: this.start, 10246 step: this.step, 10247 loop: this.loop, 10248 fromStart: this.fromStart, 10249 src: this.marqueeText + this.src 10250 }) 10251 .marqueeUpdateStrategy(MarqueeUpdateStrategy.PRESERVE_POSITION) 10252 .width(300) 10253 .height(80) 10254 .fontColor('#FFFFFF') 10255 .fontSize(48) 10256 .fontWeight(700) 10257 .backgroundColor('#182431') 10258 .margin({ bottom: 40 }) 10259 .id('dynamicMarquee') 10260 .onAppear(()=>{ 10261 this.scenes = this.getUIContext().requireDynamicSyncScene('dynamicMarquee') as MarqueeDynamicSyncScene[] 10262 }) 10263 Button('Start') 10264 .onClick(() => { 10265 this.start = true 10266 this.controller.start() 10267 this.scenes.forEach((scenes: MarqueeDynamicSyncScene) => { 10268 if (scenes.type == MarqueeDynamicSyncSceneType.ANIMATION) { 10269 scenes.setFrameRateRange(this.ANIMATION) 10270 } 10271 }); 10272 }) 10273 .width(120) 10274 .height(40) 10275 .fontSize(16) 10276 .fontWeight(500) 10277 .backgroundColor('#007DFF') 10278 TextClock({ timeZoneOffset: -8, controller: this.controller }) 10279 .format('hms') 10280 .onDateChange((value: number) => { 10281 this.src = this.convert2time(value); 10282 }) 10283 .margin(20) 10284 .fontSize(30) 10285 } 10286 .width('100%') 10287 .height('100%') 10288 } 10289} 10290``` 10291## TextMenuController<sup>16+</sup> 10292以下API需先使用UIContext中的[getTextMenuController()](js-apis-arkui-UIContext.md#gettextmenucontroller16)方法获取TextMenuController实例,再通过此实例调用对应方法。 10293 10294### setMenuOptions<sup>16+</sup> 10295 10296setMenuOptions(options: TextMenuOptions): void 10297 10298设置菜单选项。 10299 10300**原子化服务API:** 从API version 16开始,该接口支持在原子化服务中使用。 10301 10302**系统能力:** SystemCapability.ArkUI.ArkUI.Full 10303 10304**参数:** 10305 10306| 参数名 | 类型 | 必填 | 说明 | 10307| -------- | ---------- | ---- | ---- | 10308| options | [TextMenuOptions](../apis-arkui/arkui-ts/ts-text-common.md#textmenuoptions16对象说明)| 是 | 设置菜单选项。<br />默认值:{showMode: TextMenuShowMode.DEFAULT} | 10309 10310**示例:** 10311 10312```ts 10313// xxx.ets 10314@Entry 10315@Component 10316struct Index { 10317 aboutToAppear(): void { 10318 // 设置在对应的UIContext下优先使用独立窗口显示文本选择菜单 10319 this.getUIContext() 10320 .getTextMenuController() 10321 .setMenuOptions( 10322 { 10323 showMode: TextMenuShowMode.PREFER_WINDOW 10324 } 10325 ) 10326 } 10327 10328 build() { 10329 Row() { 10330 Column() { 10331 TextInput({ text: "这是一个TextInput,长按弹出文本选择菜单" }) 10332 .height(60) 10333 .fontStyle(FontStyle.Italic) 10334 .fontWeight(FontWeight.Bold) 10335 .textAlign(TextAlign.Center) 10336 .caretStyle({ width: '4vp' }) 10337 10338 Text("这是一个Text,长按弹出文本选择菜单") 10339 .height(60) 10340 .copyOption(CopyOptions.InApp) 10341 .fontStyle(FontStyle.Italic) 10342 .fontWeight(FontWeight.Bold) 10343 .textAlign(TextAlign.Center) 10344 }.width('100%') 10345 } 10346 .height('100%') 10347 } 10348} 10349``` 10350## setPixelRoundMode<sup>18+</sup> 10351 10352setPixelRoundMode(mode: PixelRoundMode): void 10353 10354配置当前页面的像素取整模式。 10355 10356**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 10357 10358**系统能力:** SystemCapability.ArkUI.ArkUI.Full 10359 10360**参数:** 10361 10362| 参数名 | 类型 | 必填 | 说明 | 10363| -------- | ---------- | ---- | ---- | 10364| mode | [PixelRoundMode](./arkui-ts/ts-appendix-enums.md#pixelroundmode18)| 是 | 像素取整模式。<br />默认值:PixelRoundMode.PIXEL_ROUND_ON_LAYOUT_FINISH | 10365 10366**示例:** 10367 10368```ts 10369// EntryAbility.ets 10370import { UIContext } from '@kit.ArkUI'; 10371import { hilog } from '@kit.PerformanceAnalysisKit'; 10372 10373onWindowStageCreate(windowStage: window.WindowStage) { 10374 // Main window is created, set main page for this ability 10375 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 10376 10377 windowStage.loadContent('pages/Index', (err, data) => { 10378 let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext(); 10379 uiContext.setPixelRoundMode(PixelRoundMode.PIXEL_ROUND_ON_LAYOUT_FINISH); 10380 if (err.code) { 10381 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 10382 return; 10383 } 10384 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 10385 }); 10386 } 10387``` 10388 10389## getPixelRoundMode<sup>18+</sup> 10390 10391getPixelRoundMode(): PixelRoundMode 10392 10393获取当前页面的像素取整模式。 10394 10395**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 10396 10397**系统能力:** SystemCapability.ArkUI.ArkUI.Full 10398 10399**返回值:** 10400 10401| 类型 | 说明 | 10402| ---------- | ---- | 10403| [PixelRoundMode](./arkui-ts/ts-appendix-enums.md#pixelroundmode18)| 当前页面的像素取整模式。| 10404 10405**示例:** 10406 10407```ts 10408// EntryAbility.ets 10409import { UIContext } from '@kit.ArkUI'; 10410import { hilog } from '@kit.PerformanceAnalysisKit'; 10411 10412onWindowStageCreate(windowStage: window.WindowStage) { 10413 // Main window is created, set main page for this ability 10414 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 10415 10416 windowStage.loadContent('pages/Index', (err, data) => { 10417 let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext(); 10418 console.info("pixelRoundMode : " + uiContext.getPixelRoundMode().valueOf()); 10419 if (err.code) { 10420 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 10421 return; 10422 } 10423 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 10424 }); 10425 }