1# @ohos.arkui.UIContext (UIContext) 2 3在Stage模型中,WindowStage/Window可以通过[loadContent](js-apis-window.md#loadcontent9)接口加载页面并创建UI的实例,并将页面内容渲染到关联的窗口中,所以UI实例和窗口是一一关联的。一些全局的UI接口是和具体UI实例的执行上下文相关的,在当前接口调用时,通过追溯调用链跟踪到UI的上下文,来确定具体的UI实例。若在非UI页面中或者一些异步回调中调用这类接口,可能无法跟踪到当前UI的上下文,导致接口执行失败。 4 5@ohos.window在API version 10 新增[getUIContext](js-apis-window.md#getuicontext10)接口,获取UI上下文实例UIContext对象,使用UIContext对象提供的替代方法,可以直接作用在对应的UI实例上。 6 7> **说明:** 8> 9> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 10> 11> 示例效果请以真机运行为准,当前IDE预览器不支持。 12 13## UIContext 14 15以下API需先使用ohos.window中的[getUIContext()](js-apis-window.md#getuicontext10)方法获取UIContext实例,再通过此实例调用对应方法。或者可以通过自定义组件内置方法[getUIContext()](arkui-ts/ts-custom-component-api.md#getuicontext)获取。本文中UIContext对象以uiContext表示。 16 17### getFont 18 19getFont(): Font 20 21获取Font对象。 22 23**系统能力:** SystemCapability.ArkUI.ArkUI.Full 24 25**返回值:** 26 27| 类型 | 说明 | 28| ------------- | ----------- | 29| [Font](#font) | 返回Font实例对象。 | 30 31**示例:** 32 33```ts 34uiContext.getFont(); 35``` 36### getComponentUtils 37 38getComponentUtils(): ComponentUtils 39 40获取ComponentUtils对象。 41 42**系统能力:** SystemCapability.ArkUI.ArkUI.Full 43 44**返回值:** 45 46| 类型 | 说明 | 47| --------------------------------- | --------------------- | 48| [ComponentUtils](#componentutils) | 返回ComponentUtils实例对象。 | 49 50**示例:** 51 52```ts 53uiContext.getComponentUtils(); 54``` 55 56### getUIInspector 57 58getUIInspector(): UIInspector 59 60获取UIInspector对象。 61 62**系统能力:** SystemCapability.ArkUI.ArkUI.Full 63 64**返回值:** 65 66| 类型 | 说明 | 67| --------------------------- | ------------------ | 68| [UIInspector](#uiinspector) | 返回UIInspector实例对象。 | 69 70**示例:** 71 72```ts 73uiContext.getUIInspector(); 74``` 75 76### getUIObserver<sup>11+</sup> 77 78getUIObserver(): UIObserver 79 80获取UIObserver对象。 81 82**系统能力:** SystemCapability.ArkUI.ArkUI.Full 83 84**返回值:** 85 86| 类型 | 说明 | 87| --------------------------- | ------------------ | 88| [UIObserver](#uiobserver11) | 返回UIObserver实例对象。 | 89 90**示例:** 91 92```ts 93uiContext.getUIObserver(); 94``` 95 96### getMediaQuery 97 98getMediaQuery(): MediaQuery 99 100获取MediaQuery对象。 101 102**系统能力:** SystemCapability.ArkUI.ArkUI.Full 103 104**返回值:** 105 106| 类型 | 说明 | 107| ------------------------- | ----------------- | 108| [MediaQuery](#mediaquery) | 返回MediaQuery实例对象。 | 109 110**示例:** 111 112```ts 113uiContext.getMediaQuery(); 114``` 115 116### getRouter 117 118getRouter(): Router 119 120获取Router对象。 121 122**系统能力:** SystemCapability.ArkUI.ArkUI.Full 123 124**返回值:** 125 126| 类型 | 说明 | 127| ----------------- | ------------- | 128| [Router](#router) | 返回Router实例对象。 | 129 130**示例:** 131 132```ts 133uiContext.getRouter(); 134``` 135 136### getPromptAction 137 138getPromptAction(): PromptAction 139 140获取PromptAction对象。 141 142**系统能力:** SystemCapability.ArkUI.ArkUI.Full 143 144**返回值:** 145 146| 类型 | 说明 | 147| ----------------------------- | ------------------- | 148| [PromptAction](#promptaction) | 返回PromptAction实例对象。 | 149 150**示例:** 151 152```ts 153uiContext.getPromptAction(); 154``` 155 156### animateTo 157 158animateTo(value: AnimateParam, event: () => void): void 159 160提供animateTo接口来指定由于闭包代码导致的状态变化插入过渡动效。 161 162**系统能力:** SystemCapability.ArkUI.ArkUI.Full 163 164**参数:** 165 166| 参数名 | 类型 | 必填 | 说明 | 167| ----- | ---------------------------------------- | ---- | ------------------------------------- | 168| value | [AnimateParam](arkui-ts/ts-explicit-animation.md#animateparam对象说明) | 是 | 设置动画效果相关参数。 | 169| event | () => void | 是 | 指定显示动效的闭包函数,在闭包函数中导致的状态变化系统会自动插入过渡动画。 | 170 171**示例:** 172 173```ts 174// xxx.ets 175@Entry 176@Component 177struct AnimateToExample { 178 @State widthSize: number = 250 179 @State heightSize: number = 100 180 @State rotateAngle: number = 0 181 private flag: boolean = true 182 183 build() { 184 Column() { 185 Button('change size') 186 .width(this.widthSize) 187 .height(this.heightSize) 188 .margin(30) 189 .onClick(() => { 190 if (this.flag) { 191 uiContext.animateTo({ 192 duration: 2000, 193 curve: Curve.EaseOut, 194 iterations: 3, 195 playMode: PlayMode.Normal, 196 onFinish: () => { 197 console.info('play end') 198 } 199 }, () => { 200 this.widthSize = 150 201 this.heightSize = 60 202 }) 203 } else { 204 uiContext.animateTo({}, () => { 205 this.widthSize = 250 206 this.heightSize = 100 207 }) 208 } 209 this.flag = !this.flag 210 }) 211 Button('change rotate angle') 212 .margin(50) 213 .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle }) 214 .onClick(() => { 215 uiContext.animateTo({ 216 duration: 1200, 217 curve: Curve.Friction, 218 delay: 500, 219 iterations: -1, // 设置-1表示动画无限循环 220 playMode: PlayMode.Alternate, 221 onFinish: () => { 222 console.info('play end') 223 } 224 }, () => { 225 this.rotateAngle = 90 226 }) 227 }) 228 }.width('100%').margin({ top: 5 }) 229 } 230} 231``` 232 233### showAlertDialog 234 235showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions): void 236 237显示警告弹窗组件,可设置文本内容与响应回调。 238 239**系统能力:** SystemCapability.ArkUI.ArkUI.Full 240 241**参数:** 242 243| 参数名 | 类型 | 必填 | 说明 | 244| ------- | ---------------------------------------- | ---- | ------------------- | 245| 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组件。 | 246 247 248**示例:** 249 250```ts 251uiContext.showAlertDialog( 252 { 253 title: 'title', 254 message: 'text', 255 autoCancel: true, 256 alignment: DialogAlignment.Bottom, 257 offset: { dx: 0, dy: -20 }, 258 gridCount: 3, 259 confirm: { 260 value: 'button', 261 action: () => { 262 console.info('Button-clicking callback') 263 } 264 }, 265 cancel: () => { 266 console.info('Closed callbacks') 267 } 268 } 269) 270``` 271 272### showActionSheet 273 274showActionSheet(value: ActionSheetOptions): void 275 276定义列表弹窗并弹出。 277 278**系统能力:** SystemCapability.ArkUI.ArkUI.Full 279 280**参数:** 281 282| 参数名 | 类型 | 必填 | 说明 | 283| ------ | ------------------------------------------------------------ | ---- | -------------------- | 284| value | [ActionSheetOptions](arkui-ts/ts-methods-action-sheet.md#actionsheetoptions对象说明) | 是 | 配置列表弹窗的参数。 | 285 286**示例:** 287 288```ts 289uiContext.showActionSheet({ 290 title: 'ActionSheet title', 291 message: 'message', 292 autoCancel: true, 293 confirm: { 294 value: 'Confirm button', 295 action: () => { 296 console.log('Get Alert Dialog handled') 297 } 298 }, 299 cancel: () => { 300 console.log('actionSheet canceled') 301 }, 302 alignment: DialogAlignment.Bottom, 303 offset: { dx: 0, dy: -10 }, 304 sheets: [ 305 { 306 title: 'apples', 307 action: () => { 308 console.log('apples') 309 } 310 }, 311 { 312 title: 'bananas', 313 action: () => { 314 console.log('bananas') 315 } 316 }, 317 { 318 title: 'pears', 319 action: () => { 320 console.log('pears') 321 } 322 } 323 ] 324}) 325``` 326 327### showDatePickerDialog 328 329showDatePickerDialog(options: DatePickerDialogOptions): void 330 331定义日期滑动选择器弹窗并弹出。 332 333**系统能力:** SystemCapability.ArkUI.ArkUI.Full 334 335**参数:** 336 337| 参数名 | 类型 | 必填 | 说明 | 338| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 339| options | [DatePickerDialogOptions](arkui-ts/ts-methods-datepicker-dialog.md#datepickerdialogoptions对象说明) | 是 | 配置日期滑动选择器弹窗的参数。 | 340 341**示例:** 342 343```ts 344let selectedDate: Date = new Date("2010-1-1") 345uiContext.showDatePickerDialog({ 346 start: new Date("2000-1-1"), 347 end: new Date("2100-12-31"), 348 selected: selectedDate, 349 onAccept: (value: DatePickerResult) => { 350 // 通过Date的setFullYear方法设置按下确定按钮时的日期,这样当弹窗再次弹出时显示选中的是上一次确定的日期 351 selectedDate.setFullYear(Number(value.year), Number(value.month), Number(value.day)) 352 console.info("DatePickerDialog:onAccept()" + JSON.stringify(value)) 353 }, 354 onCancel: () => { 355 console.info("DatePickerDialog:onCancel()") 356 }, 357 onChange: (value: DatePickerResult) => { 358 console.info("DatePickerDialog:onChange()" + JSON.stringify(value)) 359 } 360}) 361``` 362 363### showTimePickerDialog 364 365showTimePickerDialog(options: TimePickerDialogOptions): void 366 367定义时间滑动选择器弹窗并弹出。 368 369**系统能力:** SystemCapability.ArkUI.ArkUI.Full 370 371**参数:** 372 373| 参数名 | 类型 | 必填 | 说明 | 374| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 375| options | [TimePickerDialogOptions](arkui-ts/ts-methods-timepicker-dialog.md#timepickerdialogoptions对象说明) | 是 | 配置时间滑动选择器弹窗的参数。 | 376 377**示例:** 378 379```ts 380// xxx.ets 381 382class SelectTime{ 383 selectTime: Date = new Date('2020-12-25T08:30:00') 384 hours(h:number,m:number){ 385 this.selectTime.setHours(h,m) 386 } 387} 388 389@Entry 390@Component 391struct TimePickerDialogExample { 392 @State selectTime: Date = new Date('2023-12-25T08:30:00'); 393 394 build() { 395 Column() { 396 Button('showTimePickerDialog') 397 .margin(30) 398 .onClick(() => { 399 uiContext.showTimePickerDialog({ 400 selected: this.selectTime, 401 onAccept: (value: TimePickerResult) => { 402 // 设置selectTime为按下确定按钮时的时间,这样当弹窗再次弹出时显示选中的为上一次确定的时间 403 let time = new SelectTime() 404 if(value.hour&&value.minute){ 405 time.hours(value.hour, value.minute) 406 } 407 console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) 408 }, 409 onCancel: () => { 410 console.info("TimePickerDialog:onCancel()") 411 }, 412 onChange: (value: TimePickerResult) => { 413 console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) 414 } 415 }) 416 }) 417 }.width('100%').margin({ top: 5 }) 418 } 419} 420``` 421 422### showTextPickerDialog 423 424showTextPickerDialog(options: TextPickerDialogOptions): void 425 426定义文本滑动选择器弹窗并弹出。 427 428**系统能力:** SystemCapability.ArkUI.ArkUI.Full 429 430**参数:** 431 432| 参数名 | 类型 | 必填 | 说明 | 433| ------- | ------------------------------------------------------------ | ---- | ------------------------------ | 434| options | [TextPickerDialogOptions](arkui-ts/ts-methods-textpicker-dialog.md#textpickerdialogoptions对象说明) | 是 | 配置文本滑动选择器弹窗的参数。 | 435 436**示例:** 437 438```ts 439// xxx.ets 440 441class SelectedValue{ 442 select: number = 2 443 set(val:number){ 444 this.select = val 445 } 446} 447class SelectedArray{ 448 select: number[] = [] 449 set(val:number[]){ 450 this.select = val 451 } 452} 453@Entry 454@Component 455struct TextPickerDialogExample { 456 @State selectTime: Date = new Date('2023-12-25T08:30:00'); 457 private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5'] 458 private select : number = 0; 459 build() { 460 Column() { 461 Button('showTextPickerDialog') 462 .margin(30) 463 .onClick(() => { 464 uiContext.showTextPickerDialog({ 465 range: this.fruits, 466 selected: this.select, 467 onAccept: (value: TextPickerResult) => { 468 // 设置select为按下确定按钮时候的选中项index,这样当弹窗再次弹出时显示选中的是上一次确定的选项 469 let selectedVal = new SelectedValue() 470 let selectedArr = new SelectedArray() 471 if(value.index){ 472 value.index instanceof Array?selectedArr.set(value.index) : selectedVal.set(value.index) 473 } 474 console.info("TextPickerDialog:onAccept()" + JSON.stringify(value)) 475 }, 476 onCancel: () => { 477 console.info("TextPickerDialog:onCancel()") 478 }, 479 onChange: (value: TextPickerResult) => { 480 console.info("TextPickerDialog:onChange()" + JSON.stringify(value)) 481 } 482 }) 483 }) 484 }.width('100%').margin({ top: 5 }) 485 } 486} 487``` 488 489### createAnimator 490 491createAnimator(options: AnimatorOptions): AnimatorResult 492 493定义Animator类。 494 495**系统能力:** SystemCapability.ArkUI.ArkUI.Full 496 497**参数:** 498 499| 参数名 | 类型 | 必填 | 说明 | 500| ------- | ---------------------------------------- | ---- | ------- | 501| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) | 是 | 定义动画选项。 | 502 503**返回值:** 504 505| 类型 | 说明 | 506| ---------------------------------------- | ------------- | 507| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator结果接口。 | 508 509**示例:** 510 511```ts 512import { AnimatorOptions } from '@ohos.animator'; 513onWindowStageCreate(windowStage: window.WindowStage) { 514 // Main window is created, set main page for this ability 515 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 516 windowStage.loadContent('pages/Index', (err, data) => { 517 if (err.code) { 518 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 519 return; 520 } 521 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 522 let uiContext = windowStage.getMainWindowSync().getUIContext(); 523 let options:AnimatorOptions = { 524 duration: 1500, 525 easing: "friction", 526 delay: 0, 527 fill: "forwards", 528 direction: "normal", 529 iterations: 3, 530 begin: 200.0, 531 end: 400.0 532 }; 533 uiContext.createAnimator(options); 534 }); 535} 536``` 537 538### runScopedTask 539 540runScopedTask(callback: () => void): void 541 542在当前UI上下文执行传入的回调函数。 543 544**系统能力:** SystemCapability.ArkUI.ArkUI.Full 545 546**参数:** 547 548| 参数名 | 类型 | 必填 | 说明 | 549| -------- | ---------- | ---- | ---- | 550| callback | () => void | 是 | 回调函数 | 551 552**示例:** 553 554```ts 555uiContext.runScopedTask( 556 () => { 557 console.log('Succeeded in runScopedTask'); 558 } 559); 560``` 561 562### setKeyboardAvoidMode<sup>11+</sup> 563 564setKeyboardAvoidMode(value: KeyboardAvoidMode): void 565 566配置虚拟键盘弹出时,页面的避让模式。 567 568**系统能力:** SystemCapability.ArkUI.ArkUI.Full 569 570**参数:** 571 572| 参数名 | 类型 | 必填 | 说明 | 573| -------- | ---------- | ---- | ---- | 574| value | [KeyboardAvoidMode](#keyboardavoidmode11)| 是 | 键盘避让时的页面避让模式。<br />默认值:KeyboardAvoidMode.OFFSET | 575 576**示例:** 577 578```ts 579import { KeyboardAvoidMode, UIContext } from '@ohos.arkui.UIContext'; 580onWindowStageCreate(windowStage: window.WindowStage) { 581 // Main window is created, set main page for this ability 582 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 583 584 windowStage.loadContent('pages/Index', (err, data) => { 585 let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext(); 586 uiContext.setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE); 587 if (err.code) { 588 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 589 return; 590 } 591 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 592 }); 593 } 594``` 595 596### getKeyboardAvoidMode<sup>11+</sup> 597 598getKeyboardAvoidMode(): KeyboardAvoidMode 599 600获取虚拟键盘弹出时,页面的避让模式。 601 602**系统能力:** SystemCapability.ArkUI.ArkUI.Full 603 604**返回值:** 605 606| 类型 | 说明 | 607| ---------- | ---- | 608| [KeyboardAvoidMode](#keyboardavoidmode11)| 返回当前的页面避让模式。| 609 610**示例:** 611 612```ts 613import { KeyboardAvoidMode, UIContext } from '@ohos.arkui.UIContext'; 614onWindowStageCreate(windowStage: window.WindowStage) { 615 // Main window is created, set main page for this ability 616 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 617 618 windowStage.loadContent('pages/Index', (err, data) => { 619 let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext(); 620 let KeyboardAvoidMode = uiContext.getKeyboardAvoidMode(); 621 console.log("KeyboardAvoidMode:", JSON.stringify(KeyboardAvoidMode)); 622 if (err.code) { 623 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 624 return; 625 } 626 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 627 }); 628 } 629 630``` 631 632### getAtomicServiceBar<sup>11+</sup> 633 634getAtomicServiceBar(): Nullable\<AtomicServiceBar> 635 636获取AtomicServiceBar对象,通过该对象设置原子化服务menuBar的属性。 637 638**系统能力:** SystemCapability.ArkUI.ArkUI.Full 639 640**返回值:** 641 642| 类型 | 说明 | 643| ------------------------------------------------- | ------------------------------------------------------------ | 644| Nullable<[AtomicServiceBar](#atomicservicebar11)> | 如果是原子化服务则返回AtomicServerBar类型,否则返回undefined。 | 645 646**示例:** 647 648```ts 649import {UIContext, AtomicServiceBar} from '@ohos.arkui.UIContext'; 650import hilog from '@ohos.hilog'; 651import window from "@ohos.window"; 652onWindowStageCreate(windowStage: window.WindowStage) { 653 // Main window is created, set main page for this ability 654 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 655 windowStage.loadContent('pages/Index', (err, data) => { 656 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 657 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 658 if (atomicServiceBar != undefined) { 659 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 660 } else { 661 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 662 } 663 }); 664} 665``` 666### getDragController<sup>11+</sup> 667 668getDragController(): DragController 669 670获取DragController对象,可通过该对象创建并发起拖拽。 671 672**系统能力:** SystemCapability.ArkUI.ArkUI.Full 673 674**返回值:** 675 676|类型|说明| 677|----|----| 678|[DragController](js-apis-arkui-dragController.md#dragController)| 获取DragController对象。| 679 680**示例:** 681 682```ts 683uiContext.getDragController(); 684``` 685 686### getDragPreview<sup>11+</sup> 687 688getDragPreview(): dragController.DragPreview 689 690返回一个代表拖拽背板的对象。 691 692**系统能力:** SystemCapability.ArkUI.ArkUI.Full 693 694**返回值:** 695 696| 类型 | 说明 | 697| ------------------------------------------------------------ | ------------------------------------------------------------ | 698| [dragController.DragPreview](js-apis-arkui-dragController.md#dragpreview11) | 一个代表拖拽背板的对象,提供背板样式设置的接口,在OnDrop和OnDragEnd回调中使用不生效。 | 699 700**错误码:** 通用错误码请参考[通用错误码说明文档](../errorcode-universal.md)。 701 702**示例:** 703 704请参考[animate](js-apis-arkui-dragController.md#animate11) 705 706### keyframeAnimateTo<sup>11+</sup> 707 708keyframeAnimateTo(param: KeyframeAnimateParam, keyframes: Array<KeyframeState>): void 709 710产生关键帧动画。该接口的使用说明请参考[keyframeAnimateTo](arkui-ts/ts-keyframeAnimateTo.md)。 711 712**系统能力:** SystemCapability.ArkUI.ArkUI.Full 713 714**参数:** 715 716| 参数名 | 类型 | 必填 | 说明 | 717| ------------ | ---------------------------------------------------- | ------- | ---------------------------- | 718| param | [KeyframeAnimateParam](arkui-ts/ts-keyframeAnimateTo.md#keyframeanimateparam对象说明) | 是 | 关键帧动画的整体动画参数。 | 719| keyframes | Array<[KeyframeState](arkui-ts/ts-keyframeAnimateTo.md#keyframestate对象说明)> | 是 | 所有的关键帧状态。 | 720 721## Font 722 723以下API需先使用UIContext中的[getFont()](#getfont)方法获取到Font对象,再通过该对象调用对应方法。 724 725### registerFont 726 727registerFont(options: font.FontOptions): void 728 729在字体管理中注册自定义字体。 730 731**系统能力:** SystemCapability.ArkUI.ArkUI.Full 732 733**参数:** 734 735| 参数名 | 类型 | 必填 | 说明 | 736| ------- | ---------------------------------------- | ---- | ----------- | 737| options | [font.FontOptions](js-apis-font.md#fontoptions) | 是 | 注册的自定义字体信息。 | 738 739**示例:** 740 741```ts 742import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 743let font:Font = uiContext.getFont(); 744font.registerFont({ 745 familyName: 'medium', 746 familySrc: '/font/medium.ttf' 747}); 748``` 749### getSystemFontList 750 751getSystemFontList(): Array\<string> 752 753获取系统支持的字体名称列表。 754 755**系统能力:** SystemCapability.ArkUI.ArkUI.Full 756 757**返回值:** 758 759| 类型 | 说明 | 760| -------------- | --------- | 761| Array\<string> | 系统的字体名列表。 | 762 763**示例:** 764 765```ts 766import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 767let font:Font|undefined = uiContext.getFont(); 768if(font){ 769 font.getSystemFontList() 770} 771``` 772 773### getFontByName 774 775getFontByName(fontName: string): font.FontInfo 776 777根据传入的系统字体名称获取系统字体的相关信息。 778 779**系统能力:** SystemCapability.ArkUI.ArkUI.Full 780 781**参数:** 782 783| 参数名 | 类型 | 必填 | 说明 | 784| -------- | ------ | ---- | ------- | 785| fontName | string | 是 | 系统的字体名。 | 786 787**返回值:** 788 789| 类型 | 说明 | 790| ----------------------------------------- | -------------- | 791| [font.FontInfo](js-apis-font.md#fontinfo) | 字体的详细信息 | 792 793**示例:** 794 795```ts 796import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 797let font:Font|undefined = uiContext.getFont(); 798if(font){ 799 font.getFontByName('Sans Italic') 800} 801``` 802 803## ComponentUtils 804 805以下API需先使用UIContext中的[getComponentUtils()](#getcomponentutils)方法获取到ComponentUtils对象,再通过该对象调用对应方法。 806 807### getRectangleById 808 809getRectangleById(id: string): componentUtils.ComponentInfo 810 811获取组件大小、位置、平移缩放旋转及仿射矩阵属性信息。 812 813**系统能力:** SystemCapability.ArkUI.ArkUI.Full 814 815**参数:** 816 817| 参数名 | 类型 | 必填 | 说明 | 818| ---- | ------ | ---- | --------- | 819| id | string | 是 | 组件唯一标识id。 | 820 821**返回值:** 822 823| 类型 | 说明 | 824| ---------------------------------------- | ------------------------ | 825| [ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | 组件大小、位置、平移缩放旋转及仿射矩阵属性信息。 | 826 827**示例:** 828 829```ts 830import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 831let componentUtils:ComponentUtils = uiContext.getComponentUtils(); 832let modePosition = componentUtils.getRectangleById("onClick"); 833let localOffsetWidth = modePosition.size.width; 834let localOffsetHeight = modePosition.size.height; 835``` 836 837## UIInspector 838 839以下API需先使用UIContext中的[getUIInspector()](#getuiinspector)方法获取到UIInspector对象,再通过该对象调用对应方法。 840 841### createComponentObserver 842 843createComponentObserver(id: string): inspector.ComponentObserver 844 845注册组件布局和绘制完成回调通知。 846 847**系统能力:** SystemCapability.ArkUI.ArkUI.Full 848 849**参数:** 850 851| 参数名 | 类型 | 必填 | 说明 | 852| ---- | ------ | ---- | ------- | 853| id | string | 是 | 指定组件id。 | 854 855**返回值:** 856 857| 类型 | 说明 | 858| ------------------------------------------------------------ | -------------------------------------------------- | 859| [inspector.ComponentObserver](js-apis-arkui-inspector.md#componentobserver) | 组件回调事件监听句柄,用于注册和取消注册监听回调。 | 860 861**示例:** 862 863```ts 864import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 865let inspector:UIInspector = uiContext.getUIInspector(); 866let listener = inspector.createComponentObserver('COMPONENT_ID'); 867``` 868 869## UIObserver<sup>11+</sup> 870 871以下API需先使用UIContext中的[getUIObserver()](#getuiobserver11)方法获取到UIObserver对象,再通过该对象调用对应方法。 872 873### on('navDestinationUpdate')<sup>11+</sup> 874 875on(type: 'navDestinationUpdate', callback: Callback\<observer.NavDestinationInfo\>): void 876 877监听NavDestination组件的状态变化。 878 879**系统能力:** SystemCapability.ArkUI.ArkUI.Full 880 881**参数:** 882 883| 参数名 | 类型 | 必填 | 说明 | 884| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 885| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 | 886| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 是 | 回调函数。返回当前的NavDestination组件状态。 | 887 888**示例:** 889 890```ts 891import { UIObserver } from '@ohos.arkui.UIContext'; 892let observer:UIObserver = uiContext.getUIObserver(); 893observer.on('navDestinationUpdate', (info) => { 894 console.info('NavDestination state update', JSON.stringify(info)); 895}); 896``` 897 898### off('navDestinationUpdate')<sup>11+</sup> 899 900off(type: 'navDestinationUpdate', callback?: Callback\<observer.NavDestinationInfo\>): void 901 902取消监听NavDestination组件的状态变化。 903 904**系统能力:** SystemCapability.ArkUI.ArkUI.Full 905 906**参数:** 907 908| 参数名 | 类型 | 必填 | 说明 | 909| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ | 910| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 | 911| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 否 | 回调函数。返回当前的NavDestination组件状态。 | 912 913**示例:** 914 915```ts 916import { UIObserver } from '@ohos.arkui.UIContext'; 917let observer:UIObserver = uiContext.getUIObserver(); 918observer.off('navDestinationUpdate'); 919``` 920 921### on('navDestinationUpdate')<sup>11+</sup> 922 923on(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback: Callback\<observer.NavDestinationInfo\>): void 924 925监听NavDestination组件的状态变化。 926 927**系统能力:** SystemCapability.ArkUI.ArkUI.Full 928 929**参数:** 930 931| 参数名 | 类型 | 必填 | 说明 | 932| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 933| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 | 934| options | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | 是 | 指定监听的Navigation的id。 | 935| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 是 | 回调函数。返回当前的NavDestination组件状态。 | 936 937**示例:** 938 939```ts 940import { UIObserver } from '@ohos.arkui.UIContext'; 941let observer:UIObserver = uiContext.getUIObserver(); 942observer.on('navDestinationUpdate', { navigationId: "testId" }, (info) => { 943 console.info('NavDestination state update', JSON.stringify(info)); 944}); 945``` 946 947### off('navDestinationUpdate')<sup>11+</sup> 948 949off(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback?: Callback\<observer.NavDestinationInfo\>): void 950 951取消监听NavDestination组件的状态变化。 952 953**系统能力:** SystemCapability.ArkUI.ArkUI.Full 954 955**参数:** 956 957| 参数名 | 类型 | 必填 | 说明 | 958| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 959| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 | 960| options | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | 是 | 指定监听的Navigation的id。 | 961| callback | Callback\<observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo)\> | 否 | 回调函数。返回当前的NavDestination组件状态。 | 962 963**示例:** 964 965```ts 966import { UIObserver } from '@ohos.arkui.UIContext'; 967let observer:UIObserver = uiContext.getUIObserver(); 968observer.off('navDestinationUpdate', { navigationId: "testId" }); 969``` 970 971### on('routerPageUpdate')<sup>11+</sup> 972 973on(type: 'routerPageUpdate', callback: Callback\<observer.RouterPageInfo\>): void 974 975监听router中page页面的状态变化。 976 977**系统能力:** SystemCapability.ArkUI.ArkUI.Full 978 979**参数:** 980 981| 参数名 | 类型 | 必填 | 说明 | 982| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 983| type | string | 是 | 监听事件,固定为'routerPageUpdate',即router中page页面的状态变化。 | 984| callback | Callback\<observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo)\> | 是 | 回调函数。携带pageInfo,返回当前的page页面状态。 | 985 986**示例:** 987 988```ts 989import {UIContext, UIObserver } from '@kit.ArkUI'; 990 991let observer:UIObserver = this.getUIContext().getUIObserver(); 992observer.on('routerPageUpdate', (info) => { 993 console.info('RouterPage state updated, called by ' + `${info.name}`); 994}); 995``` 996 997### off('routerPageUpdate')<sup>11+</sup> 998 999off(type: 'routerPageUpdate', callback?: Callback\<observer.RouterPageInfo\>): void 1000 1001取消监听router中page页面的状态变化。 1002 1003**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1004 1005**参数:** 1006 1007| 参数名 | 类型 | 必填 | 说明 | 1008| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1009| type | string | 是 | 监听事件,固定为'routerPageUpdate',即router中page页面的状态变化。 | 1010| callback | Callback\<observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo)\> | 否 | 需要被注销的回调函数。 | 1011 1012**示例:** 1013 1014```ts 1015import {UIContext, UIObserver } from '@kit.ArkUI'; 1016 1017let observer:UIObserver = this.getUIContext().getUIObserver(); 1018function callBackFunc(info:observer.RouterPageInfo) {}; 1019// callBackFunc is defined and used before 1020observer.off('routerPageUpdate', callBackFunc); 1021``` 1022 1023## MediaQuery 1024 1025以下API需先使用UIContext中的[getMediaQuery()](#getmediaquery)方法获取到MediaQuery对象,再通过该对象调用对应方法。 1026 1027### matchMediaSync 1028 1029matchMediaSync(condition: string): mediaQuery.MediaQueryListener 1030 1031设置媒体查询的查询条件,并返回对应的监听句柄。 1032 1033**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1034 1035**参数:** 1036 1037| 参数名 | 类型 | 必填 | 说明 | 1038| --------- | ------ | ---- | ---------------------------------------- | 1039| condition | string | 是 | 媒体事件的匹配条件,具体可参考[媒体查询语法规则](../../ui/arkts-layout-development-media-query.md#语法规则)。 | 1040 1041**返回值:** 1042 1043| 类型 | 说明 | 1044| ------------------------------------------------------------ | -------------------------------------------- | 1045| [mediaQuery.MediaQueryListener](js-apis-mediaquery.md#mediaquerylistener) | 媒体事件监听句柄,用于注册和去注册监听回调。 | 1046 1047**示例:** 1048 1049```ts 1050import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1051let mediaquery: MediaQuery = uiContext.getMediaQuery(); 1052let listener = mediaquery.matchMediaSync('(orientation: landscape)'); //监听横屏事件 1053``` 1054 1055## Router 1056 1057以下API需先使用UIContext中的[getRouter()](#getrouter)方法获取到Router对象,再通过该对象调用对应方法。 1058 1059### pushUrl 1060 1061pushUrl(options: router.RouterOptions): Promise<void> 1062 1063跳转到应用内的指定页面,通过Promise获取跳转异常的返回结果。 1064 1065**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1066 1067**参数:** 1068 1069| 参数名 | 类型 | 必填 | 说明 | 1070| ------- | ---------------------------------------- | ---- | --------- | 1071| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 | 1072 1073**返回值:** 1074 1075| 类型 | 说明 | 1076| ------------------- | ------- | 1077| Promise<void> | 异常返回结果。 | 1078 1079**错误码:** 1080 1081以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1082 1083| 错误码ID | 错误信息 | 1084| ------ | ---------------------------------- | 1085| 100001 | if UI execution context not found. | 1086| 100002 | if the uri is not exist. | 1087| 100003 | if the pages are pushed too much. | 1088 1089**示例:** 1090 1091```ts 1092import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1093import { BusinessError } from '@ohos.base'; 1094let router:Router = uiContext.getRouter(); 1095try { 1096 router.pushUrl({ 1097 url: 'pages/routerpage2', 1098 params: { 1099 data1: 'message', 1100 data2: { 1101 data3: [123, 456, 789] 1102 } 1103 } 1104 }) 1105} catch (err) { 1106 let message = (err as BusinessError).message; 1107 let code = (err as BusinessError).code; 1108 console.error(`pushUrl failed, code is ${code}, message is ${message}`); 1109} 1110``` 1111 1112### pushUrl 1113 1114pushUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void 1115 1116跳转到应用内的指定页面。 1117 1118**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1119 1120**参数:** 1121 1122| 参数名 | 类型 | 必填 | 说明 | 1123| -------- | ---------------------------------------- | ---- | --------- | 1124| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 | 1125| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 1126 1127**错误码:** 1128 1129以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1130 1131| 错误码ID | 错误信息 | 1132| ------ | ---------------------------------- | 1133| 100001 | if UI execution context not found. | 1134| 100002 | if the uri is not exist. | 1135| 100003 | if the pages are pushed too much. | 1136 1137**示例:** 1138 1139```ts 1140import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1141import { BusinessError } from '@ohos.base'; 1142let router:Router = uiContext.getRouter(); 1143router.pushUrl({ 1144 url: 'pages/routerpage2', 1145 params: { 1146 data1: 'message', 1147 data2: { 1148 data3: [123, 456, 789] 1149 } 1150 } 1151}, (err: Error) => { 1152 if (err) { 1153 let message = (err as BusinessError).message; 1154 let code = (err as BusinessError).code; 1155 console.error(`pushUrl failed, code is ${code}, message is ${message}`); 1156 return; 1157 } 1158 console.info('pushUrl success'); 1159}) 1160``` 1161 1162### pushUrl 1163 1164pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void> 1165 1166跳转到应用内的指定页面,通过Promise获取跳转异常的返回结果。 1167 1168**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1169 1170**参数:** 1171 1172| 参数名 | 类型 | 必填 | 说明 | 1173| ------- | ---------------------------------------- | ---- | ---------- | 1174| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 | 1175| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 1176 1177**返回值:** 1178 1179| 类型 | 说明 | 1180| ------------------- | ------- | 1181| Promise<void> | 异常返回结果。 | 1182 1183**错误码:** 1184 1185以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1186 1187| 错误码ID | 错误信息 | 1188| ------ | ---------------------------------- | 1189| 100001 | if UI execution context not found. | 1190| 100002 | if the uri is not exist. | 1191| 100003 | if the pages are pushed too much. | 1192 1193**示例:** 1194 1195```ts 1196import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1197import { BusinessError } from '@ohos.base'; 1198import router from '@ohos.router'; 1199let routerF:Router = uiContext.getRouter(); 1200class RouterTmp{ 1201 Standard:router.RouterMode = router.RouterMode.Standard 1202} 1203let rtm:RouterTmp = new RouterTmp() 1204try { 1205 routerF.pushUrl({ 1206 url: 'pages/routerpage2', 1207 params: { 1208 data1: 'message', 1209 data2: { 1210 data3: [123, 456, 789] 1211 } 1212 } 1213 }, rtm.Standard) 1214} catch (err) { 1215 let message = (err as BusinessError).message; 1216 let code = (err as BusinessError).code; 1217 console.error(`pushUrl failed, code is ${code}, message is ${message}`); 1218} 1219``` 1220 1221### pushUrl 1222 1223pushUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 1224 1225跳转到应用内的指定页面。 1226 1227**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1228 1229**参数:** 1230 1231| 参数名 | 类型 | 必填 | 说明 | 1232| -------- | ---------------------------------------- | ---- | ---------- | 1233| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 | 1234| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 1235| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 1236 1237**错误码:** 1238 1239以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1240 1241| 错误码ID | 错误信息 | 1242| ------ | ---------------------------------- | 1243| 100001 | if UI execution context not found. | 1244| 100002 | if the uri is not exist. | 1245| 100003 | if the pages are pushed too much. | 1246 1247**示例:** 1248 1249```ts 1250import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1251import { BusinessError } from '@ohos.base'; 1252import router from '@ohos.router'; 1253let routerF:Router = uiContext.getRouter(); 1254class RouterTmp{ 1255 Standard:router.RouterMode = router.RouterMode.Standard 1256} 1257let rtm:RouterTmp = new RouterTmp() 1258routerF.pushUrl({ 1259 url: 'pages/routerpage2', 1260 params: { 1261 data1: 'message', 1262 data2: { 1263 data3: [123, 456, 789] 1264 } 1265 } 1266}, rtm.Standard, (err) => { 1267 if (err) { 1268 let message = (err as BusinessError).message; 1269 let code = (err as BusinessError).code; 1270 console.error(`pushUrl failed, code is ${code}, message is ${message}`); 1271 return; 1272 } 1273 console.info('pushUrl success'); 1274}) 1275``` 1276 1277### replaceUrl 1278 1279replaceUrl(options: router.RouterOptions): Promise<void> 1280 1281用应用内的某个页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回的结果。 1282 1283**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1284 1285**参数:** 1286 1287| 参数名 | 类型 | 必填 | 说明 | 1288| ------- | ---------------------------------------- | ---- | --------- | 1289| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 | 1290 1291**返回值:** 1292 1293| 类型 | 说明 | 1294| ------------------- | ------- | 1295| Promise<void> | 异常返回结果。 | 1296 1297**错误码:** 1298 1299以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1300 1301| 错误码ID | 错误信息 | 1302| ------ | ---------------------------------------- | 1303| 100001 | if UI execution context not found, only throw in standard system. | 1304| 200002 | if the uri is not exist. | 1305 1306**示例:** 1307 1308```ts 1309import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1310import { BusinessError } from '@ohos.base'; 1311let router:Router = uiContext.getRouter(); 1312try { 1313 router.replaceUrl({ 1314 url: 'pages/detail', 1315 params: { 1316 data1: 'message' 1317 } 1318 }) 1319} catch (err) { 1320 let message = (err as BusinessError).message; 1321 let code = (err as BusinessError).code; 1322 console.error(`replaceUrl failed, code is ${code}, message is ${message}`); 1323} 1324``` 1325 1326### replaceUrl 1327 1328replaceUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void 1329 1330用应用内的某个页面替换当前页面,并销毁被替换的页面。 1331 1332**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1333 1334**参数:** 1335 1336| 参数名 | 类型 | 必填 | 说明 | 1337| -------- | ---------------------------------------- | ---- | --------- | 1338| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 | 1339| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 1340 1341**错误码:** 1342 1343以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1344 1345| 错误码ID | 错误信息 | 1346| ------ | ---------------------------------------- | 1347| 100001 | if UI execution context not found, only throw in standard system. | 1348| 200002 | if the uri is not exist. | 1349 1350**示例:** 1351 1352```ts 1353import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1354import { BusinessError } from '@ohos.base'; 1355let router:Router = uiContext.getRouter(); 1356router.replaceUrl({ 1357 url: 'pages/detail', 1358 params: { 1359 data1: 'message' 1360 } 1361}, (err: Error) => { 1362 if (err) { 1363 let message = (err as BusinessError).message; 1364 let code = (err as BusinessError).code; 1365 console.error(`replaceUrl failed, code is ${code}, message is ${message}`); 1366 return; 1367 } 1368 console.info('replaceUrl success'); 1369}) 1370``` 1371 1372### replaceUrl 1373 1374replaceUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void> 1375 1376用应用内的某个页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。 1377 1378**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1379 1380**参数:** 1381 1382| 参数名 | 类型 | 必填 | 说明 | 1383| ------- | ---------------------------------------- | ---- | ---------- | 1384| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 | 1385| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 1386 1387**返回值:** 1388 1389| 类型 | 说明 | 1390| ------------------- | ------- | 1391| Promise<void> | 异常返回结果。 | 1392 1393**错误码:** 1394 1395以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1396 1397| 错误码ID | 错误信息 | 1398| ------ | ---------------------------------------- | 1399| 100001 | if can not get the delegate, only throw in standard system. | 1400| 200002 | if the uri is not exist. | 1401 1402**示例:** 1403 1404```ts 1405import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1406import { BusinessError } from '@ohos.base'; 1407import router from '@ohos.router'; 1408let routerF:Router = uiContext.getRouter(); 1409class RouterTmp{ 1410 Standard:router.RouterMode = router.RouterMode.Standard 1411} 1412let rtm:RouterTmp = new RouterTmp() 1413try { 1414 routerF.replaceUrl({ 1415 url: 'pages/detail', 1416 params: { 1417 data1: 'message' 1418 } 1419 }, rtm.Standard) 1420} catch (err) { 1421 let message = (err as BusinessError).message; 1422 let code = (err as BusinessError).code; 1423 console.error(`replaceUrl failed, code is ${code}, message is ${message}`); 1424} 1425``` 1426 1427### replaceUrl 1428 1429replaceUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 1430 1431用应用内的某个页面替换当前页面,并销毁被替换的页面。 1432 1433**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1434 1435**参数:** 1436 1437| 参数名 | 类型 | 必填 | 说明 | 1438| -------- | ---------------------------------------- | ---- | ---------- | 1439| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 | 1440| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 1441| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 1442 1443**错误码:** 1444 1445以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1446 1447| 错误码ID | 错误信息 | 1448| ------ | ---------------------------------------- | 1449| 100001 | if UI execution context not found, only throw in standard system. | 1450| 200002 | if the uri is not exist. | 1451 1452**示例:** 1453 1454```ts 1455import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1456import { BusinessError } from '@ohos.base'; 1457import router from '@ohos.router'; 1458let routerF:Router = uiContext.getRouter(); 1459class RouterTmp{ 1460 Standard:router.RouterMode = router.RouterMode.Standard 1461} 1462let rtm:RouterTmp = new RouterTmp() 1463routerF.replaceUrl({ 1464 url: 'pages/detail', 1465 params: { 1466 data1: 'message' 1467 } 1468}, rtm.Standard, (err: Error) => { 1469 if (err) { 1470 let message = (err as BusinessError).message; 1471 let code = (err as BusinessError).code; 1472 console.error(`replaceUrl failed, code is ${code}, message is ${message}`); 1473 return; 1474 } 1475 console.info('replaceUrl success'); 1476}); 1477``` 1478 1479### pushNamedRoute 1480 1481pushNamedRoute(options: router.NamedRouterOptions): Promise<void> 1482 1483跳转到指定的命名路由页面,通过Promise获取跳转异常的返回结果。 1484 1485**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1486 1487**参数:** 1488 1489| 参数名 | 类型 | 必填 | 说明 | 1490| ------- | ---------------------------------------- | ---- | --------- | 1491| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 | 1492 1493**返回值:** 1494 1495| 类型 | 说明 | 1496| ------------------- | ------- | 1497| Promise<void> | 异常返回结果。 | 1498 1499**错误码:** 1500 1501以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1502 1503| 错误码ID | 错误信息 | 1504| ------ | ---------------------------------- | 1505| 100001 | if UI execution context not found. | 1506| 100003 | if the pages are pushed too much. | 1507| 100004 | if the named route is not exist. | 1508 1509**示例:** 1510 1511```ts 1512import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1513import { BusinessError } from '@ohos.base'; 1514let router:Router = uiContext.getRouter(); 1515try { 1516 router.pushNamedRoute({ 1517 name: 'myPage', 1518 params: { 1519 data1: 'message', 1520 data2: { 1521 data3: [123, 456, 789] 1522 } 1523 } 1524 }) 1525} catch (err) { 1526 let message = (err as BusinessError).message; 1527 let code = (err as BusinessError).code; 1528 console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); 1529} 1530``` 1531 1532### pushNamedRoute 1533 1534pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void 1535 1536跳转到指定的命名路由页面。 1537 1538**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1539 1540**参数:** 1541 1542| 参数名 | 类型 | 必填 | 说明 | 1543| -------- | ---------------------------------------- | ---- | --------- | 1544| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 | 1545| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 1546 1547**错误码:** 1548 1549以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1550 1551| 错误码ID | 错误信息 | 1552| ------ | ---------------------------------- | 1553| 100001 | if UI execution context not found. | 1554| 100003 | if the pages are pushed too much. | 1555| 100004 | if the named route is not exist. | 1556 1557**示例:** 1558 1559```ts 1560import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1561import { BusinessError } from '@ohos.base'; 1562let router:Router = uiContext.getRouter(); 1563router.pushNamedRoute({ 1564 name: 'myPage', 1565 params: { 1566 data1: 'message', 1567 data2: { 1568 data3: [123, 456, 789] 1569 } 1570 } 1571}, (err: Error) => { 1572 if (err) { 1573 let message = (err as BusinessError).message; 1574 let code = (err as BusinessError).code; 1575 console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); 1576 return; 1577 } 1578 console.info('pushNamedRoute success'); 1579}) 1580``` 1581### pushNamedRoute 1582 1583pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void> 1584 1585跳转到指定的命名路由页面,通过Promise获取跳转异常的返回结果。 1586 1587**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1588 1589**参数:** 1590 1591| 参数名 | 类型 | 必填 | 说明 | 1592| ------- | ---------------------------------------- | ---- | ---------- | 1593| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 | 1594| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 1595 1596**返回值:** 1597 1598| 类型 | 说明 | 1599| ------------------- | ------- | 1600| Promise<void> | 异常返回结果。 | 1601 1602**错误码:** 1603 1604以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1605 1606| 错误码ID | 错误信息 | 1607| ------ | ---------------------------------- | 1608| 100001 | if UI execution context not found. | 1609| 100003 | if the pages are pushed too much. | 1610| 100004 | if the named route is not exist. | 1611 1612**示例:** 1613 1614```ts 1615import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1616import { BusinessError } from '@ohos.base'; 1617import router from '@ohos.router'; 1618let routerF:Router = uiContext.getRouter(); 1619class RouterTmp{ 1620 Standard:router.RouterMode = router.RouterMode.Standard 1621} 1622let rtm:RouterTmp = new RouterTmp() 1623try { 1624 routerF.pushNamedRoute({ 1625 name: 'myPage', 1626 params: { 1627 data1: 'message', 1628 data2: { 1629 data3: [123, 456, 789] 1630 } 1631 } 1632 }, rtm.Standard) 1633} catch (err) { 1634 let message = (err as BusinessError).message; 1635 let code = (err as BusinessError).code; 1636 console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); 1637} 1638``` 1639 1640### pushNamedRoute 1641 1642pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 1643 1644跳转到指定的命名路由页面。 1645 1646**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1647 1648**参数:** 1649 1650| 参数名 | 类型 | 必填 | 说明 | 1651| -------- | ---------------------------------------- | ---- | ---------- | 1652| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 | 1653| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 1654| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 1655 1656**错误码:** 1657 1658以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1659 1660| 错误码ID | 错误信息 | 1661| ------ | ---------------------------------- | 1662| 100001 | if UI execution context not found. | 1663| 100003 | if the pages are pushed too much. | 1664| 100004 | if the named route is not exist. | 1665 1666**示例:** 1667 1668```ts 1669import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1670import { BusinessError } from '@ohos.base'; 1671import router from '@ohos.router'; 1672let routerF:Router = uiContext.getRouter(); 1673class RouterTmp{ 1674 Standard:router.RouterMode = router.RouterMode.Standard 1675} 1676let rtm:RouterTmp = new RouterTmp() 1677routerF.pushNamedRoute({ 1678 name: 'myPage', 1679 params: { 1680 data1: 'message', 1681 data2: { 1682 data3: [123, 456, 789] 1683 } 1684 } 1685}, rtm.Standard, (err: Error) => { 1686 if (err) { 1687 let message = (err as BusinessError).message; 1688 let code = (err as BusinessError).code; 1689 console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`); 1690 return; 1691 } 1692 console.info('pushNamedRoute success'); 1693}) 1694``` 1695 1696### replaceNamedRoute 1697 1698replaceNamedRoute(options: router.NamedRouterOptions): Promise<void> 1699 1700用指定的命名路由页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。 1701 1702**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1703 1704**参数:** 1705 1706| 参数名 | 类型 | 必填 | 说明 | 1707| ------- | ---------------------------------------- | ---- | --------- | 1708| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 | 1709 1710**返回值:** 1711 1712| 类型 | 说明 | 1713| ------------------- | ------- | 1714| Promise<void> | 异常返回结果。 | 1715 1716**错误码:** 1717 1718以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1719 1720| 错误码ID | 错误信息 | 1721| ------ | ---------------------------------------- | 1722| 100001 | if UI execution context not found, only throw in standard system. | 1723| 100004 | if the named route is not exist. | 1724 1725**示例:** 1726 1727```ts 1728import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1729import { BusinessError } from '@ohos.base'; 1730let router:Router = uiContext.getRouter(); 1731try { 1732 router.replaceNamedRoute({ 1733 name: 'myPage', 1734 params: { 1735 data1: 'message' 1736 } 1737 }) 1738} catch (err) { 1739 let message = (err as BusinessError).message; 1740 let code = (err as BusinessError).code; 1741 console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`); 1742} 1743``` 1744 1745### replaceNamedRoute 1746 1747replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void 1748 1749用指定的命名路由页面替换当前页面,并销毁被替换的页面。 1750 1751**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1752 1753**参数:** 1754 1755| 参数名 | 类型 | 必填 | 说明 | 1756| -------- | ---------------------------------------- | ---- | --------- | 1757| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 | 1758| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 1759 1760**错误码:** 1761 1762以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1763 1764| 错误码ID | 错误信息 | 1765| ------ | ---------------------------------------- | 1766| 100001 | if UI execution context not found, only throw in standard system. | 1767| 100004 | if the named route is not exist. | 1768 1769**示例:** 1770 1771```ts 1772import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1773import { BusinessError } from '@ohos.base'; 1774let router:Router = uiContext.getRouter(); 1775router.replaceNamedRoute({ 1776 name: 'myPage', 1777 params: { 1778 data1: 'message' 1779 } 1780}, (err: Error) => { 1781 if (err) { 1782 let message = (err as BusinessError).message; 1783 let code = (err as BusinessError).code; 1784 console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`); 1785 return; 1786 } 1787 console.info('replaceNamedRoute success'); 1788}) 1789``` 1790 1791### replaceNamedRoute 1792 1793replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void> 1794 1795用指定的命名路由页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。 1796 1797**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1798 1799**参数:** 1800 1801| 参数名 | 类型 | 必填 | 说明 | 1802| ------- | ---------------------------------------- | ---- | ---------- | 1803| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 | 1804| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 1805 1806 1807**返回值:** 1808 1809| 类型 | 说明 | 1810| ------------------- | ------- | 1811| Promise<void> | 异常返回结果。 | 1812 1813**错误码:** 1814 1815以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1816 1817| 错误码ID | 错误信息 | 1818| ------ | ---------------------------------------- | 1819| 100001 | if can not get the delegate, only throw in standard system. | 1820| 100004 | if the named route is not exist. | 1821 1822**示例:** 1823 1824```ts 1825import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1826import { BusinessError } from '@ohos.base'; 1827import router from '@ohos.router'; 1828let routerF:Router = uiContext.getRouter(); 1829class RouterTmp{ 1830 Standard:router.RouterMode = router.RouterMode.Standard 1831} 1832let rtm:RouterTmp = new RouterTmp() 1833try { 1834 routerF.replaceNamedRoute({ 1835 name: 'myPage', 1836 params: { 1837 data1: 'message' 1838 } 1839 }, rtm.Standard) 1840} catch (err) { 1841 let message = (err as BusinessError).message; 1842 let code = (err as BusinessError).code; 1843 console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`); 1844} 1845``` 1846 1847### replaceNamedRoute 1848 1849replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void 1850 1851用指定的命名路由页面替换当前页面,并销毁被替换的页面。 1852 1853**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1854 1855**参数:** 1856 1857| 参数名 | 类型 | 必填 | 说明 | 1858| -------- | ---------------------------------------- | ---- | ---------- | 1859| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 | 1860| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 | 1861| callback | AsyncCallback<void> | 是 | 异常响应回调。 | 1862 1863**错误码:** 1864 1865以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 1866 1867| 错误码ID | 错误信息 | 1868| ------ | ---------------------------------------- | 1869| 100001 | if UI execution context not found, only throw in standard system. | 1870| 100004 | if the named route is not exist. | 1871 1872**示例:** 1873 1874```ts 1875import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1876import { BusinessError } from '@ohos.base'; 1877import router from '@ohos.router'; 1878let routerF:Router = uiContext.getRouter(); 1879class RouterTmp{ 1880 Standard:router.RouterMode = router.RouterMode.Standard 1881} 1882let rtm:RouterTmp = new RouterTmp() 1883routerF.replaceNamedRoute({ 1884 name: 'myPage', 1885 params: { 1886 data1: 'message' 1887 } 1888}, rtm.Standard, (err: Error) => { 1889 if (err) { 1890 let message = (err as BusinessError).message; 1891 let code = (err as BusinessError).code; 1892 console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`); 1893 return; 1894 } 1895 console.info('replaceNamedRoute success'); 1896}); 1897``` 1898 1899### back 1900 1901back(options?: router.RouterOptions ): void 1902 1903返回上一页面或指定的页面。 1904 1905**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1906 1907**参数:** 1908 1909| 参数名 | 类型 | 必填 | 说明 | 1910| ------- | ---------------------------------------- | ---- | ---------------------------------------- | 1911| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 否 | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面不会重新构建,页面栈里面的page不会回收,出栈后会被回收。 | 1912 1913**示例:** 1914 1915```ts 1916import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1917import { BusinessError } from '@ohos.base'; 1918let router: Router = uiContext.getRouter(); 1919router.back({url:'pages/detail'}); 1920``` 1921 1922### clear 1923 1924clear(): void 1925 1926清空页面栈中的所有历史页面,仅保留当前页面作为栈顶页面。 1927 1928**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1929 1930**示例:** 1931 1932```ts 1933import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1934import { BusinessError } from '@ohos.base'; 1935let router: Router = uiContext.getRouter(); 1936router.clear(); 1937``` 1938 1939### getLength 1940 1941getLength(): string 1942 1943获取当前在页面栈内的页面数量。 1944 1945**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1946 1947**返回值:** 1948 1949| 类型 | 说明 | 1950| ------ | ------------------ | 1951| string | 页面数量,页面栈支持最大数值是32。 | 1952 1953**示例:** 1954 1955```ts 1956import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1957import { BusinessError } from '@ohos.base'; 1958let router: Router = uiContext.getRouter(); 1959let size = router.getLength(); 1960console.log('pages stack size = ' + size); 1961``` 1962 1963### getState 1964 1965getState(): router.RouterState 1966 1967获取当前页面的状态信息。 1968 1969**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1970 1971**返回值:** 1972 1973| 类型 | 说明 | 1974| ---------------------------------------- | ------- | 1975| [RouterState](js-apis-router.md#routerstate) | 页面状态信息。 | 1976 1977**示例:** 1978 1979```ts 1980import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 1981import { BusinessError } from '@ohos.base'; 1982let router: Router = uiContext.getRouter(); 1983let page = router.getState(); 1984console.log('current index = ' + page.index); 1985console.log('current name = ' + page.name); 1986console.log('current path = ' + page.path); 1987``` 1988 1989### showAlertBeforeBackPage 1990 1991showAlertBeforeBackPage(options: router.EnableAlertOptions): void 1992 1993开启页面返回询问对话框。 1994 1995**系统能力:** SystemCapability.ArkUI.ArkUI.Full 1996 1997**参数:** 1998 1999| 参数名 | 类型 | 必填 | 说明 | 2000| ------- | ---------------------------------------- | ---- | --------- | 2001| options | [router.EnableAlertOptions](js-apis-router.md#enablealertoptions) | 是 | 文本弹窗信息描述。 | 2002 2003**错误码:** 2004 2005以下错误码的详细介绍请参见[ohos.router(页面路由)](errorcode-router.md)错误码。 2006 2007| 错误码ID | 错误信息 | 2008| ------ | ---------------------------------- | 2009| 100001 | if UI execution context not found. | 2010 2011**示例:** 2012 2013```ts 2014import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 2015import { BusinessError } from '@ohos.base'; 2016let router: Router = uiContext.getRouter(); 2017try { 2018 router.showAlertBeforeBackPage({ 2019 message: 'Message Info' 2020 }); 2021} catch(error) { 2022 let message = (error as BusinessError).message; 2023 let code = (error as BusinessError).code; 2024 console.error(`showAlertBeforeBackPage failed, code is ${code}, message is ${message}`); 2025} 2026``` 2027 2028### hideAlertBeforeBackPage 2029 2030hideAlertBeforeBackPage(): void 2031 2032禁用页面返回询问对话框。 2033 2034**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2035 2036**示例:** 2037 2038```ts 2039import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 2040import { BusinessError } from '@ohos.base'; 2041let router: Router = uiContext.getRouter(); 2042router.hideAlertBeforeBackPage(); 2043``` 2044 2045### getParams 2046 2047getParams(): Object 2048 2049获取发起跳转的页面往当前页传入的参数。 2050 2051**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2052 2053**返回值:** 2054 2055| 类型 | 说明 | 2056| ------ | ----------------- | 2057| object | 发起跳转的页面往当前页传入的参数。 | 2058 2059**示例:** 2060 2061```ts 2062import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 2063import { BusinessError } from '@ohos.base'; 2064let router: Router = uiContext.getRouter(); 2065router.getParams(); 2066``` 2067 2068## PromptAction 2069 2070以下API需先使用UIContext中的[getPromptAction()](#getpromptaction)方法获取到PromptAction对象,再通过该对象调用对应方法。 2071 2072### showToast 2073 2074showToast(options: promptAction.ShowToastOptions): void 2075 2076创建并显示文本提示框。 2077 2078**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2079 2080**参数:** 2081 2082| 参数名 | 类型 | 必填 | 说明 | 2083| ------- | ---------------------------------------- | ---- | ------- | 2084| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | 是 | 文本弹窗选项。 | 2085 2086**错误码:** 2087 2088以下错误码的详细介绍请参见[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 2089 2090| 错误码ID | 错误信息 | 2091| ------ | ---------------------------------- | 2092| 100001 | if UI execution context not found. | 2093 2094**示例:** 2095 2096```ts 2097import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 2098import { BusinessError } from '@ohos.base'; 2099let promptAction: PromptAction = uiContext.getPromptAction(); 2100try { 2101 promptAction.showToast({ 2102 message: 'Message Info', 2103 duration: 2000 2104 }); 2105} catch (error) { 2106 let message = (error as BusinessError).message; 2107 let code = (error as BusinessError).code; 2108 console.error(`showToast args error code is ${code}, message is ${message}`); 2109}; 2110``` 2111 2112### showDialog 2113 2114showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse>): void 2115 2116创建并显示对话框,对话框响应结果异步返回。 2117 2118**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2119 2120**参数:** 2121 2122| 参数名 | 类型 | 必填 | 说明 | 2123| -------- | ---------------------------------------- | ---- | ------------ | 2124| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | 是 | 页面显示对话框信息描述。 | 2125| callback | AsyncCallback<[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | 是 | 对话框响应结果回调。 | 2126 2127**错误码:** 2128 2129以下错误码的详细介绍请参见[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 2130 2131| 错误码ID | 错误信息 | 2132| ------ | ---------------------------------- | 2133| 100001 | if UI execution context not found. | 2134 2135**示例:** 2136 2137```ts 2138import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 2139import { BusinessError } from '@ohos.base'; 2140class ButtonsModel { 2141 text: string = "" 2142 color: string = "" 2143} 2144let promptAction: PromptAction = uiContext.getPromptAction(); 2145try { 2146 promptAction.showDialog({ 2147 title: 'showDialog Title Info', 2148 message: 'Message Info', 2149 buttons: [ 2150 { 2151 text: 'button1', 2152 color: '#000000' 2153 } as ButtonsModel, 2154 { 2155 text: 'button2', 2156 color: '#000000' 2157 } as ButtonsModel 2158 ] 2159 }, (err, data) => { 2160 if (err) { 2161 console.info('showDialog err: ' + err); 2162 return; 2163 } 2164 console.info('showDialog success callback, click button: ' + data.index); 2165 }); 2166} catch (error) { 2167 let message = (error as BusinessError).message; 2168 let code = (error as BusinessError).code; 2169 console.error(`showDialog args error code is ${code}, message is ${message}`); 2170}; 2171``` 2172 2173### showDialog 2174 2175showDialog(options: promptAction.ShowDialogOptions): Promise<promptAction.ShowDialogSuccessResponse> 2176 2177创建并显示对话框,对话框响应后同步返回结果,通过Promise获取对话框响应结果。 2178 2179**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2180 2181**参数:** 2182 2183| 参数名 | 类型 | 必填 | 说明 | 2184| ------- | ---------------------------------------- | ---- | ------ | 2185| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | 是 | 对话框选项。 | 2186 2187**返回值:** 2188 2189| 类型 | 说明 | 2190| ---------------------------------------- | -------- | 2191| Promise<[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | 对话框响应结果。 | 2192 2193**错误码:** 2194 2195以下错误码的详细介绍请参见[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 2196 2197| 错误码ID | 错误信息 | 2198| ------ | ---------------------------------- | 2199| 100001 | if UI execution context not found. | 2200 2201**示例:** 2202 2203```ts 2204import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 2205import { BusinessError } from '@ohos.base'; 2206let promptAction: PromptAction = uiContext.getPromptAction(); 2207try { 2208 promptAction.showDialog({ 2209 title: 'Title Info', 2210 message: 'Message Info', 2211 buttons: [ 2212 { 2213 text: 'button1', 2214 color: '#000000' 2215 }, 2216 { 2217 text: 'button2', 2218 color: '#000000' 2219 } 2220 ], 2221 }) 2222 .then(data => { 2223 console.info('showDialog success, click button: ' + data.index); 2224 }) 2225 .catch((err:Error) => { 2226 console.info('showDialog error: ' + err); 2227 }) 2228} catch (error) { 2229 let message = (error as BusinessError).message; 2230 let code = (error as BusinessError).code; 2231 console.error(`showDialog args error code is ${code}, message is ${message}`); 2232}; 2233``` 2234 2235### showActionMenu<sup>11+</sup> 2236 2237showActionMenu(options: promptAction.ActionMenuOptions, callback: AsyncCallback<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)>):void 2238 2239创建并显示操作菜单,菜单响应结果异步返回。 2240 2241**系统能力:** SystemCapability.ArkUI.ArkUI.Full。 2242 2243**参数:** 2244 2245| 参数名 | 类型 | 必填 | 说明 | 2246| -------- | ------------------------------------------------------------ | ---- | ------------------ | 2247| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是 | 操作菜单选项。 | 2248| callback | AsyncCallback<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | 是 | 菜单响应结果回调。 | 2249 2250**错误码:** 2251 2252以下错误码的详细介绍请参见[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 2253 2254| 错误码ID | 错误信息 | 2255| -------- | ---------------------------------- | 2256| 100001 | if UI execution context not found. | 2257 2258**示例:** 2259 2260```ts 2261import { PromptAction } from '@ohos.arkui.UIContext'; 2262import promptAction from '@ohos.promptAction'; 2263import { BusinessError } from '@ohos.base'; 2264 2265let promptActionF: PromptAction = uiContext.getPromptAction(); 2266try { 2267 promptActionF.showActionMenu({ 2268 title: 'Title Info', 2269 buttons: [ 2270 { 2271 text: 'item1', 2272 color: '#666666' 2273 }, 2274 { 2275 text: 'item2', 2276 color: '#000000' 2277 } 2278 ] 2279 }, (err:BusinessError, data:promptAction.ActionMenuSuccessResponse) => { 2280 if (err) { 2281 console.info('showDialog err: ' + err); 2282 return; 2283 } 2284 console.info('showDialog success callback, click button: ' + data.index); 2285 }); 2286} catch (error) { 2287 let message = (error as BusinessError).message; 2288 let code = (error as BusinessError).code; 2289 console.error(`showActionMenu args error code is ${code}, message is ${message}`); 2290}; 2291``` 2292 2293### showActionMenu<sup>(deprecated)</sup> 2294 2295showActionMenu(options: promptAction.ActionMenuOptions, callback: [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)):void 2296 2297创建并显示操作菜单,菜单响应结果异步返回。 2298 2299从API version11开始不再维护,建议使用[showActionMenu](#showactionmenu11)。 2300 2301**系统能力:** SystemCapability.ArkUI.ArkUI.Full。 2302 2303**参数:** 2304 2305| 参数名 | 类型 | 必填 | 说明 | 2306| -------- | ------------------------------------------------------------ | ---- | ------------------ | 2307| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是 | 操作菜单选项。 | 2308| callback | [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse) | 是 | 菜单响应结果回调。 | 2309 2310**错误码:** 2311 2312以下错误码的详细介绍请参见[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 2313 2314| 错误码ID | 错误信息 | 2315| ------ | ---------------------------------- | 2316| 100001 | if UI execution context not found. | 2317 2318**示例:** 2319 2320```ts 2321import { PromptAction } from '@ohos.arkui.UIContext'; 2322import promptAction from '@ohos.promptAction'; 2323import { BusinessError } from '@ohos.base'; 2324 2325let promptActionF: PromptAction = uiContext.getPromptAction(); 2326try { 2327 promptActionF.showActionMenu({ 2328 title: 'Title Info', 2329 buttons: [ 2330 { 2331 text: 'item1', 2332 color: '#666666' 2333 }, 2334 { 2335 text: 'item2', 2336 color: '#000000' 2337 } 2338 ] 2339 }, { index:0 }); 2340} catch (error) { 2341 let message = (error as BusinessError).message; 2342 let code = (error as BusinessError).code; 2343 console.error(`showActionMenu args error code is ${code}, message is ${message}`); 2344}; 2345``` 2346 2347### showActionMenu 2348 2349showActionMenu(options: promptAction.ActionMenuOptions): Promise<promptAction.ActionMenuSuccessResponse> 2350 2351创建并显示操作菜单,通过Promise获取菜单响应结果。 2352 2353**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2354 2355**参数:** 2356 2357| 参数名 | 类型 | 必填 | 说明 | 2358| ------- | ---------------------------------------- | ---- | ------- | 2359| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是 | 操作菜单选项。 | 2360 2361**返回值:** 2362 2363| 类型 | 说明 | 2364| ---------------------------------------- | ------- | 2365| Promise<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | 菜单响应结果。 | 2366 2367**错误码:** 2368 2369以下错误码的详细介绍请参见[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。 2370 2371| 错误码ID | 错误信息 | 2372| ------ | ---------------------------------- | 2373| 100001 | if UI execution context not found. | 2374 2375**示例:** 2376 2377```ts 2378import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext'; 2379import { BusinessError } from '@ohos.base'; 2380let promptAction: PromptAction = uiContext.getPromptAction(); 2381try { 2382 promptAction.showActionMenu({ 2383 title: 'showActionMenu Title Info', 2384 buttons: [ 2385 { 2386 text: 'item1', 2387 color: '#666666' 2388 }, 2389 { 2390 text: 'item2', 2391 color: '#000000' 2392 }, 2393 ] 2394 }) 2395 .then(data => { 2396 console.info('showActionMenu success, click button: ' + data.index); 2397 }) 2398 .catch((err:Error) => { 2399 console.info('showActionMenu error: ' + err); 2400 }) 2401} catch (error) { 2402 let message = (error as BusinessError).message; 2403 let code = (error as BusinessError).code; 2404 console.error(`showActionMenu args error code is ${code}, message is ${message}`); 2405}; 2406``` 2407## DragController<sup>11+</sup> 2408以下API需先使用UIContext中的[getDragController()](js-apis-arkui-UIContext.md#getdragcontroller11)方法获取UIContext实例,再通过此实例调用对应方法。 2409 2410### executeDrag 2411 2412executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo, callback: AsyncCallback< {event: DragEvent, extraParams: string}>): void 2413 2414主动发起拖拽能力,传入拖拽发起后跟手效果所拖拽的对象以及携带拖拽信息。通过回调返回拖拽事件结果。 2415 2416**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2417 2418**参数:** 2419 2420| 参数名 | 类型 | 必填 | 说明 | 2421| -------- | ------------------------------------------------------------ | ---- | -------------------------------- | 2422| custom | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明) | 是 | 拖拽发起后跟手效果所拖拽的对象。 <br/> **说明:** <br/>不支持全局builder。如果builder中使用了[Image](arkui-ts/ts-basic-components-image.md)组件,应尽量开启同步加载,即配置Image的[syncLoad](arkui-ts/ts-basic-components-image.md#属性)为true。该builder只用于生成当次拖拽中显示的图片,builder的修改不会同步到当前正在拖拽的图片,对builder的修改需要在下一次拖拽时生效。 | 2423| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | 是 | 拖拽信息。 | 2424| callback | [AsyncCallback](../apis-basic-services-kit/js-apis-base.md#asynccallback)<{event: [DragEvent](arkui-ts/ts-universal-events-drag-drop.md#dragevent说明), extraParams: string}> | 是 | 拖拽结束返回结果的回调<br/>- event:拖拽事件信息,仅包括拖拽结果。<br/>- extraParams:拖拽事件额外信息。 | 2425 2426**错误码:** 2427 2428| 错误码ID | 错误信息 | 2429| -------- | ------------- | 2430| 100001 | if some internal handling failed. | 2431 2432**示例:** 2433 2434```ts 2435import dragController from "@ohos.arkui.dragController" 2436import UDC from '@ohos.data.unifiedDataChannel'; 2437 2438@Entry 2439@Component 2440struct DragControllerPage { 2441 @Builder DraggingBuilder() { 2442 Column() { 2443 Text("DraggingBuilder") 2444 } 2445 .width(100) 2446 .height(100) 2447 .backgroundColor(Color.Blue) 2448 } 2449 2450 build() { 2451 Column() { 2452 Button('touch to execute drag') 2453 .onTouch((event?:TouchEvent) => { 2454 if(event){ 2455 if (event.type == TouchType.Down) { 2456 let text = new UDC.Text() 2457 let unifiedData = new UDC.UnifiedData(text) 2458 2459 let dragInfo: dragController.DragInfo = { 2460 pointerId: 0, 2461 data: unifiedData, 2462 extraParams: '' 2463 } 2464 class tmp{ 2465 event:DragEvent|undefined = undefined 2466 extraParams:string = '' 2467 } 2468 let eve:tmp = new tmp() 2469 dragController.executeDrag(()=>{this.DraggingBuilder()}, dragInfo, (err, eve) => { 2470 if(eve.event){ 2471 if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) { 2472 // ... 2473 } else if (eve.event.getResult() == DragResult.DRAG_FAILED) { 2474 // ... 2475 } 2476 } 2477 }) 2478 } 2479 } 2480 }) 2481 } 2482 } 2483} 2484``` 2485 2486### executeDrag 2487 2488executeDrag(custom: CustomBuilder | DragItemInfo, dragInfo: dragController.DragInfo): Promise<{event: DragEvent, extraParams: string}> 2489 2490主动发起拖拽能力,传入拖拽发起后跟手效果所拖拽的对象以及携带拖拽信息。通过Promise返回拖拽事件结果。 2491 2492**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2493 2494**参数:** 2495 2496| 参数名 | 类型 | 必填 | 说明 | 2497| -------- | ------------------------------------------------------------ | ---- | -------------------------------- | 2498| custom | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明) | 是 | 拖拽发起后跟手效果所拖拽的对象。 | 2499| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | 是 | 拖拽信息。 | 2500 2501**返回值:** 2502 2503| 类型 | 说明 | 2504| ------------------------------------------------------ | ------------------ | 2505| Promise<{event: [DragEvent](arkui-ts/ts-universal-events-drag-drop.md#dragevent说明), extraParams: string}> | 拖拽结束返回结果的回调<br/>- event:拖拽事件信息,仅包括拖拽结果。<br/>- extraParams:拖拽事件额外信息。 | 2506 2507**错误码:** 2508 2509| 错误码ID | 错误信息 | 2510| -------- | ------------- | 2511| 100001 | if some internal handling failed. | 2512 2513**示例:** 2514 2515```ts 2516import dragController from "@ohos.arkui.dragController" 2517import componentSnapshot from '@ohos.arkui.componentSnapshot'; 2518import image from '@ohos.multimedia.image'; 2519import UDC from '@ohos.data.unifiedDataChannel'; 2520 2521@Entry 2522@Component 2523struct DragControllerPage { 2524 @State pixmap: image.PixelMap|null = null 2525 2526 @Builder DraggingBuilder() { 2527 Column() { 2528 Text("DraggingBuilder") 2529 } 2530 .width(100) 2531 .height(100) 2532 .backgroundColor(Color.Blue) 2533 } 2534 2535 @Builder PixmapBuilder() { 2536 Column() { 2537 Text("PixmapBuilder") 2538 } 2539 .width(100) 2540 .height(100) 2541 .backgroundColor(Color.Blue) 2542 } 2543 2544 build() { 2545 Column() { 2546 Button('touch to execute drag') 2547 .onTouch((event?:TouchEvent) => { 2548 if(event){ 2549 if (event.type == TouchType.Down) { 2550 let text = new UDC.Text() 2551 let unifiedData = new UDC.UnifiedData(text) 2552 2553 let dragInfo: dragController.DragInfo = { 2554 pointerId: 0, 2555 data: unifiedData, 2556 extraParams: '' 2557 } 2558 let pb:CustomBuilder = ():void=>{this.PixmapBuilder()} 2559 componentSnapshot.createFromBuilder(pb).then((pix: image.PixelMap) => { 2560 this.pixmap = pix; 2561 let dragItemInfo: DragItemInfo = { 2562 pixelMap: this.pixmap, 2563 builder: ()=>{this.DraggingBuilder()}, 2564 extraInfo: "DragItemInfoTest" 2565 } 2566 2567 class tmp{ 2568 event:DragResult|undefined = undefined 2569 extraParams:string = '' 2570 } 2571 let eve:tmp = new tmp() 2572 dragController.executeDrag(dragItemInfo, dragInfo) 2573 .then((eve) => { 2574 if (eve.event.getResult() == DragResult.DRAG_SUCCESSFUL) { 2575 // ... 2576 } else if (eve.event.getResult() == DragResult.DRAG_FAILED) { 2577 // ... 2578 } 2579 }) 2580 .catch((err:Error) => { 2581 }) 2582 }) 2583 } 2584 } 2585 }) 2586 } 2587 .width('100%') 2588 .height('100%') 2589 } 2590} 2591``` 2592 2593### createDragAction 2594 2595createDragAction(customArray: Array<CustomBuilder \| DragItemInfo>, dragInfo: dragController.DragInfo): dragController.DragAction 2596 2597创建拖拽的Action对象,需要显式指定拖拽背板图(可多个),以及拖拽的数据,跟手点等信息;当通过一个已创建的 Action 对象发起的拖拽未结束时,无法再次创建新的 Action 对象,接口会抛出异常。 2598 2599**说明:** 建议控制传递的拖拽背板数量,传递过多容易导致拖起的效率问题。 2600 2601**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2602 2603**参数:** 2604 2605| 参数名 | 类型 | 必填 | 说明 | 2606| -------- | ------------------------------------------------------------ | ---- | -------------------------------- | 2607| customArray | Array<[CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [DragItemInfo](arkui-ts/ts-universal-events-drag-drop.md#dragiteminfo说明)> | 是 | 拖拽发起后跟手效果所拖拽的对象。 | 2608| dragInfo | [dragController.DragInfo](js-apis-arkui-dragController.md#draginfo) | 是 | 拖拽信息。 | 2609 2610**返回值:** 2611 2612| 类型 | 说明 | 2613| ------------------------------------------------------ | ------------------ | 2614| [dragController.DragAction](js-apis-arkui-dragController.md#dragaction11)| 创建拖拽Action对象,主要用于后面实现注册监听拖拽状态改变事件和启动拖拽服务。 | 2615 2616**错误码:** 2617 2618| 错误码ID | 错误信息 | 2619| -------- | ------------- | 2620| 100001 | if some internal handling failed. | 2621 2622**示例:** 26231.在EntryAbility.ets中获取UI上下文并保存至LocalStorage中。 2624```ts 2625import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 2626import hilog from '@ohos.hilog'; 2627import UIAbility from '@ohos.app.ability.UIAbility'; 2628import Want from '@ohos.app.ability.Want'; 2629import window from '@ohos.window'; 2630import { UIContext } from '@ohos.arkui.UIContext'; 2631 2632let uiContext: UIContext; 2633let localStorage: LocalStorage = new LocalStorage('uiContext'); 2634 2635export default class EntryAbility extends UIAbility { 2636 storage: LocalStorage = localStorage; 2637 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 2638 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 2639 } 2640 2641 onDestroy(): void { 2642 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy'); 2643 } 2644 2645 onWindowStageCreate(windowStage: window.WindowStage): void { 2646 // Main window is created, set main page for this ability 2647 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 2648 2649 windowStage.loadContent('pages/Index', (err, data) => { 2650 if (err.code) { 2651 hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); 2652 return; 2653 } 2654 hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); 2655 windowStage.getMainWindow((err, data) => 2656 { 2657 if (err.code) { 2658 console.log('Failed to abtain the main window. Cause:' + err.message); 2659 return; 2660 } 2661 let windowClass: window.Window = data; 2662 uiContext = windowClass.getUIContext(); 2663 this.storage.setOrCreate<UIContext>('uiContext', uiContext); 2664 // 获取UIContext实例 2665 }) 2666 }); 2667 } 2668 2669 onWindowStageDestroy(): void { 2670 // Main window is destroyed, release UI related resources 2671 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); 2672 } 2673 2674 onForeground(): void { 2675 // Ability has brought to foreground 2676 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground'); 2677 } 2678 2679 onBackground(): void { 2680 // Ability has back to background 2681 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground'); 2682 } 2683} 2684``` 26852.通过LocalStorage.getShared()获取上下文,进而获取DragController对象实施后续操作。 2686```ts 2687import dragController from "@ohos.arkui.dragController" 2688import componentSnapshot from '@ohos.arkui.componentSnapshot'; 2689import image from '@ohos.multimedia.image'; 2690import UDC from '@ohos.data.unifiedDataChannel'; 2691import { UIContext, DragController } from '@ohos.arkui.UIContext' 2692 2693let storages = LocalStorage.getShared(); 2694 2695@Entry(storages) 2696@Component 2697struct DragControllerPage { 2698 @State pixmap: image.PixelMap|null = null 2699 private dragAction: dragController.DragAction|null = null; 2700 customBuilders:Array<CustomBuilder | DragItemInfo> = new Array<CustomBuilder | DragItemInfo>(); 2701 @Builder DraggingBuilder() { 2702 Column() { 2703 Text("DraggingBuilder") 2704 } 2705 .width(100) 2706 .height(100) 2707 .backgroundColor(Color.Blue) 2708 } 2709 2710 build() { 2711 Column() { 2712 2713 Column() { 2714 Text("测试") 2715 } 2716 .width(100) 2717 .height(100) 2718 .backgroundColor(Color.Red) 2719 2720 Button('多对象dragAction customBuilder拖拽').onTouch((event?:TouchEvent) => { 2721 if(event){ 2722 if (event.type == TouchType.Down) { 2723 console.log("muti drag Down by listener"); 2724 this.customBuilders.push(()=>{this.DraggingBuilder()}); 2725 this.customBuilders.push(()=>{this.DraggingBuilder()}); 2726 this.customBuilders.push(()=>{this.DraggingBuilder()}); 2727 let text = new UDC.Text() 2728 let unifiedData = new UDC.UnifiedData(text) 2729 let dragInfo: dragController.DragInfo = { 2730 pointerId: 0, 2731 data: unifiedData, 2732 extraParams: '' 2733 } 2734 try{ 2735 let uiContext: UIContext = storages.get<UIContext>('uiContext') as UIContext; 2736 this.dragAction = uiContext.getDragController().createDragAction(this.customBuilders, dragInfo) 2737 if(!this.dragAction){ 2738 console.log("listener dragAction is null"); 2739 return 2740 } 2741 this.dragAction.on('statusChange', (dragAndDropInfo)=>{ 2742 if (dragAndDropInfo.status == dragController.DragStatus.STARTED) { 2743 console.log("drag has start"); 2744 } else if (dragAndDropInfo.status == dragController.DragStatus.ENDED){ 2745 console.log("drag has end"); 2746 if (!this.dragAction) { 2747 return 2748 } 2749 this.customBuilders.splice(0, this.customBuilders.length) 2750 this.dragAction.off('statusChange') 2751 } 2752 }) 2753 this.dragAction.startDrag().then(()=>{}).catch((err:Error)=>{ 2754 console.log("start drag Error:" + err.message); 2755 }) 2756 } catch(err) { 2757 console.log("create dragAction Error:" + err.message); 2758 } 2759 } 2760 } 2761 }).margin({top:20}) 2762 } 2763 } 2764} 2765``` 2766 2767## AtomicServiceBar<sup>11+</sup> 2768 2769以下接口需要先使用UIContext中的[getAtomicServiceBar](#getatomicservicebar11)方法获取到AtomicServiceBar对象,再通过该对象调用对应方法。 2770 2771### setVisible<sup>11+</sup> 2772 2773setVisible(visible: boolean): void 2774 2775通过该方法设置原子化服务menuBar是否可见。 2776 2777**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2778 2779**参数:** 2780 2781| 参数名 | 类型 | 必填 | 说明 | 2782| ------- | ------- | ------- | ------- | 2783| visiable | boolean | 是 | 原子化服务menuBar是否可见。| 2784 2785 2786**示例:** 2787 2788```ts 2789import { UIContext, AtomicServiceBar } from '@ohos.arkui.UIContext'; 2790import hilog from '@ohos.hilog'; 2791import window from "@ohos.window"; 2792onWindowStageCreate(windowStage: window.WindowStage) { 2793 // Main window is created, set main page for this ability 2794 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 2795 windowStage.loadContent('pages/Index', (err, data) => { 2796 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 2797 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 2798 if (atomicServiceBar != undefined) { 2799 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 2800 atomicServiceBar.setVisible(false); 2801 } else { 2802 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 2803 } 2804 }); 2805} 2806``` 2807 2808### setBackgroundColor<sup>11+</sup> 2809 2810setBackgroundColor(color:Nullable<Color | number | string>): void 2811 2812通过该方法设置原子化服务menuBar的背景颜色。 2813 2814**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2815 2816**参数:** 2817 2818| 参数名 | 类型 | 必填 | 说明 | 2819| ------ | ------ | ------ | ------ | 2820| color | color:Nullable\<[Color](arkui-ts/ts-appendix-enums.md#color) \| number \| string> | 是 | 通过该方法设置原子化服务menuBar的背景颜色,undefined代表使用默认颜色。| 2821 2822**示例:** 2823 2824```ts 2825import { UIContext, AtomicServiceBar } from '@ohos.arkui.UIContext'; 2826import hilog from '@ohos.hilog'; 2827import window from "@ohos.window"; 2828onWindowStageCreate(windowStage: window.WindowStage) { 2829 // Main window is created, set main page for this ability 2830 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 2831 windowStage.loadContent('pages/Index', (err, data) => { 2832 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 2833 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 2834 if (atomicServiceBar != undefined) { 2835 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 2836 atomicServiceBar.setBackgroundColor(0x88888888); 2837 } else { 2838 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 2839 } 2840 }); 2841} 2842``` 2843 2844### setTitleContent<sup>11+</sup> 2845 2846setTitleContent(content:string): void 2847 2848通过该方法设置原子化服务menuBar的标题内容。 2849 2850**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2851 2852**参数:** 2853 2854|参数名|类型|必填|说明 | 2855| ------- | ------- | ------- | ------- | 2856| content | string | 是 | 原子化服务menuBar中的标题内容。| 2857 2858**示例:** 2859 2860```ts 2861import { UIContext, AtomicServiceBar } from '@ohos.arkui.UIContext'; 2862import hilog from '@ohos.hilog'; 2863import window from "@ohos.window"; 2864onWindowStageCreate(windowStage: window.WindowStage) { 2865 // Main window is created, set main page for this ability 2866 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 2867 windowStage.loadContent('pages/Index', (err, data) => { 2868 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 2869 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 2870 if (atomicServiceBar != undefined) { 2871 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 2872 atomicServiceBar.setTitleContent('text2'); 2873 } else { 2874 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 2875 } 2876 }); 2877} 2878``` 2879 2880### setTitleFontStyle<sup>11+</sup> 2881 2882setTitleFontStyle(font:FontStyle):void 2883 2884通过该方法设置原子化服务menuBar的字体样式。 2885 2886**系统能力:** SystemCapability.ArkUI.ArkUI.Full。 2887 2888**参数:** 2889 2890| 参数名 | 类型 | 必填 | 说明 | 2891| ------ | ------ | ------ | ------ | 2892| font | [FontStyle](arkui-ts/ts-appendix-enums.md#fontstyle) | 是 | 原子化服务menuBar中的字体样式。 | 2893 2894**示例:** 2895 2896```ts 2897import { UIContext, Font, AtomicServiceBar } from '@ohos.arkui.UIContext'; 2898import hilog from '@ohos.hilog'; 2899import window from "@ohos.window"; 2900onWindowStageCreate(windowStage: window.WindowStage) { 2901 // Main window is created, set main page for this ability 2902 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 2903 windowStage.loadContent('pages/Index', (err, data) => { 2904 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 2905 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 2906 if (atomicServiceBar != undefined) { 2907 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 2908 atomicServiceBar.setTitleFontStyle(FontStyle.Normal); 2909 } else { 2910 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 2911 } 2912 }); 2913} 2914``` 2915 2916### setIconColor<sup>11+</sup> 2917 2918setIconColor(color:Nullable<Color | number | string>): void 2919 2920通过该方法设置原子化服务图标的颜色。 2921 2922**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2923 2924**参数:** 2925 2926| 参数名 | 类型 | 必填 | 说明 | 2927| ------- | ------- | ------- | ------- | 2928| color | Nullable\<[Color](arkui-ts/ts-appendix-enums.md#color) \| number \| string> | 是 | 原子化服务图标的颜色,undefined代表使用默认颜色。 | 2929 2930 2931**示例:** 2932 2933```ts 2934import { UIContext, AtomicServiceBar } from '@ohos.arkui.UIContext'; 2935import hilog from '@ohos.hilog'; 2936import window from "@ohos.window"; 2937onWindowStageCreate(windowStage: window.WindowStage) { 2938 // Main window is created, set main page for this ability 2939 hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate'); 2940 windowStage.loadContent('pages/Index', (err, data) => { 2941 let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext(); 2942 let atomicServiceBar: Nullable<AtomicServiceBar> = uiContext.getAtomicServiceBar(); 2943 if (atomicServiceBar != undefined) { 2944 hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.'); 2945 atomicServiceBar.setIconColor(0x12345678); 2946 } else { 2947 hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.'); 2948 } 2949 }); 2950} 2951``` 2952## KeyboardAvoidMode<sup>11+</sup> 2953 2954配置键盘避让时页面的避让模式。 2955 2956**系统能力:** SystemCapability.ArkUI.ArkUI.Full 2957 2958| 名称 | 说明 | 2959| ------ | ---------- | 2960| OFFSET | 上抬模式。 | 2961| RESIZE | 压缩模式。 | 2962 2963