# @ohos.arkui.UIContext (UIContext)
在Stage模型中,WindowStage/Window可以通过[loadContent](js-apis-window.md#loadcontent9)接口加载页面并创建UI的实例,并将页面内容渲染到关联的窗口中,所以UI实例和窗口是一一关联的。一些全局的UI接口是和具体UI实例的执行上下文相关的,在当前接口调用时,通过追溯调用链跟踪到UI的上下文,来确定具体的UI实例。若在非UI页面中或者一些异步回调中调用这类接口,可能无法跟踪到当前UI的上下文,导致接口执行失败。
@ohos.window在API version 10 新增[getUIContext](js-apis-window.md#getuicontext10)接口,获取UI上下文实例UIContext对象,使用UIContext对象提供的替代方法,可以直接作用在对应的UI实例上。
> **说明:**
>
> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>
> 示例效果请以真机运行为准,当前DevEco Studio预览器不支持。
## UIContext
以下API需先使用ohos.window中的[getUIContext()](js-apis-window.md#getuicontext10)方法获取UIContext实例,再通过此实例调用对应方法。或者可以通过自定义组件内置方法[getUIContext()](arkui-ts/ts-custom-component-api.md#getuicontext)获取。本文中UIContext对象以uiContext表示。
### getFont
getFont(): Font
获取Font对象。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ------------- | ----------- |
| [Font](#font) | 返回Font实例对象。 |
**示例:**
```ts
uiContext.getFont();
```
### getComponentUtils
getComponentUtils(): ComponentUtils
获取ComponentUtils对象。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| --------------------------------- | --------------------- |
| [ComponentUtils](#componentutils) | 返回ComponentUtils实例对象。 |
**示例:**
```ts
uiContext.getComponentUtils();
```
### getUIInspector
getUIInspector(): UIInspector
获取UIInspector对象。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| --------------------------- | ------------------ |
| [UIInspector](#uiinspector) | 返回UIInspector实例对象。 |
**示例:**
```ts
uiContext.getUIInspector();
```
### getUIObserver11+
getUIObserver(): UIObserver
获取UIObserver对象。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| --------------------------- | ------------------ |
| [UIObserver](#uiobserver11) | 返回UIObserver实例对象。 |
**示例:**
```ts
uiContext.getUIObserver();
```
### getMediaQuery
getMediaQuery(): MediaQuery
获取MediaQuery对象。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ------------------------- | ----------------- |
| [MediaQuery](#mediaquery) | 返回MediaQuery实例对象。 |
**示例:**
```ts
uiContext.getMediaQuery();
```
### getRouter
getRouter(): Router
获取Router对象。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ----------------- | ------------- |
| [Router](#router) | 返回Router实例对象。 |
**示例:**
```ts
uiContext.getRouter();
```
### getPromptAction
getPromptAction(): PromptAction
获取PromptAction对象。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ----------------------------- | ------------------- |
| [PromptAction](#promptaction) | 返回PromptAction实例对象。 |
**示例:**
```ts
uiContext.getPromptAction();
```
### getOverlayManager12+
getOverlayManager(): OverlayManager
获取OverlayManager对象。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:**: SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ----------------------------- | ------------------- |
| [OverlayManager](#overlaymanager12) | 返回OverlayManager实例对象。 |
**示例:**
```ts
uiContext.getOverlayManager();
```
### setOverlayManagerOptions15+
setOverlayManagerOptions(options: OverlayManagerOptions): boolean
设置[OverlayManager](#overlaymanager12)参数。用于在使用OverlayManager能力之前先初始化overlayManager的参数,包括是否需要渲染overlay根节点等属性。该方法需要在执行getOverlayManager方法之前执行生效,且该方法只生效一次。
**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
**系统能力:**: SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ---------------------------------------- | ---- | ------------------------------------- |
| options | [OverlayManagerOptions](#overlaymanageroptions15) | 是 | OverlayManager参数。|
**返回值:**
| 类型 | 说明 |
| ------- | -------------- |
| boolean | 是否设置成功。
返回true时,设置成功。返回false时,设置失败。 |
**示例:**
```ts
uiContext.setOverlayManagerOptions({ renderRootOverlay: true });
```
### getOverlayManagerOptions15+
getOverlayManagerOptions(): OverlayManagerOptions
用于获取当前[OverlayManager](#overlaymanager12)参数。
**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
**系统能力:**: SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ----------------------------- | ------------------- |
| [OverlayManagerOptions](#overlaymanageroptions15) | 返回当前OverlayManagerOptions。 |
**示例:**
```ts
uiContext.getOverlayManagerOptions();
```
### animateTo
animateTo(value: AnimateParam, event: () => void): void
提供animateTo接口来指定由于闭包代码导致的状态变化插入过渡动效。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ---------------------------------------- | ---- | ------------------------------------- |
| value | [AnimateParam](arkui-ts/ts-explicit-animation.md#animateparam对象说明) | 是 | 设置动画效果相关参数。 |
| event | () => void | 是 | 指定显示动效的闭包函数,在闭包函数中导致的状态变化系统会自动插入过渡动画。 |
**示例:**
```ts
// xxx.ets
@Entry
@Component
struct AnimateToExample {
@State widthSize: number = 250
@State heightSize: number = 100
@State rotateAngle: number = 0
private flag: boolean = true
uiContext: UIContext | undefined = undefined;
aboutToAppear() {
this.uiContext = this.getUIContext();
if (!this.uiContext) {
console.warn("no uiContext");
return;
}
}
build() {
Column() {
Button('change size')
.width(this.widthSize)
.height(this.heightSize)
.margin(30)
.onClick(() => {
if (this.flag) {
this.uiContext?.animateTo({
duration: 2000,
curve: Curve.EaseOut,
iterations: 3,
playMode: PlayMode.Normal,
onFinish: () => {
console.info('play end')
}
}, () => {
this.widthSize = 150
this.heightSize = 60
})
} else {
this.uiContext?.animateTo({}, () => {
this.widthSize = 250
this.heightSize = 100
})
}
this.flag = !this.flag
})
Button('stop rotating')
.margin(50)
.rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
.onAppear(() => {
// 组件出现时开始做动画
this.uiContext?.animateTo({
duration: 1200,
curve: Curve.Friction,
delay: 500,
iterations: -1, // 设置-1表示动画无限循环
playMode: PlayMode.Alternate,
expectedFrameRateRange: {
min: 10,
max: 120,
expected: 60,
}
}, () => {
this.rotateAngle = 90
})
})
.onClick(() => {
this.uiContext?.animateTo({ duration: 0 }, () => {
// this.rotateAngle之前为90,在duration为0的动画中修改属性,可以停止该属性之前的动画,按新设置的属性显示
this.rotateAngle = 0
})
})
}.width('100%').margin({ top: 5 })
}
}
```
### getSharedLocalStorage12+
getSharedLocalStorage(): LocalStorage | undefined
获取当前stage共享的LocalStorage实例。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**模型约束:** 此接口仅可在Stage模型下使用。
**返回值:**
| 类型 | 描述 |
| ------------------------------ | ----------------- |
| [LocalStorage](arkui-ts/ts-state-management.md#localstorage9) \| undefined | 返回LocalStorage实例。共享的LocalStorage实例不存在时返回undefined。 |
**示例:**
```ts
// EntryAbility.ets
import { UIAbility } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
export default class EntryAbility extends UIAbility {
storage: LocalStorage = new LocalStorage();
onWindowStageCreate(windowStage: window.WindowStage) {
windowStage.loadContent('pages/Index', this.storage);
}
}
```
```ts
// Index.ets
@Entry
@Component
struct SharedLocalStorage {
localStorage = this.getUIContext().getSharedLocalStorage();
build() {
Row() {
Column() {
Button("Change Local Storage to 47")
.onClick(() => {
this.localStorage?.setOrCreate("propA", 47);
})
Button("Get Local Storage")
.onClick(() => {
console.info(`localStorage: ${this.localStorage?.get("propA")}`);
})
}
.width('100%')
}
.height('100%')
}
}
```
### getHostContext12+
getHostContext(): Context | undefined
获得当前元能力的Context。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**模型约束:** 此接口仅可在Stage模型下使用。
**返回值:**
| 类型 | 说明 |
| ------ | ------------------------------- |
| [Context](#context12) \| undefined | 返回当前组件所在Ability的Context,Context的具体类型为当前Ability关联的Context对象。例如:在UIAbility窗口中的页面调用该接口,返回类型为UIAbilityContext。在ExtensionAbility窗口中的页面调用该接口,返回类型为ExtensionContext。ability上下文不存在时返回undefined。 |
**示例:**
```ts
@Entry
@Component
struct Index {
uiContext = this.getUIContext();
build() {
Row() {
Column() {
Text("cacheDir='"+this.uiContext?.getHostContext()?.cacheDir+"'").fontSize(25)
Text("bundleCodeDir='"+this.uiContext?.getHostContext()?.bundleCodeDir+"'").fontSize(25)
}
.width('100%')
}
.height('100%')
}
}
```
### getFrameNodeById12+
getFrameNodeById(id: string): FrameNode | null
通过组件的id获取组件树的实体节点。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ---------------------------------------- | ---- | ------------------------------------- |
| id | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------------- |
| [FrameNode](js-apis-arkui-frameNode.md) \| null | 返回的组件树的实体节点或者空节点。 |
> **说明:**
>
> getFrameNodeById通过遍历查询对应id的节点,性能较差。推荐使用[getAttachedFrameNodeById](#getattachedframenodebyid12)。
**示例:**
```ts
uiContext.getFrameNodeById("TestNode")
```
### getAttachedFrameNodeById12+
getAttachedFrameNodeById(id: string): FrameNode | null
通过组件的id获取当前窗口上的实体节点。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ---------------------------------------- | ---- | ------------------------------------- |
| id | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------------- |
| [FrameNode](js-apis-arkui-frameNode.md) \| null | 返回的组件树的实体节点或者空节点。 |
> **说明:**
>
> getAttachedFrameNodeById仅能查询上屏节点。
**示例:**
```ts
uiContext.getAttachedFrameNodeById("TestNode")
```
### getFrameNodeByUniqueId12+
getFrameNodeByUniqueId(id: number): FrameNode | null
提供getFrameNodeByUniqueId接口通过组件的uniqueId获取组件树的实体节点。
1. 当uniqueId对应的是系统组件时,返回组件所对应的FrameNode;
2. 当uniqueId对应的是自定义组件时,若其有渲染内容,则返回该自定义组件的根节点,类型为__Common__;若其无渲染内容,则返回其第一个子组件的FrameNode。
3. 当uniqueId无对应的组件时,返回null。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ---------------------------------------- | ---- | ------------------------------------- |
| id | number | 是 | 节点对应的UniqueId |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------------- |
| [FrameNode](js-apis-arkui-frameNode.md) \| null | 返回的组件树的实体节点或者空节点。 |
**示例:**
```ts
import { UIContext, FrameNode } from '@kit.ArkUI';
@Entry
@Component
struct MyComponent {
aboutToAppear() {
let uniqueId: number = this.getUniqueId();
let uiContext: UIContext = this.getUIContext();
if (uiContext) {
let node: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId);
}
}
build() {
// ...
}
}
```
### getPageInfoByUniqueId12+
getPageInfoByUniqueId(id: number): PageInfo
提供getPageInfoByUniqueId接口通过组件的uniqueId获取该节点对应的Router和NavDestination页面信息。
1. 当uniqueId对应的节点在Page节点中,routerPageInfo属性为其对应的Router信息;
2. 当uniqueId对应的节点在NavDestination节点中,navDestinationInfo属性为其对应的NavDestination信息;
3. 当uniqueId对应的节点无对应的Router或NavDestination信息时,对应的属性为undefined;
4. 模态弹窗并不在任何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。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ---------------------------------------- | ---- | ------------------------------------- |
| id | number | 是 | 节点对应的UniqueId |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------------- |
| [PageInfo](#pageinfo12) | 返回节点对应的Router和NavDestination信息。 |
**示例:**
```ts
import { UIContext, PageInfo } from '@kit.ArkUI';
@Entry
@Component
struct PageInfoExample {
@Provide('pageInfos') pageInfos: NavPathStack = new NavPathStack();
build() {
Column() {
Navigation(this.pageInfos) {
NavDestination() {
MyComponent()
}
}.id('navigation')
}
}
}
@Component
struct MyComponent {
@State content: string = '';
build() {
Column() {
Text('PageInfoExample')
Button('click').onClick(() => {
const uiContext: UIContext = this.getUIContext();
const uniqueId: number = this.getUniqueId();
const pageInfo: PageInfo = uiContext.getPageInfoByUniqueId(uniqueId);
console.info('pageInfo: ' + JSON.stringify(pageInfo));
console.info('navigationInfo: ' + JSON.stringify(uiContext.getNavigationInfoByUniqueId(uniqueId)));
})
TextArea({
text: this.content
})
.width('100%')
.height(100)
}
.width('100%')
.alignItems(HorizontalAlign.Center)
}
}
```
### getNavigationInfoByUniqueId12+
getNavigationInfoByUniqueId(id: number): observer.NavigationInfo | undefined
提供getNavigationInfoByUniqueId接口通过组件的uniqueId获取该节点对应的Navigation页面信息。
1. 当uniqueId对应的节点在Navigation节点中,返回其对应的Navigation信息;
2. 当uniqueId对应的节点无对应的Navigation信息时,返回undefined。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ---------------------------------------- | ---- | ------------------------------------- |
| id | number | 是 | 节点对应的UniqueId |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------------- |
| observer.[NavigationInfo](js-apis-arkui-observer.md#navigationinfo12) \| undefined | 返回节点对应的Navigation信息。 |
**示例:**
请参考[getPageInfoByUniqueId](#getpageinfobyuniqueid12)的示例。
### showAlertDialog
showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions): void
显示警告弹窗组件,可设置文本内容与响应回调。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------------------- |
| 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组件。 |
**示例:**
```ts
uiContext.showAlertDialog(
{
title: 'title',
message: 'text',
autoCancel: true,
alignment: DialogAlignment.Bottom,
offset: { dx: 0, dy: -20 },
gridCount: 3,
confirm: {
value: 'button',
action: () => {
console.info('Button-clicking callback')
}
},
cancel: () => {
console.info('Closed callbacks')
}
}
)
```
### showActionSheet
showActionSheet(value: ActionSheetOptions): void
定义列表弹窗并弹出。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------------------------------------------------ | ---- | -------------------- |
| value | [ActionSheetOptions](arkui-ts/ts-methods-action-sheet.md#actionsheetoptions对象说明) | 是 | 配置列表弹窗的参数。 |
**示例:**
```ts
uiContext.showActionSheet({
title: 'ActionSheet title',
message: 'message',
autoCancel: true,
confirm: {
value: 'Confirm button',
action: () => {
console.info('Get Alert Dialog handled')
}
},
cancel: () => {
console.info('actionSheet canceled')
},
alignment: DialogAlignment.Bottom,
offset: { dx: 0, dy: -10 },
sheets: [
{
title: 'apples',
action: () => {
console.info('apples')
}
},
{
title: 'bananas',
action: () => {
console.info('bananas')
}
},
{
title: 'pears',
action: () => {
console.info('pears')
}
}
]
})
```
### showDatePickerDialog
showDatePickerDialog(options: DatePickerDialogOptions): void
定义日期滑动选择器弹窗并弹出。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------ |
| options | [DatePickerDialogOptions](arkui-ts/ts-methods-datepicker-dialog.md#datepickerdialogoptions对象说明) | 是 | 配置日期滑动选择器弹窗的参数。 |
**示例:**
```ts
let selectedDate: Date = new Date("2010-1-1")
uiContext.showDatePickerDialog({
start: new Date("2000-1-1"),
end: new Date("2100-12-31"),
selected: selectedDate,
onAccept: (value: DatePickerResult) => {
// 通过Date的setFullYear方法设置按下确定按钮时的日期,这样当弹窗再次弹出时显示选中的是上一次确定的日期
selectedDate.setFullYear(Number(value.year), Number(value.month), Number(value.day))
console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("DatePickerDialog:onCancel()")
},
onChange: (value: DatePickerResult) => {
console.info("DatePickerDialog:onChange()" + JSON.stringify(value))
}
})
```
### showTimePickerDialog
showTimePickerDialog(options: TimePickerDialogOptions): void
定义时间滑动选择器弹窗并弹出。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------ |
| options | [TimePickerDialogOptions](arkui-ts/ts-methods-timepicker-dialog.md#timepickerdialogoptions对象说明) | 是 | 配置时间滑动选择器弹窗的参数。 |
**示例:**
```ts
// xxx.ets
class SelectTime{
selectTime: Date = new Date('2020-12-25T08:30:00')
hours(h:number,m:number){
this.selectTime.setHours(h,m)
}
}
@Entry
@Component
struct TimePickerDialogExample {
@State selectTime: Date = new Date('2023-12-25T08:30:00');
build() {
Column() {
Button('showTimePickerDialog')
.margin(30)
.onClick(() => {
this.getUIContext().showTimePickerDialog({
selected: this.selectTime,
onAccept: (value: TimePickerResult) => {
// 设置selectTime为按下确定按钮时的时间,这样当弹窗再次弹出时显示选中的为上一次确定的时间
let time = new SelectTime()
if(value.hour&&value.minute){
time.hours(value.hour, value.minute)
}
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("TimePickerDialog:onCancel()")
},
onChange: (value: TimePickerResult) => {
console.info("TimePickerDialog:onChange()" + JSON.stringify(value))
}
})
})
}.width('100%').margin({ top: 5 })
}
}
```
### showTextPickerDialog
showTextPickerDialog(options: TextPickerDialogOptions): void
定义文本滑动选择器弹窗并弹出。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------ |
| options | [TextPickerDialogOptions](arkui-ts/ts-methods-textpicker-dialog.md#textpickerdialogoptions对象说明) | 是 | 配置文本滑动选择器弹窗的参数。 |
**示例:**
```ts
// xxx.ets
class SelectedValue{
select: number = 2
set(val:number){
this.select = val
}
}
class SelectedArray{
select: number[] = []
set(val:number[]){
this.select = val
}
}
@Entry
@Component
struct TextPickerDialogExample {
@State selectTime: Date = new Date('2023-12-25T08:30:00');
private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5']
private select : number = 0;
build() {
Column() {
Button('showTextPickerDialog')
.margin(30)
.onClick(() => {
this.getUIContext().showTextPickerDialog({
range: this.fruits,
selected: this.select,
onAccept: (value: TextPickerResult) => {
// 设置select为按下确定按钮时候的选中项index,这样当弹窗再次弹出时显示选中的是上一次确定的选项
let selectedVal = new SelectedValue()
let selectedArr = new SelectedArray()
if(value.index){
value.index instanceof Array?selectedArr.set(value.index) : selectedVal.set(value.index)
}
console.info("TextPickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("TextPickerDialog:onCancel()")
},
onChange: (value: TextPickerResult) => {
console.info("TextPickerDialog:onChange()" + JSON.stringify(value))
}
})
})
}.width('100%').margin({ top: 5 })
}
}
```
### createAnimator
createAnimator(options: AnimatorOptions): AnimatorResult
定义Animator类。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) | 是 | 定义动画选项。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------------- |
| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator结果接口。 |
**错误码**:
以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| ------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
**示例:**
```ts
// EntryAbility.ets
import { AnimatorOptions, window } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';
// used in UIAbility
onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
let uiContext = windowStage.getMainWindowSync().getUIContext();
let options:AnimatorOptions = {
duration: 1500,
easing: "friction",
delay: 0,
fill: "forwards",
direction: "normal",
iterations: 3,
begin: 200.0,
end: 400.0
};
uiContext.createAnimator(options);
});
}
```
### createAnimator18+
createAnimator(options: AnimatorOptions | SimpleAnimatorOptions): AnimatorResult
创建animator动画结果对象(AnimatorResult)。与[createAnimator](#createanimator)相比,新增对[SimpleAnimatorOptions](js-apis-animator.md#simpleanimatoroptions18)类型入参的支持。
**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| options | [AnimatorOptions](js-apis-animator.md#animatoroptions) \| [SimpleAnimatorOptions](js-apis-animator.md#simpleanimatoroptions18) | 是 | 定义动画选项。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------------- |
| [AnimatorResult](js-apis-animator.md#animatorresult) | Animator结果接口。 |
**错误码**:
以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| ------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
**示例:**
```ts
import { SimpleAnimatorOptions, window } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';
// used in UIAbility
onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
let uiContext = windowStage.getMainWindowSync().getUIContext();
let options: SimpleAnimatorOptions = new SimpleAnimatorOptions(100, 200).duration(2000);
uiContext.createAnimator(options);
});
}
```
### runScopedTask
runScopedTask(callback: () => void): void
在当前UI上下文执行传入的回调函数。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------- | ---- | ---- |
| callback | () => void | 是 | 回调函数 |
**示例:**
```ts
uiContext.runScopedTask(
() => {
console.info('Succeeded in runScopedTask');
}
);
```
### setKeyboardAvoidMode11+
setKeyboardAvoidMode(value: KeyboardAvoidMode): void
配置虚拟键盘弹出时,页面的避让模式。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------- | ---- | ---- |
| value | [KeyboardAvoidMode](#keyboardavoidmode11)| 是 | 键盘避让时的页面避让模式。
默认值:KeyboardAvoidMode.OFFSET |
**示例:**
```ts
// EntryAbility.ets
import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';
onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err, data) => {
let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext();
uiContext.setKeyboardAvoidMode(KeyboardAvoidMode.RESIZE);
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
});
}
```
### getKeyboardAvoidMode11+
getKeyboardAvoidMode(): KeyboardAvoidMode
获取虚拟键盘弹出时,页面的避让模式。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ---------- | ---- |
| [KeyboardAvoidMode](#keyboardavoidmode11)| 返回当前的页面避让模式。|
**示例:**
```ts
// EntryAbility.ets
import { KeyboardAvoidMode, UIContext } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';
onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err, data) => {
let uiContext :UIContext = windowStage.getMainWindowSync().getUIContext();
let KeyboardAvoidMode = uiContext.getKeyboardAvoidMode();
hilog.info(0x0000, "KeyboardAvoidMode:", JSON.stringify(KeyboardAvoidMode));
if (err.code) {
hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
});
}
```
### getAtomicServiceBar11+
getAtomicServiceBar(): Nullable\
获取AtomicServiceBar对象,通过该对象设置原子化服务menuBar的属性。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ------------------------------------------------- | ------------------------------------------------------------ |
| Nullable<[AtomicServiceBar](#atomicservicebar11)> | 如果是原子化服务则返回AtomicServerBar类型,否则返回undefined。 |
**示例:**
```ts
// EntryAbility.ets
import { UIContext, AtomicServiceBar, window } from '@kit.ArkUI';
import { hilog } from '@kit.PerformanceAnalysisKit';
onWindowStageCreate(windowStage: window.WindowStage) {
// Main window is created, set main page for this ability
hilog.info(0x0000, 'testTag', 'Ability onWindowStageCreate');
windowStage.loadContent('pages/Index', (err, data) => {
let uiContext: UIContext = windowStage.getMainWindowSync().getUIContext();
let atomicServiceBar: Nullable = uiContext.getAtomicServiceBar();
if (atomicServiceBar != undefined) {
hilog.info(0x0000, 'testTag', 'Get AtomServiceBar Successfully.');
} else {
hilog.error(0x0000, 'testTag', 'Get AtomicServiceBar failed.');
}
});
}
```
### getDragController11+
getDragController(): DragController
获取DragController对象,可通过该对象创建并发起拖拽。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
|类型|说明|
|----|----|
|[DragController](js-apis-arkui-dragController.md#dragController)| 获取DragController对象。|
**示例:**
```ts
uiContext.getDragController();
```
### keyframeAnimateTo11+
keyframeAnimateTo(param: KeyframeAnimateParam, keyframes: Array<KeyframeState>): void
产生关键帧动画。该接口的使用说明请参考[keyframeAnimateTo](arkui-ts/ts-keyframeAnimateTo.md)。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------------ | ---------------------------------------------------- | ------- | ---------------------------- |
| param | [KeyframeAnimateParam](arkui-ts/ts-keyframeAnimateTo.md#keyframeanimateparam对象说明) | 是 | 关键帧动画的整体动画参数。 |
| keyframes | Array<[KeyframeState](arkui-ts/ts-keyframeAnimateTo.md#keyframestate对象说明)> | 是 | 所有的关键帧状态。 |
### getFocusController12+
getFocusController(): FocusController
获取[FocusController](js-apis-arkui-UIContext.md#focuscontroller12)对象,可通过该对象控制焦点。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
|类型|说明|
|----|----|
|[FocusController](js-apis-arkui-UIContext.md#focuscontroller12)| 获取FocusController对象。|
**示例:**
```ts
uiContext.getFocusController();
```
### getFilteredInspectorTree12+
getFilteredInspectorTree(filters?: Array\): string
获取组件树及组件属性。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | --------------- | ---- | ------------------------------------------------------------ |
| filters | Array\ | 否 | 需要获取的组件属性的过滤列表。目前仅支持过滤字段:
"id":组件唯一标识。
"src":资源来源。
"content":元素、组件或对象所包含的信息或数据。
"editable":是否可编辑。
"scrollable":是否可滚动。
"selectable":是否可选择。
"focusable":是否可聚焦。
"focused":是否已聚焦。
其余字段仅供测试场景使用。 |
**返回值:**
| 类型 | 说明 |
| ------ | ---------------------------------- |
| string | 获取组件树及组件属性的JSON字符串。 |
**错误码**:
以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| ------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
**示例:**
```ts
uiContext.getFilteredInspectorTree(['id', 'src', 'content']);
```
### getFilteredInspectorTreeById12+
getFilteredInspectorTreeById(id: string, depth: number, filters?: Array\): string
获取指定的组件及其子组件的属性。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | --------------- | ---- | ------------------------------------------------------------ |
| id | string | 是 | 指定的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)id。 |
| depth | number | 是 | 获取子组件的层数。当取值0时,获取指定的组件及其所有的子孙组件的属性。当取值1时,仅获取指定的组件的属性。当取值2时,指定的组件及其1层子组件的属性。以此类推。 |
| filters | Array\ | 否 | 需要获取的组件属性的过滤列表。目前仅支持过滤字段:
"id":组件唯一标识。
"src":资源来源。
"content":元素、组件或对象所包含的信息或数据。
"editable":是否可编辑。
"scrollable":是否可滚动。
"selectable":是否可选择。
"focusable":是否可聚焦。
"focused":是否已聚焦。
其余字段仅供测试场景使用。 |
**返回值:**
| 类型 | 说明 |
| ------ | -------------------------------------------- |
| string | 获取指定的组件及其子组件的属性的JSON字符串。 |
**错误码**:
以下错误码详细介绍请参考[通用错误码](../errorcode-universal.md)。
| 错误码ID | 错误信息 |
| ------- | -------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
**示例:**
```ts
uiContext.getFilteredInspectorTreeById('testId', 0, ['id', 'src', 'content']);
```
### getCursorController12+
getCursorController(): CursorController
获取[CursorController](js-apis-arkui-UIContext.md#cursorcontroller12)对象,可通过该对象控制光标。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
|类型|说明|
|----|----|
|[CursorController](js-apis-arkui-UIContext.md#cursorcontroller12)| 获取CursorController对象。|
**示例:**
```ts
uiContext.CursorController();
```
### getContextMenuController12+
getContextMenuController(): ContextMenuController
获取[ContextMenuController](#contextmenucontroller12)对象,可通过该对象控制菜单。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
|类型|说明|
|----|----|
|[ContextMenuController](#contextmenucontroller12)| 获取ContextMenuController对象。|
**示例:**
```ts
uiContext.getContextMenuController();
```
### getMeasureUtils12+
getMeasureUtils(): MeasureUtils
允许用户通过UIContext对象,获取MeasureUtils对象进行文本计算。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ------ | -------------------------------------------- |
| [MeasureUtils](js-apis-arkui-UIContext.md#measureutils12) | 提供文本宽度、高度等相关计算。 |
**示例:**
```ts
uiContext.getMeasureUtils();
```
### getComponentSnapshot12+
getComponentSnapshot(): ComponentSnapshot
获取ComponentSnapshot对象,可通过该对象获取组件截图的能力。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ------------------------------------------------------------ | --------------------------- |
| [ComponentSnapshot](js-apis-arkui-UIContext.md#componentsnapshot12) | 获取ComponentSnapshot对象。 |
**示例:**
```ts
uiContext.getComponentSnapshot();
```
### vp2px12+
vp2px(value : number) : number
将vp单位的数值转换为以px为单位的数值。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------------------------------------- |
| value | number | 是 | 将vp单位的数值转换为以px为单位的数值。
取值范围:(-∞, +∞) |
**返回值:**
| 类型 | 说明 |
| ------ | -------------- |
| number | 转换后的数值。
取值范围:(-∞, +∞) |
**示例:**
```ts
uiContext.vp2px(200);
```
### px2vp12+
px2vp(value : number) : number
将px单位的数值转换为以vp为单位的数值。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------------------------------------- |
| value | number | 是 | 将px单位的数值转换为以vp为单位的数值。
取值范围:(-∞, +∞) |
**返回值:**
| 类型 | 说明 |
| ------ | -------------- |
| number | 转换后的数值。
取值范围:(-∞, +∞) |
**示例:**
```ts
uiContext.px2vp(200);
```
### fp2px12+
fp2px(value : number) : number
将fp单位的数值转换为以px为单位的数值。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------------------------------------- |
| value | number | 是 | 将fp单位的数值转换为以px为单位的数值。
取值范围:(-∞, +∞) |
**返回值:**
| 类型 | 说明 |
| ------ | -------------- |
| number | 转换后的数值。
取值范围:(-∞, +∞) |
**示例:**
```ts
uiContext.fp2px(200);
```
### px2fp12+
px2fp(value : number) : number
将px单位的数值转换为以fp为单位的数值。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | -------------------------------------- |
| value | number | 是 | 将px单位的数值转换为以fp为单位的数值。
取值范围:(-∞, +∞) |
**返回值:**
| 类型 | 说明 |
| ------ | -------------- |
| number | 转换后的数值。
取值范围:(-∞, +∞) |
**示例:**
```ts
uiContext.px2fp(200);
```
### lpx2px12+
lpx2px(value : number) : number
将lpx单位的数值转换为以px为单位的数值。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | --------------------------------------- |
| value | number | 是 | 将lpx单位的数值转换为以px为单位的数值。
取值范围:(-∞, +∞) |
**返回值:**
| 类型 | 说明 |
| ------ | -------------- |
| number | 转换后的数值。
取值范围:(-∞, +∞) |
**示例:**
```ts
uiContext.lpx2px(200);
```
### px2lpx12+
px2lpx(value : number) : number
将px单位的数值转换为以lpx为单位的数值。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | --------------------------------------- |
| value | number | 是 | 将px单位的数值转换为以lpx为单位的数值。
取值范围:(-∞, +∞) |
**返回值:**
| 类型 | 说明 |
| ------ | -------------- |
| number | 转换后的数值。
取值范围:(-∞, +∞) |
**示例:**
```ts
uiContext.px2lpx(200);
```
### getWindowName12+
getWindowName(): string | undefined
获取当前实例所在窗口的名称。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ------ | -------------------------------------------- |
| string \| undefined | 当前实例所在窗口的名称。若窗口不存在,则返回undefined。 |
**示例:**
```ts
import { window } from '@kit.ArkUI';
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
aboutToAppear() {
const windowName = this.getUIContext().getWindowName();
console.info('WindowName ' + windowName);
const currWindow = window.findWindow(windowName);
const windowProperties = currWindow.getWindowProperties();
console.info(`Window width ${windowProperties.windowRect.width}, height ${windowProperties.windowRect.height}`);
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
### getWindowWidthBreakpoint13+
getWindowWidthBreakpoint(): WidthBreakpoint
获取当前实例所在窗口的宽度断点枚举值。具体枚举值根据窗口宽度vp值确定,详见 [WidthBreakpoint](./arkui-ts/ts-appendix-enums.md#widthbreakpoint13)。
**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ------ | -------------------------------------------- |
| [WidthBreakpoint](./arkui-ts/ts-appendix-enums.md#widthbreakpoint13) | 当前实例所在窗口的宽度断点枚举值。若窗口宽度为 0vp,则返回WIDTH_XS。 |
**示例:**
```ts
import { UIContext } from '@kit.ArkUI';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
Button() {
Text('test')
.fontSize(30)
}
.onClick(() => {
let uiContext: UIContext = this.getUIContext();
let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint();
let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint();
console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`)
})
}
.width('100%')
}
.height('100%')
}
}
```
### getWindowHeightBreakpoint13+
getWindowHeightBreakpoint(): HeightBreakpoint
获取当前实例所在窗口的高度断点。具体枚举值根据窗口高宽比确定,详见 [HeightBreakpoint](./arkui-ts/ts-appendix-enums.md#heightbreakpoint13)。
**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ------ | -------------------------------------------- |
| [HeightBreakpoint](./arkui-ts/ts-appendix-enums.md#heightbreakpoint13) | 当前实例所在窗口的宽高比对应的高度断点枚举值。若窗口高宽比为0,则返回HEIGHT_SM。 |
**示例:**
```ts
import { UIContext } from '@kit.ArkUI';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
Button() {
Text('test')
.fontSize(30)
}
.onClick(() => {
let uiContext: UIContext = this.getUIContext();
let heightBp: HeightBreakpoint = uiContext.getWindowHeightBreakpoint();
let widthBp: WidthBreakpoint = uiContext.getWindowWidthBreakpoint();
console.info(`Window heightBP: ${heightBp}, widthBp: ${widthBp}`)
})
}
.width('100%')
}
.height('100%')
}
}
```
### postFrameCallback12+
postFrameCallback(frameCallback: FrameCallback): void
注册一个回调,仅在下一帧渲染时调用。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | --------------------------------------- |
| frameCallback | [FrameCallback](#framecallback12) | 是 | 下一帧需要执行的回调。 |
**示例:**
```ts
import {FrameCallback } from '@kit.ArkUI';
class MyFrameCallback extends FrameCallback {
private tag: string;
constructor(tag: string) {
super()
this.tag = tag;
}
onFrame(frameTimeNanos: number) {
console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString());
}
}
@Entry
@Component
struct Index {
build() {
Row() {
Button('点击触发postFrameCallback')
.onClick(() => {
this.getUIContext().postFrameCallback(new MyFrameCallback("normTask"));
})
}
}
}
```
### postDelayedFrameCallback12+
postDelayedFrameCallback(frameCallback: FrameCallback, delayTime: number): void
注册一个回调,在延迟一段时间后的下一帧进行渲染时执行。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | --------------------------------------- |
| frameCallback | [FrameCallback](#framecallback12) | 是 | 下一帧需要执行的回调。 |
| delayTime | number | 是 | 延迟的时间,以毫秒为单位。传入null、undefined或小于0的值,会按0处理。 |
**示例:**
```ts
import {FrameCallback } from '@kit.ArkUI';
class MyFrameCallback extends FrameCallback {
private tag: string;
constructor(tag: string) {
super()
this.tag = tag;
}
onFrame(frameTimeNanos: number) {
console.info('MyFrameCallback ' + this.tag + ' ' + frameTimeNanos.toString());
}
}
@Entry
@Component
struct Index {
build() {
Row() {
Button('点击触发postDelayedFrameCallback')
.onClick(() => {
this.getUIContext().postDelayedFrameCallback(new MyFrameCallback("delayTask"), 5);
})
}
}
}
```
### requireDynamicSyncScene12+
requireDynamicSyncScene(id: string): Array<DynamicSyncScene>
请求组件的动态帧率场景,用于自定义场景相关帧率配置。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | --------------------------------------- |
| id | string | 是 | 节点对应的[组件标识](arkui-ts/ts-universal-attributes-component-id.md)。|
**返回值:**
| 类型 | 说明 |
| ------ | -------------------------------------------- |
| Array<DynamicSyncScene> | 获取DynamicSyncScene对象数组。 |
**示例:**
```ts
uiContext.DynamicSyncScene("dynamicSyncScene")
```
### openBindSheet12+
openBindSheet\(bindSheetContent: ComponentContent\, sheetOptions?: SheetOptions, targetId?: number): Promise<void>
创建并弹出以bindSheetContent作为内容的半模态页面,使用Promise异步回调。通过该接口弹出的半模态页面样式完全按照bindSheetContent中设置的样式显示。
> **说明:**
>
> 1. 使用该接口时,若未传入有效的targetId,则不支持设置SheetOptions.preferType为POPUP模式、不支持设置SheetOptions.mode为EMBEDDED模式。
>
> 2. 由于[updateBindSheet](#updatebindsheet12)和[closeBindSheet](#closebindsheet12)依赖bindSheetContent去更新或者关闭指定的半模态页面,开发者需自行维护传入的bindSheetContent。
>
> 3. 不支持设置SheetOptions.UIContext。
>
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| bindSheetContent | [ComponentContent\](./js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 |
| sheetOptions | [SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions) | 否 | 半模态页面样式。
**说明:**
1. 不支持设置SheetOptions.uiContext,该属性的值固定为当前实例的UIContext。
2. 若不传递targetId,则不支持设置SheetOptions.preferType为POPUP样式,若设置了POPUP样式则使用CENTER样式替代。
3. 若不传递targetId,则不支持设置SheetOptions.mode为EMBEDDED模式,默认为OVERLAY模式。
4. 其余属性的默认值参考[SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions)文档。 |
| targetId | number | 否 | 需要绑定组件的ID,若不指定则不绑定任何组件。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| Promise<void> | 异常返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 120001 | The bindSheetContent is incorrect. |
| 120002 | The bindSheetContent already exists. |
| 120004 | The targetId does not exist. |
| 120005 | The node of targetId is not in the component tree. |
| 120006 | The node of targetId is not a child of the page node or NavDestination node. |
**示例:**
```ts
import { FrameNode, ComponentContent } from "@kit.ArkUI";
import { BusinessError } from '@kit.BasicServicesKit';
class Params {
text: string = ""
constructor(text: string) {
this.text = text;
}
}
let contentNode: ComponentContent;
let gUIContext: UIContext;
@Builder
function buildText(params: Params) {
Column() {
Text(params.text)
Button('Update BindSheet')
.fontSize(20)
.onClick(() => {
gUIContext.updateBindSheet(contentNode, {
backgroundColor: Color.Pink,
}, true)
.then(() => {
console.info('updateBindSheet success');
})
.catch((err: BusinessError) => {
console.info('updateBindSheet error: ' + err.code + ' ' + err.message);
})
})
Button('Close BindSheet')
.fontSize(20)
.onClick(() => {
gUIContext.closeBindSheet(contentNode)
.then(() => {
console.info('closeBindSheet success');
})
.catch((err: BusinessError) => {
console.info('closeBindSheet error: ' + err.code + ' ' + err.message);
})
})
}
}
@Entry
@Component
struct UIContextBindSheet {
@State message: string = 'BindSheet';
aboutToAppear() {
gUIContext = this.getUIContext();
contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message));
}
build() {
RelativeContainer() {
Column() {
Button('Open BindSheet')
.fontSize(20)
.onClick(() => {
let uiContext = this.getUIContext();
let uniqueId = this.getUniqueId();
let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId);
let targetId = frameNode?.getFirstChild()?.getUniqueId();
uiContext.openBindSheet(contentNode, {
height: SheetSize.MEDIUM,
backgroundColor: Color.Green,
title: { title: "Title", subtitle: "subtitle" }
}, targetId)
.then(() => {
console.info('openBindSheet success');
})
.catch((err: BusinessError) => {
console.info('openBindSheet error: ' + err.code + ' ' + err.message);
})
})
}
}
.height('100%')
.width('100%')
}
}
```
### updateBindSheet12+
updateBindSheet\(bindSheetContent: ComponentContent\, sheetOptions: SheetOptions, partialUpdate?: boolean ): Promise<void>
更新bindSheetContent对应的半模态页面的样式,使用Promise异步回调。
> **说明:**
>
> 不支持更新SheetOptions.UIContext、SheetOptions.mode、回调函数。
>
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| bindSheetContent | [ComponentContent\](./js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 |
| sheetOptions | [SheetOptions](arkui-ts/ts-universal-attributes-sheet-transition.md#sheetoptions) | 是 | 半模态页面样式。
**说明:**
不支持更新SheetOptions.uiContext、SheetOptions.mode、回调函数。 |
| partialUpdate | boolean | 否 | 半模态页面更新方式, 默认值为false。
**说明:**
1. true为增量更新,保留当前值,更新SheetOptions中的指定属性。
2. false为全量更新,除SheetOptions中的指定属性,其他属性恢复默认值。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| Promise<void> | 异常返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 120001 | The bindSheetContent is incorrect. |
| 120003 | The bindSheetContent cannot be found. |
**示例:**
```ts
import { FrameNode, ComponentContent } from "@kit.ArkUI";
import { BusinessError } from '@kit.BasicServicesKit';
class Params {
text: string = ""
constructor(text: string) {
this.text = text;
}
}
let contentNode: ComponentContent;
let gUIContext: UIContext;
@Builder
function buildText(params: Params) {
Column() {
Text(params.text)
Button('Update BindSheet')
.fontSize(20)
.onClick(() => {
gUIContext.updateBindSheet(contentNode, {
backgroundColor: Color.Pink,
}, true)
.then(() => {
console.info('updateBindSheet success');
})
.catch((err: BusinessError) => {
console.info('updateBindSheet error: ' + err.code + ' ' + err.message);
})
})
Button('Close BindSheet')
.fontSize(20)
.onClick(() => {
gUIContext.closeBindSheet(contentNode)
.then(() => {
console.info('closeBindSheet success');
})
.catch((err: BusinessError) => {
console.info('closeBindSheet error: ' + err.code + ' ' + err.message);
})
})
}
}
@Entry
@Component
struct UIContextBindSheet {
@State message: string = 'BindSheet';
aboutToAppear() {
gUIContext = this.getUIContext();
contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message));
}
build() {
RelativeContainer() {
Column() {
Button('Open BindSheet')
.fontSize(20)
.onClick(() => {
let uiContext = this.getUIContext();
let uniqueId = this.getUniqueId();
let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId);
let targetId = frameNode?.getFirstChild()?.getUniqueId();
uiContext.openBindSheet(contentNode, {
height: SheetSize.MEDIUM,
backgroundColor: Color.Green,
title: { title: "Title", subtitle: "subtitle" }
}, targetId)
.then(() => {
console.info('openBindSheet success');
})
.catch((err: BusinessError) => {
console.info('openBindSheet error: ' + err.code + ' ' + err.message);
})
})
}
}
.height('100%')
.width('100%')
}
}
```
### closeBindSheet12+
closeBindSheet\(bindSheetContent: ComponentContent\): Promise<void>
关闭bindSheetContent对应的半模态页面,使用Promise异步回调。
> **说明:**
>
> 使用此接口关闭半模态页面时,不会触发shouldDismiss回调。
>
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| bindSheetContent | [ComponentContent\](./js-apis-arkui-ComponentContent.md) | 是 | 半模态页面中显示的组件内容。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| Promise<void> | 异常返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[半模态错误码](errorcode-bindSheet.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 120001 | The bindSheetContent is incorrect. |
| 120003 | The bindSheetContent cannot be found. |
**示例:**
```ts
import { FrameNode, ComponentContent } from "@kit.ArkUI";
import { BusinessError } from '@kit.BasicServicesKit';
class Params {
text: string = ""
constructor(text: string) {
this.text = text;
}
}
let contentNode: ComponentContent;
let gUIContext: UIContext;
@Builder
function buildText(params: Params) {
Column() {
Text(params.text)
Button('Update BindSheet')
.fontSize(20)
.onClick(() => {
gUIContext.updateBindSheet(contentNode, {
backgroundColor: Color.Pink,
}, true)
.then(() => {
console.info('updateBindSheet success');
})
.catch((err: BusinessError) => {
console.info('updateBindSheet error: ' + err.code + ' ' + err.message);
})
})
Button('Close BindSheet')
.fontSize(20)
.onClick(() => {
gUIContext.closeBindSheet(contentNode)
.then(() => {
console.info('closeBindSheet success');
})
.catch((err: BusinessError) => {
console.info('closeBindSheet error: ' + err.code + ' ' + err.message);
})
})
}
}
@Entry
@Component
struct UIContextBindSheet {
@State message: string = 'BindSheet';
aboutToAppear() {
gUIContext = this.getUIContext();
contentNode = new ComponentContent(this.getUIContext(), wrapBuilder(buildText), new Params(this.message));
}
build() {
RelativeContainer() {
Column() {
Button('Open BindSheet')
.fontSize(20)
.onClick(() => {
let uiContext = this.getUIContext();
let uniqueId = this.getUniqueId();
let frameNode: FrameNode | null = uiContext.getFrameNodeByUniqueId(uniqueId);
let targetId = frameNode?.getFirstChild()?.getUniqueId();
uiContext.openBindSheet(contentNode, {
height: SheetSize.MEDIUM,
backgroundColor: Color.Green,
title: { title: "Title", subtitle: "subtitle" }
}, targetId)
.then(() => {
console.info('openBindSheet success');
})
.catch((err: BusinessError) => {
console.info('openBindSheet error: ' + err.code + ' ' + err.message);
})
})
}
}
.height('100%')
.width('100%')
}
}
```
### isFollowingSystemFontScale13+
isFollowingSystemFontScale(): boolean
获取当前UI上下文是否跟随系统字体倍率。
**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
|---------|---------------|
| boolean | 当前UI上下文是否跟随系统字体倍率。
true表示UI上下文跟随系统倍率,false表示UI上下文不跟随系统倍率。 |
**示例:**
```ts
uiContext.isFollowingSystemFontScale()
```
### getMaxFontScale13+
getMaxFontScale(): number
获取当前UI上下文最大字体倍率。
**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
|---------|-----------|
| number | 当前UI上下文最大字体倍率。 |
**示例:**
```ts
uiContext.getMaxFontScale()
```
### bindTabsToScrollable13+
bindTabsToScrollable(tabsController: TabsController, scroller: Scroller): void;
绑定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绑定。
> **说明:**
>
> 当多个可滚动容器组件绑定了同一个Tabs组件时,只要滑动任意一个可滚动容器组件,就会触发TabBar的显示或隐藏。且当任意一个可滚动容器组件滑动到底部时,会立即触发TabBar的显示动效。因此不建议同时触发多个可滚动容器组件的滑动。
**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 |
| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 |
**示例:**
```ts
@Entry
@Component
struct TabsExample {
private arr: string[] = []
private parentTabsController: TabsController = new TabsController()
private childTabsController: TabsController = new TabsController()
private listScroller: Scroller = new Scroller()
private parentScroller: Scroller = new Scroller()
private childScroller: Scroller = new Scroller()
aboutToAppear(): void {
for (let i = 0; i < 20; i++) {
this.arr.push(i.toString())
}
let context = this.getUIContext()
context.bindTabsToScrollable(this.parentTabsController, this.listScroller)
context.bindTabsToScrollable(this.childTabsController, this.listScroller)
context.bindTabsToNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller)
}
aboutToDisappear(): void {
let context = this.getUIContext()
context.unbindTabsFromScrollable(this.parentTabsController, this.listScroller)
context.unbindTabsFromScrollable(this.childTabsController, this.listScroller)
context.unbindTabsFromNestedScrollable(this.parentTabsController, this.parentScroller, this.childScroller)
}
build() {
Tabs({ barPosition: BarPosition.End, controller: this.parentTabsController }) {
TabContent() {
Tabs({ controller: this.childTabsController }) {
TabContent() {
List({ space: 20, initialIndex: 0, scroller: this.listScroller }) {
ForEach(this.arr, (item: string) => {
ListItem() {
Text(item)
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(Color.Gray)
}
}, (item: string) => item)
}
.scrollBar(BarState.Off)
.width('90%')
.height('100%')
.contentStartOffset(56)
.contentEndOffset(52)
}.tabBar(SubTabBarStyle.of('顶部页签'))
}
.width('100%')
.height('100%')
.barOverlap(true) // 使TabBar叠加在TabContent上,当TabBar向上或向下隐藏后,原位置处不为空白
.clip(true) // 对超出Tabs组件范围的子组件进行裁剪,防止TabBar向上或向下隐藏后误触TabBar
}.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), 'scroller联动多个TabsController'))
TabContent() {
Scroll(this.parentScroller) {
List({ space: 20, initialIndex: 0, scroller: this.childScroller }) {
ForEach(this.arr, (item: string) => {
ListItem() {
Text(item)
.width('100%')
.height(100)
.fontSize(16)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(Color.Gray)
}
}, (item: string) => item)
}
.scrollBar(BarState.Off)
.width('90%')
.height('100%')
.contentEndOffset(52)
.nestedScroll({ scrollForward: NestedScrollMode.SELF_FIRST, scrollBackward: NestedScrollMode.SELF_FIRST })
}
.width('100%')
.height('100%')
.scrollBar(BarState.Off)
.scrollable(ScrollDirection.Vertical)
.edgeEffect(EdgeEffect.Spring)
}.tabBar(BottomTabBarStyle.of($r('app.media.startIcon'), '嵌套的scroller联动TabsController'))
}
.width('100%')
.height('100%')
.barOverlap(true) // 使TabBar叠加在TabContent上,当TabBar向上或向下隐藏后,原位置处不为空白
.clip(true) // 对超出Tabs组件范围的子组件进行裁剪,防止TabBar向上或向下隐藏后误触TabBar
}
}
```

### unbindTabsFromScrollable13+
unbindTabsFromScrollable(tabsController: TabsController, scroller: Scroller): void;
解除Tabs组件和可滚动容器组件的绑定。
**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 |
| scroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 |
**示例:**
参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。
### bindTabsToNestedScrollable13+
bindTabsToNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void;
绑定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绑定。
**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 |
| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 |
| childScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。其对应组件为parentScroller对应组件的子组件,且组件间存在嵌套滚动关系。 |
**示例:**
参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。
### unbindTabsFromNestedScrollable13+
unbindTabsFromNestedScrollable(tabsController: TabsController, parentScroller: Scroller, childScroller: Scroller): void;
解除Tabs组件和嵌套的可滚动容器组件的绑定。
**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| tabsController | [TabsController](./arkui-ts/ts-container-tabs.md#tabscontroller) | 是 | Tabs组件的控制器。 |
| parentScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。 |
| childScroller | [Scroller](./arkui-ts/ts-container-scroll.md#scroller) | 是 | 可滚动容器组件的控制器。其对应组件为parentScroller对应组件的子组件,且组件间存在嵌套滚动关系。 |
**示例:**
参考[bindTabsToScrollable](#bindtabstoscrollable13)接口示例。
### enableSwipeBack18+
enableSwipeBack(enabled: Optional\): void
设置是否支持应用内横向滑动返回上一级。
**原子化服务API:** 从API Version 18 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Circle
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| enabled | boolean | 是 | 是否支持应用内横向滑动返回,默认值为true。|
**示例:**
```js
@Entry
@Component
struct Index {
@State isEnable: boolean = true;
build() {
RelativeContainer() {
Button(`enable swipe back: ${this.isEnable}`).onClick(() => {
this.isEnable = !this.isEnable;
this.getUIContext().enableSwipeBack(this.isEnable);
})
}
.height('100%')
.width('100%')
}
}
```
### getTextMenuController16+
getTextMenuController(): TextMenuController
获取[TextMenuController](#textmenucontroller16)对象,可通过该对象控制文本选择菜单。
**原子化服务API:** 从API Version 16 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
|类型|说明|
|----|----|
|[TextMenuController](#textmenucontroller16)| 获取TextMenuController对象。|
**示例:**
参考[TextMenuController](#textmenucontroller16)接口示例。
### createUIContextWithoutWindow17+
static createUIContextWithoutWindow(context: common.UIAbilityContext | common.ExtensionContext) : UIContext | undefined
创建一个不依赖窗口的UI实例,并返回其UI上下文。该接口所创建的UI实例是单例。
> **说明:**
>
> 返回的UI上下文只可用于创建[自定义节点](../../ui/arkts-user-defined-node.md),不能执行其他UI操作。
**原子化服务API:** 从API version 17 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ----------- |
| 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)所对应的上下文环境。 |
**返回值:**
|类型|说明|
|----|----|
| UIContext \| undefined | 创建的UI实例的上下文,创建失败时返回undefined。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[UI上下文](errorcode-uicontext.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes:
1. The number of parameters is incorrect.
2. Invalid parameter type of context. |
| 100001 | Internal error. |
**示例:**
```ts
import { UIContext } from '@kit.ArkUI';
export default class EntryAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
let uiContext : UIContext | undefined = UIContext.createUIContextWithoutWindow(this.context);
}
// ......
}
```
### destroyUIContextWithoutWindow17+
static destroyUIContextWithoutWindow(): void
销毁[createUIContextWithoutWindow](#createuicontextwithoutwindow17)创建的UI实例。
**原子化服务API:** 从API version 17 开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**示例:**
```ts
UIContext.destroyUIContextWithoutWindow();
```
### dispatchKeyEvent15+
dispatchKeyEvent(node: number | string, event: KeyEvent): boolean
按键事件应分发给指定的组件。为了确保行为的可预测性,目标组件必须位于分发组件的子树中。
**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ----------------------------- | ---- | ------------------ |
| node | number \| string | 是 | 组件的id或者节点UniqueID。 |
| event |[KeyEvent](./arkui-ts/ts-universal-events-key.md#keyevent对象说明) | 是 | KeyEvent对象。 |
**示例:**
```ts
@Entry
@Component
struct Index {
build() {
Row() {
Row() {
Button('Button1').id('Button1').onKeyEvent((event) => {
console.log("Button1");
return true
})
Button('Button2').id('Button2').onKeyEvent((event) => {
console.log("Button2");
return true
})
}
.width('100%')
.height('100%')
.id('Row1')
.onKeyEventDispatch((event) => {
let context = this.getUIContext();
context.getFocusController().requestFocus('Button1');
return context.dispatchKeyEvent('Button1', event);
})
}
.height('100%')
.width('100%')
.onKeyEventDispatch((event) => {
if (event.type == KeyType.Down) {
let context = this.getUIContext();
context.getFocusController().requestFocus('Row1');
return context.dispatchKeyEvent('Row1', event);
}
return true;
})
}
}
```
## Font
以下API需先使用UIContext中的[getFont()](#getfont)方法获取到Font对象,再通过该对象调用对应方法。
### registerFont
registerFont(options: font.FontOptions): void
在字体管理中注册自定义字体。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ----------- |
| options | [font.FontOptions](js-apis-font.md#fontoptions) | 是 | 注册的自定义字体信息。 |
**示例:**
```ts
import { Font } from '@kit.ArkUI';
let font:Font = uiContext.getFont();
font.registerFont({
familyName: 'medium',
familySrc: '/font/medium.ttf'
});
```
### getSystemFontList
getSystemFontList(): Array\
获取系统支持的字体名称列表。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| -------------- | --------- |
| Array\ | 系统的字体名列表。 |
> **说明:**
>
> 该接口仅在2in1设备上生效。
**示例:**
```ts
import { Font } from '@kit.ArkUI';
let font:Font|undefined = uiContext.getFont();
if(font){
font.getSystemFontList()
}
```
### getFontByName
getFontByName(fontName: string): font.FontInfo
根据传入的系统字体名称获取系统字体的相关信息。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | ------- |
| fontName | string | 是 | 系统的字体名。 |
**返回值:**
| 类型 | 说明 |
| ----------------------------------------- | -------------- |
| [font.FontInfo](js-apis-font.md#fontinfo) | 字体的详细信息 |
**示例:**
```ts
import { Font } from '@kit.ArkUI';
let font:Font|undefined = uiContext.getFont();
if(font){
font.getFontByName('Sans Italic')
}
```
## Context12+
type Context = common.Context
当前组件所在Ability的上下文。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.Ability.AbilityRuntime.Core
**模型约束:** 此接口仅可在Stage模型下使用。
| 类型 |说明 |
| ------ | ------------------- |
| [common.Context](../apis-ability-kit/js-apis-app-ability-common.md#context) |Context的具体类型为当前Ability关联的Context对象。|
## ComponentUtils
以下API需先使用UIContext中的[getComponentUtils()](#getcomponentutils)方法获取到ComponentUtils对象,再通过该对象调用对应方法。
### getRectangleById
getRectangleById(id: string): componentUtils.ComponentInfo
获取组件大小、位置、平移缩放旋转及仿射矩阵属性信息。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---- | ------ | ---- | --------- |
| id | string | 是 | 组件唯一标识id。 |
**返回值:**
| 类型 | 说明 |
| ------------------------------------------------------------ | ------------------------------------------------ |
| [componentUtils.ComponentInfo](js-apis-arkui-componentUtils.md#componentinfo) | 组件大小、位置、平移缩放旋转及仿射矩阵属性信息。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ------------------- |
| 100001 | UI execution context not found. |
**示例:**
```ts
import { ComponentUtils } from '@kit.ArkUI';
let componentUtils:ComponentUtils = uiContext.getComponentUtils();
let modePosition = componentUtils.getRectangleById("onClick");
let localOffsetWidth = modePosition.size.width;
let localOffsetHeight = modePosition.size.height;
```
## UIInspector
以下API需先使用UIContext中的[getUIInspector()](#getuiinspector)方法获取到UIInspector对象,再通过该对象调用对应方法。
### createComponentObserver
createComponentObserver(id: string): inspector.ComponentObserver
注册组件布局和组件绘制送显完成回调通知。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---- | ------ | ---- | ------- |
| id | string | 是 | 指定组件id,该id通过通用属性[id](./arkui-ts/ts-universal-attributes-component-id.md#id)或者[key](./arkui-ts/ts-universal-attributes-component-id.md#key12)设置。 |
**返回值:**
| 类型 | 说明 |
| ------------------------------------------------------------ | -------------------------------------------------- |
| [inspector.ComponentObserver](js-apis-arkui-inspector.md#componentobserver) | 组件回调事件监听句柄,用于注册和取消注册监听回调。 |
**示例:**
```ts
import { UIInspector } from '@kit.ArkUI';
let inspector: UIInspector = uiContext.getUIInspector();
let listener = inspector.createComponentObserver('COMPONENT_ID');
```
## PageInfo12+
Router和NavDestination等页面信息,若无对应的Router或NavDestination页面信息,则对应属性为undefined。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
| 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| routerPageInfo | observer.[RouterPageInfo](js-apis-arkui-observer.md#routerpageinfo) | 否 | Router信息。 |
| navDestinationInfo | observer.[NavDestinationInfo](js-apis-arkui-observer.md#navdestinationinfo) | 否 | NavDestination信息。 |
## UIObserver11+
以下API需先使用UIContext中的[getUIObserver()](#getuiobserver11)方法获取到UIObserver对象,再通过该对象调用对应方法。
### on('navDestinationUpdate')11+
on(type: 'navDestinationUpdate', callback: Callback\): void
监听NavDestination组件的状态变化。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 |
| callback | Callback\ | 是 | 回调函数。返回当前的NavDestination组件状态。 |
**示例:**
```ts
// Index.ets
// 演示 uiObserver.on('navDestinationUpdate', callback)
// uiObserver.off('navDestinationUpdate', callback)
@Component
struct PageOne {
build() {
NavDestination() {
Text("pageOne")
}.title("pageOne")
}
}
@Entry
@Component
struct Index {
private stack: NavPathStack = new NavPathStack();
@Builder
PageBuilder(name: string) {
PageOne()
}
aboutToAppear() {
this.getUIContext().getUIObserver().on('navDestinationUpdate', (info) => {
console.info('NavDestination state update', JSON.stringify(info));
});
}
aboutToDisappear() {
this.getUIContext().getUIObserver().off('navDestinationUpdate');
}
build() {
Column() {
Navigation(this.stack) {
Button("push").onClick(() => {
this.stack.pushPath({ name: "pageOne" });
})
}
.title("Navigation")
.navDestination(this.PageBuilder)
}
.width('100%')
.height('100%')
}
}
```
### off('navDestinationUpdate')11+
off(type: 'navDestinationUpdate', callback?: Callback\): void
取消监听NavDestination组件的状态变化。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 |
| callback | Callback\ | 否 | 回调函数。返回当前的NavDestination组件状态。 |
**示例:**
参考[uiObserver.on('navDestinationUpdate')](#onnavdestinationupdate11)示例。
### on('navDestinationUpdate')11+
on(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback: Callback\): void
监听NavDestination组件的状态变化。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 |
| options | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | 是 | 指定监听的Navigation的id。 |
| callback | Callback\ | 是 | 回调函数。返回当前的NavDestination组件状态。 |
**示例:**
```ts
// Index.ets
// 演示 uiObserver.on('navDestinationUpdate', navigationId, callback)
// uiObserver.off('navDestinationUpdate', navigationId, callback)
@Component
struct PageOne {
build() {
NavDestination() {
Text("pageOne")
}.title("pageOne")
}
}
@Entry
@Component
struct Index {
private stack: NavPathStack = new NavPathStack();
@Builder
PageBuilder(name: string) {
PageOne()
}
aboutToAppear() {
this.getUIContext().getUIObserver().on('navDestinationUpdate', { navigationId: "testId" }, (info) => {
console.info('NavDestination state update', JSON.stringify(info));
});
}
aboutToDisappear() {
this.getUIContext().getUIObserver().off('navDestinationUpdate', { navigationId: "testId" });
}
build() {
Column() {
Navigation(this.stack) {
Button("push").onClick(() => {
this.stack.pushPath({ name: "pageOne" });
})
}
.id("testId")
.title("Navigation")
.navDestination(this.PageBuilder)
}
.width('100%')
.height('100%')
}
}
```
### off('navDestinationUpdate')11+
off(type: 'navDestinationUpdate', options: { navigationId: ResourceStr }, callback?: Callback\): void
取消监听NavDestination组件的状态变化。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'navDestinationUpdate',即NavDestination组件的状态变化。 |
| options | { navigationId: [ResourceStr](arkui-ts/ts-types.md#resourcestr) } | 是 | 指定监听的Navigation的id。 |
| callback | Callback\ | 否 | 回调函数。返回当前的NavDestination组件状态。 |
**示例:**
参考[uiObserver.on('navDestinationUpdate')](#onnavdestinationupdate11-1)示例。
### on('scrollEvent')12+
on(type: 'scrollEvent', callback: Callback\): void
监听滚动事件的开始和结束。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 |
| callback | Callback\ | 是 | 回调函数。返回滚动事件的信息。 |
**示例:**
请参考[offscrollevent示例](#offscrollevent12-1)
### off('scrollEvent')12+
off(type: 'scrollEvent', callback?: Callback\): void
取消监听滚动事件的开始和结束。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 |
| callback | Callback\ | 否 | 回调函数。返回滚动事件的信息。 |
**示例:**
请参考[offscrollevent示例](#offscrollevent12-1)
### on('scrollEvent')12+
on(type: 'scrollEvent', options: observer.ObserverOptions, callback: Callback\): void
监听滚动事件的开始和结束。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 |
| options | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是 | Observer选项,包含指定监听的滚动组件的id。 |
| callback | Callback\ | 是 | 回调函数。返回滚动事件的信息。 |
**示例:**
请参考[offscrollevent示例](#offscrollevent12-1)
### off('scrollEvent')12+
off(type: 'scrollEvent', options: observer.ObserverOptions, callback?: Callback\): void
取消监听滚动事件的开始和结束。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'scrollEvent',即滚动事件的开始和结束。 |
| options | [observer.ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是 | Observer选项,包含指定监听的滚动组件的id。 |
| callback | Callback\ | 否 | 回调函数。返回滚动事件的信息。 |
**示例:**
```ts
import { UIObserver } from '@kit.ArkUI'
@Entry
@Component
struct Index {
scroller: Scroller = new Scroller()
observer: UIObserver = new UIObserver()
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7]
build() {
Row() {
Column() {
Scroll(this.scroller) {
Column() {
ForEach(this.arr, (item: number) => {
Text(item.toString())
.width('90%')
.height(150)
.backgroundColor(0xFFFFFF)
.borderRadius(15)
.fontSize(16)
.textAlign(TextAlign.Center)
.margin({ top: 10 })
}, (item: string) => item)
}.width('100%')
}
.id("testId")
.height('80%')
}
.width('100%')
Row() {
Button('UIObserver on')
.onClick(() => {
this.observer.on('scrollEvent', (info) => {
console.info('scrollEventInfo', JSON.stringify(info));
});
})
Button('UIObserver off')
.onClick(() => {
this.observer.off('scrollEvent');
})
}
Row() {
Button('UIObserverWithId on')
.onClick(() => {
this.observer.on('scrollEvent', { id:"testId" }, (info) => {
console.info('scrollEventInfo', JSON.stringify(info));
});
})
Button('UIObserverWithId off')
.onClick(() => {
this.observer.off('scrollEvent', { id:"testId" });
})
}
}
.height('100%')
}
}
```
### on('routerPageUpdate')11+
on(type: 'routerPageUpdate', callback: Callback\): void
监听router中page页面的状态变化。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'routerPageUpdate',即router中page页面的状态变化。 |
| callback | Callback\ | 是 | 回调函数。携带pageInfo,返回当前的page页面状态。 |
**示例:**
```ts
import { UIContext, UIObserver } from '@kit.ArkUI';
let observer:UIObserver = this.getUIContext().getUIObserver();
observer.on('routerPageUpdate', (info) => {
console.info('RouterPage state updated, called by ' + `${info.name}`);
});
```
### off('routerPageUpdate')11+
off(type: 'routerPageUpdate', callback?: Callback\): void
取消监听router中page页面的状态变化。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'routerPageUpdate',即router中page页面的状态变化。 |
| callback | Callback\ | 否 | 需要被注销的回调函数。 |
**示例:**
```ts
import { UIContext, UIObserver } from '@kit.ArkUI';
let observer:UIObserver = this.getUIContext().getUIObserver();
function callBackFunc(info:observer.RouterPageInfo) {};
// callBackFunc is defined and used before
observer.off('routerPageUpdate', callBackFunc);
```
### on('densityUpdate')12+
on(type: 'densityUpdate', callback: Callback\): void
监听屏幕像素密度变化。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'densityUpdate',即屏幕像素密度变化。 |
| callback | Callback\ | 是 | 回调函数。携带densityInfo,返回变化后的屏幕像素密度。 |
```ts
import { uiObserver } from '@kit.ArkUI';
@Entry
@Component
struct Index {
@State density: number = 0;
@State message: string = '未注册监听'
densityUpdateCallback = (info: uiObserver.DensityInfo) => {
this.density = info.density;
this.message = '变化后的DPI:' + this.density.toString();
}
build() {
Column() {
Text(this.message)
.fontSize(24)
.fontWeight(FontWeight.Bold)
Button('注册屏幕像素密度变化监听')
.onClick(() => {
this.message = '已注册监听'
this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback);
})
}
}
}
```
### off('densityUpdate')12+
off(type: 'densityUpdate', callback?: Callback\): void
取消监听屏幕像素密度的变化。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------------------------------------------------------- | ---- | -------------------------------------------------------------------------------------------- |
| type | string | 是 | 监听事件,固定为'densityUpdate',即屏幕像素密度变化。 |
| callback | Callback\ | 否 | 需要被注销的回调函数。若不指定具体的回调函数,则注销该UIContext下所有densityUpdate事件监听。 |
```ts
import { uiObserver } from '@kit.ArkUI';
@Entry
@Component
struct Index {
@State density: number = 0;
@State message: string = '未注册监听'
densityUpdateCallback = (info: uiObserver.DensityInfo) => {
this.density = info.density;
this.message = '变化后的DPI:' + this.density.toString();
}
build() {
Column() {
Text(this.message)
.fontSize(24)
.fontWeight(FontWeight.Bold)
Button('注册屏幕像素密度变化监听')
.margin({ bottom: 10 })
.onClick(() => {
this.message = '已注册监听'
this.getUIContext().getUIObserver().on('densityUpdate', this.densityUpdateCallback);
})
Button('解除注册屏幕像素密度变化监听')
.onClick(() => {
this.message = '未注册监听'
this.getUIContext().getUIObserver().off('densityUpdate', this.densityUpdateCallback);
})
}
}
}
```
### on('willDraw')12+
on(type: 'willDraw', callback: Callback\): void
监听每一帧绘制指令下发情况。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'willDraw',即是否将要绘制。 |
| callback | Callback\ | 是 | 回调函数。 |
```ts
import { uiObserver } from '@kit.ArkUI';
@Entry
@Component
struct Index {
willDrawCallback = () => {
console.info("willDraw指令下发");
}
build() {
Column() {
Button('注册绘制指令下发监听')
.onClick(() => {
this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback);
})
}
}
}
```
### off('willDraw')12+
off(type: 'willDraw', callback?: Callback\): void
取消监听每一帧绘制指令下发情况。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'willDraw',即是否将要绘制。 |
| callback | Callback\ | 否 | 需要被注销的回调函数。 |
```ts
import { uiObserver } from '@kit.ArkUI';
@Entry
@Component
struct Index {
willDrawCallback = () => {
console.info("willDraw指令下发")
}
build() {
Column() {
Button('注册绘制指令下发监听')
.margin({ bottom: 10 })
.onClick(() => {
this.getUIContext().getUIObserver().on('willDraw', this.willDrawCallback);
})
Button('解除注册绘制指令下发监听')
.onClick(() => {
this.getUIContext().getUIObserver().off('willDraw', this.willDrawCallback);
})
}
}
}
```
### on('didLayout')12+
on(type: 'didLayout', callback: Callback\): void
监听每一帧布局完成情况。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'didLayout',即是否布局完成。 |
| callback | Callback\ | 是 | 回调函数。 |
```ts
import { uiObserver } from '@kit.ArkUI';
@Entry
@Component
struct Index {
didLayoutCallback = () => {
console.info("layout布局完成");
}
build() {
Column() {
Button('注册布局完成监听')
.onClick(() => {
this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback);
})
}
}
}
```
### off('didLayout')12+
off(type: 'didLayout', callback?: Callback\): void
取消监听每一帧布局完成情况。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'didLayout',即是否将要绘制。 |
| callback | Callback\ | 否 | 需要被注销的回调函数。 |
```ts
import { uiObserver } from '@kit.ArkUI';
@Entry
@Component
struct Index {
didLayoutCallback = () => {
console.info("layout布局完成")
}
build() {
Column() {
Button('注册布局完成监听')
.margin({ bottom: 10 })
.onClick(() => {
this.getUIContext().getUIObserver().on('didLayout', this.didLayoutCallback);
})
Button('解除注册注册布局完成监听')
.onClick(() => {
this.getUIContext().getUIObserver().off('didLayout', this.didLayoutCallback);
})
}
}
}
```
### on('navDestinationSwitch')12+
on(type: 'navDestinationSwitch', callback: Callback\): void
监听Navigation的页面切换事件。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 |
| callback | Callback\ | 是 | 回调函数。携带NavDestinationSwitchInfo,返回页面切换事件的信息。 |
**示例:**
```ts
// Index.ets
// 演示 UIObserver.on('navDestinationSwitch', callback)
// UIObserver.off('navDestinationSwitch', callback)
import { uiObserver } from '@kit.ArkUI';
@Component
struct PageOne {
build() {
NavDestination() {
Text("pageOne")
}.title("pageOne")
}
}
function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) {
console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`)
}
@Entry
@Component
struct Index {
private stack: NavPathStack = new NavPathStack();
@Builder
PageBuilder(name: string) {
PageOne()
}
aboutToAppear() {
let obs = this.getUIContext().getUIObserver();
obs.on('navDestinationSwitch', callBackFunc);
}
aboutToDisappear() {
let obs = this.getUIContext().getUIObserver();
obs.off('navDestinationSwitch', callBackFunc);
}
build() {
Column() {
Navigation(this.stack) {
Button("push").onClick(() => {
this.stack.pushPath({name: "pageOne"});
})
}
.title("Navigation")
.navDestination(this.PageBuilder)
}
.width('100%')
.height('100%')
}
}
```
### off('navDestinationSwitch')12+
off(type: 'navDestinationSwitch', callback?: Callback\): void
取消监听Navigation的页面切换事件。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 |
| callback | Callback\ | 否 | 需要被注销的回调函数。 |
**示例代码参考上述UIObserver.on('navDestinationSwitch')接口的示例代码**
### on('navDestinationSwitch')12+
on(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback: Callback\): void
监听Navigation的页面切换事件。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 |
| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12) | 是 | 监听选项。 |
| callback | Callback\ | 是 | 回调函数。携带NavDestinationSwitchInfo,返回页面切换事件的信息。 |
**示例:**
```ts
// Index.ets
// 演示 UIObserver.on('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback)
// UIObserver.off('navDestinationSwitch', NavDestinationSwitchObserverOptions, callback)
import { uiObserver } from '@kit.ArkUI';
@Component
struct PageOne {
build() {
NavDestination() {
Text("pageOne")
}.title("pageOne")
}
}
function callBackFunc(info: uiObserver.NavDestinationSwitchInfo) {
console.info(`testTag navDestinationSwitch from: ${JSON.stringify(info.from)} to: ${JSON.stringify(info.to)}`)
}
@Entry
@Component
struct Index {
private stack: NavPathStack = new NavPathStack();
@Builder
PageBuilder(name: string) {
PageOne()
}
aboutToAppear() {
let obs = this.getUIContext().getUIObserver();
obs.on('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc)
}
aboutToDisappear() {
let obs = this.getUIContext().getUIObserver();
obs.off('navDestinationSwitch', { navigationId: "myNavId" }, callBackFunc)
}
build() {
Column() {
Navigation(this.stack) {
Button("push").onClick(() => {
this.stack.pushPath({name: "pageOne"});
})
}
.id("myNavId")
.title("Navigation")
.navDestination(this.PageBuilder)
}
.width('100%')
.height('100%')
}
}
```
### off('navDestinationSwitch')12+
off(type: 'navDestinationSwitch', observerOptions: observer.NavDestinationSwitchObserverOptions, callback?: Callback\): void
取消监听Navigation的页面切换事件。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'navDestinationSwitch',即Navigation的页面切换事件。 |
| observerOptions | observer.[NavDestinationSwitchObserverOptions](js-apis-arkui-observer.md#navdestinationswitchobserveroptions12) | 是 | 监听选项。 |
| callback | Callback\ | 否 | 需要被注销的回调函数。 |
**示例代码参考上述UIObserver.on('navDestinationSwitch')接口的示例代码**
### on('willClick')12+
on(type: 'willClick', callback: GestureEventListenerCallback): void
监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'willClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发前触发。 |
| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 是 | 回调函数。可以获得点击事件的GestureEvent和组件的FrameNode。 |
**示例:**
```ts
// 在页面Component中使用
import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
// callback是开发者定义的监听回调函数
let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
let observer: UIObserver = this.getUIContext().getUIObserver();
observer.on('willClick', callback);
```
### off('willClick')12+
off(type: 'willClick', callback?: GestureEventListenerCallback): void
取消监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
| type | string | 是 | 监听事件,固定为'willClick',即点击事件指令下发情况。 |
| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 否 | 需要被注销的回调函数。 |
**示例:**
```ts
// 在页面Component中使用
import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
// callback是开发者定义的监听回调函数
let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
let observer: UIObserver = this.getUIContext().getUIObserver();
observer.off('willClick', callback);
```
### on('didClick')12+
on(type: 'didClick', callback: GestureEventListenerCallback): void
监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'didClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发后触发。 |
| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 是 | 回调函数。可以获得点击事件的GestureEvent和组件的FrameNode。 |
**示例:**
```ts
// 在页面Component中使用
import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
// callback是开发者定义的监听回调函数
let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
let observer: UIObserver = this.getUIContext().getUIObserver();
observer.on('didClick', callback);
```
### off('didClick')12+
off(type: 'didClick', callback?: GestureEventListenerCallback): void
取消监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------- |
| type | string | 是 | 监听事件,固定为'didClick',即点击事件指令下发情况。 |
| callback | [GestureEventListenerCallback](#gestureeventlistenercallback12) | 否 | 需要被注销的回调函数。 |
**示例:**
```ts
// 在页面Component中使用
import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
// callback是开发者定义的监听回调函数
let callback = (event: GestureEvent, frameNode?: FrameNode) => {};
let observer: UIObserver = this.getUIContext().getUIObserver();
observer.off('didClick', callback);
```
### on('willClick')12+
on(type: 'willClick', callback: ClickEventListenerCallback): void
监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'willClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发前触发。 |
| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 是 | 回调函数。可以获得点击事件的ClickEvent和组件的FrameNode。 |
**示例:**
```ts
// 在页面Component中使用
import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
// callback是开发者定义的监听回调函数
let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
let observer: UIObserver = this.getUIContext().getUIObserver();
observer.on('willClick', callback);
```
### off('willClick')12+
off(type: 'willClick', callback?: ClickEventListenerCallback): void
取消监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------------- | ---- | ----------------------------------------------------- |
| type | string | 是 | 监听事件,固定为'willClick',即点击事件指令下发情况。 |
| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 否 | 需要被注销的回调函数。 |
**示例:**
```ts
// 在页面Component中使用
import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
// callback是开发者定义的监听回调函数
let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
let observer: UIObserver = this.getUIContext().getUIObserver();
observer.off('willClick', callback);
```
### on('didClick')12+
on(type: 'didClick', callback: ClickEventListenerCallback): void
监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'didClick',用于监听点击事件指令下发情况,所注册回调将于点击事件触发后触发。 |
| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 是 | 回调函数。可以获得点击事件的ClickEvent和组件的FrameNode。 |
**示例:**
```ts
// 在页面Component中使用
import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
// callback是开发者定义的监听回调函数
let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
let observer: UIObserver = this.getUIContext().getUIObserver();
observer.on('didClick', callback);
```
### off('didClick')12+
off(type: 'didClick', callback?: ClickEventListenerCallback): void
取消监听点击事件指令下发情况。暂不支持屏幕朗读触控模式。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------------------- | ---- | ---------------------------------------------------- |
| type | string | 是 | 监听事件,固定为'didClick',即点击事件指令下发情况。 |
| callback | [ClickEventListenerCallback](#clickeventlistenercallback12) | 否 | 需要被注销的回调函数。 |
**示例:**
```ts
// 在页面Component中使用
import { UIContext, UIObserver, FrameNode } from '@kit.ArkUI';
// callback是开发者定义的监听回调函数
let callback = (event: ClickEvent, frameNode?: FrameNode) => {};
let observer: UIObserver = this.getUIContext().getUIObserver();
observer.off('didClick', callback);
```
### on('tabContentUpdate')12+
on(type: 'tabContentUpdate', callback: Callback\): void
监听TabContent页面的切换事件。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 |
| callback | Callback\ | 是 | 回调函数。携带TabContentInfo,返回TabContent页面切换事件的信息。 |
**示例:**
```ts
import { uiObserver } from '@kit.ArkUI';
function callbackFunc(info: uiObserver.TabContentInfo) {
console.info('tabContentUpdate', JSON.stringify(info));
}
@Entry
@Component
struct TabsExample {
aboutToAppear(): void {
let observer = this.getUIContext().getUIObserver();
observer.on('tabContentUpdate', callbackFunc);
}
aboutToDisappear(): void {
let observer = this.getUIContext().getUIObserver();
observer.off('tabContentUpdate', callbackFunc);
}
build() {
Column() {
Tabs() {
TabContent() {
Column().width('100%').height('100%').backgroundColor('#00CB87')
}.tabBar('green').id('tabContentId0')
TabContent() {
Column().width('100%').height('100%').backgroundColor('#007DFF')
}.tabBar('blue').id('tabContentId1')
TabContent() {
Column().width('100%').height('100%').backgroundColor('#FFBF00')
}.tabBar('yellow').id('tabContentId2')
TabContent() {
Column().width('100%').height('100%').backgroundColor('#E67C92')
}.tabBar('pink').id('tabContentId3')
}
.width(360)
.height(296)
.backgroundColor('#F1F3F5')
.id('tabsId')
}.width('100%')
}
}
```
### off('tabContentUpdate')12+
off(type: 'tabContentUpdate', callback?: Callback\): void
取消监听TabContent页面的切换事件。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 |
| callback | Callback\ | 否 | 需要被注销的回调函数。 |
**示例:**
参考[on('tabContentUpdate')](#ontabcontentupdate12)接口示例。
### on('tabContentUpdate')12+
on(type: 'tabContentUpdate', options: observer.ObserverOptions, callback: Callback\): void
监听TabContent页面的切换事件。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 |
| options | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是 | 指定监听的Tabs组件的id。 |
| callback | Callback\ | 是 | 回调函数。携带TabContentInfo,返回TabContent页面切换事件的信息。 |
**示例:**
```ts
import { uiObserver } from '@kit.ArkUI';
function callbackFunc(info: uiObserver.TabContentInfo) {
console.info('tabContentUpdate', JSON.stringify(info));
}
@Entry
@Component
struct TabsExample {
aboutToAppear(): void {
let observer = this.getUIContext().getUIObserver();
observer.on('tabContentUpdate', { id: 'tabsId' }, callbackFunc);
}
aboutToDisappear(): void {
let observer = this.getUIContext().getUIObserver();
observer.off('tabContentUpdate', { id: 'tabsId' }, callbackFunc);
}
build() {
Column() {
Tabs() {
TabContent() {
Column().width('100%').height('100%').backgroundColor('#00CB87')
}.tabBar('green').id('tabContentId0')
TabContent() {
Column().width('100%').height('100%').backgroundColor('#007DFF')
}.tabBar('blue').id('tabContentId1')
TabContent() {
Column().width('100%').height('100%').backgroundColor('#FFBF00')
}.tabBar('yellow').id('tabContentId2')
TabContent() {
Column().width('100%').height('100%').backgroundColor('#E67C92')
}.tabBar('pink').id('tabContentId3')
}
.width(360)
.height(296)
.backgroundColor('#F1F3F5')
.id('tabsId')
}.width('100%')
}
}
```
### off('tabContentUpdate')12+
off(type: 'tabContentUpdate', options: observer.ObserverOptions, callback?: Callback\): void
取消监听TabContent页面的切换事件。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'tabContentUpdate',即TabContent页面的切换事件。 |
| options | observer.[ObserverOptions](js-apis-arkui-observer.md#observeroptions12) | 是 | 指定监听的Tabs组件的id。 |
| callback | Callback\ | 否 | 需要被注销的回调函数。 |
**示例:**
参考[on('tabContentUpdate')](#ontabcontentupdate12-1)接口示例。
## GestureEventListenerCallback12+
type GestureEventListenerCallback = (event: GestureEvent, node?: FrameNode) => void
ArkTS GestureEvent事件监听函数类型。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | --------------------------- |
| event | [GestureEvent](../apis-arkui/arkui-ts/ts-gesture-settings.md#gestureevent对象说明) | 是 | 触发事件监听的手势事件的相关信息。 |
| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | 否 | 触发事件监听的手势事件所绑定的组件。 |
## ClickEventListenerCallback12+
type ClickEventListenerCallback = (event: ClickEvent, node?: FrameNode) => void
ArkTS GestureEvent事件监听函数类型。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | --------------------------- |
| event | [ClickEvent](../apis-arkui/arkui-ts/ts-universal-events-click.md#clickevent对象说明) | 是 | 触发事件监听的点击事件的相关信息。 |
| node | [FrameNode](js-apis-arkui-frameNode.md#framenode) | 否 | 触发事件监听的点击事件所绑定的组件。 |
## MediaQuery
以下API需先使用UIContext中的[getMediaQuery()](#getmediaquery)方法获取到MediaQuery对象,再通过该对象调用对应方法。
### matchMediaSync
matchMediaSync(condition: string): mediaQuery.MediaQueryListener
设置媒体查询的查询条件,并返回对应的监听句柄。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | ---------------------------------------- |
| condition | string | 是 | 媒体事件的匹配条件,具体可参考[媒体查询语法规则](../../ui/arkts-layout-development-media-query.md#语法规则)。 |
**返回值:**
| 类型 | 说明 |
| ------------------------------------------------------------ | -------------------------------------------- |
| [mediaQuery.MediaQueryListener](js-apis-mediaquery.md#mediaquerylistener) | 媒体事件监听句柄,用于注册和去注册监听回调。 |
**示例:**
```ts
import { MediaQuery } from '@kit.ArkUI';
let mediaquery: MediaQuery = uiContext.getMediaQuery();
let listener = mediaquery.matchMediaSync('(orientation: landscape)'); //监听横屏事件
```
## Router
以下API需先使用UIContext中的[getRouter()](#getrouter)方法获取到Router对象,再通过该对象调用对应方法。
### pushUrl
pushUrl(options: router.RouterOptions): Promise<void>
跳转到应用内的指定页面,通过Promise获取跳转异常的返回结果。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | --------- |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ------- |
| Promise<void> | 异常返回结果。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. |
| 100003 | Page stack error. Too many pages are pushed. |
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit'
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().pushUrl({
url: 'pages/routerpage2',
params: {
data1: 'message',
data2: {
data3: [123, 456, 789]
}
}
})
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### pushUrl
pushUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void
跳转到应用内的指定页面。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | --------- |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 |
| callback | AsyncCallback<void> | 是 | 异常响应回调。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. |
| 100003 | Page stack error. Too many pages are pushed. |
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit'
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().pushUrl({
url: 'pages/routerpage2',
params: {
data1: 'message',
data2: {
data3: [123, 456, 789]
}
}
}, (err: Error) => {
if (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`pushUrl failed, code is ${code}, message is ${message}`);
return;
}
console.info('pushUrl success');
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### pushUrl
pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void>
跳转到应用内的指定页面,通过Promise获取跳转异常的返回结果。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ---------- |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 |
| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ------- |
| Promise<void> | 异常返回结果。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. |
| 100003 | Page stack error. Too many pages are pushed. |
**示例:**
```ts
import { router } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit'
class RouterTmp {
Standard: router.RouterMode = router.RouterMode.Standard
}
let rtm: RouterTmp = new RouterTmp()
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().pushUrl({
url: 'pages/routerpage2',
params: {
data1: 'message',
data2: {
data3: [123, 456, 789]
}
}
}, rtm.Standard)
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### pushUrl
pushUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void
跳转到应用内的指定页面。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ---------- |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 跳转页面描述信息。 |
| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 |
| callback | AsyncCallback<void> | 是 | 异常响应回调。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
| 100002 | Uri error. The URI of the page to redirect is incorrect or does not exist. |
| 100003 | Page stack error. Too many pages are pushed. |
**示例:**
```ts
import { router } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit'
class RouterTmp {
Standard: router.RouterMode = router.RouterMode.Standard
}
let rtm: RouterTmp = new RouterTmp()
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().pushUrl({
url: 'pages/routerpage2',
params: {
data1: 'message',
data2: {
data3: [123, 456, 789]
}
}
}, rtm.Standard, (err) => {
if (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`pushUrl failed, code is ${code}, message is ${message}`);
return;
}
console.info('pushUrl success');
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### replaceUrl
replaceUrl(options: router.RouterOptions): Promise<void>
用应用内的某个页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回的结果。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | --------- |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ------- |
| Promise<void> | 异常返回结果。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. |
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit'
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().replaceUrl({
url: 'pages/detail',
params: {
data1: 'message'
}
})
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### replaceUrl
replaceUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void
用应用内的某个页面替换当前页面,并销毁被替换的页面。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | --------- |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 |
| callback | AsyncCallback<void> | 是 | 异常响应回调。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. |
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit'
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().replaceUrl({
url: 'pages/detail',
params: {
data1: 'message'
}
}, (err: Error) => {
if (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`replaceUrl failed, code is ${code}, message is ${message}`);
return;
}
console.info('replaceUrl success');
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### replaceUrl
replaceUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void>
用应用内的某个页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ---------- |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 |
| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ------- |
| Promise<void> | 异常返回结果。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. |
| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. |
**示例:**
```ts
import { router } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit'
class RouterTmp {
Standard: router.RouterMode = router.RouterMode.Standard
}
let rtm: RouterTmp = new RouterTmp()
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().replaceUrl({
url: 'pages/detail',
params: {
data1: 'message'
}
}, rtm.Standard)
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### replaceUrl
replaceUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void
用应用内的某个页面替换当前页面,并销毁被替换的页面。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ---------- |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 替换页面描述信息。 |
| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 |
| callback | AsyncCallback<void> | 是 | 异常响应回调。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
| 200002 | Uri error. The URI of the page to be used for replacement is incorrect or does not exist. |
**示例:**
```ts
import { router } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
class RouterTmp {
Standard: router.RouterMode = router.RouterMode.Standard
}
let rtm: RouterTmp = new RouterTmp()
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().replaceUrl({
url: 'pages/detail',
params: {
data1: 'message'
}
}, rtm.Standard, (err: Error) => {
if (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`replaceUrl failed, code is ${code}, message is ${message}`);
return;
}
console.info('replaceUrl success');
});
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### pushNamedRoute
pushNamedRoute(options: router.NamedRouterOptions): Promise<void>
跳转到指定的命名路由页面,通过Promise获取跳转异常的返回结果。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | --------- |
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ------- |
| Promise<void> | 异常返回结果。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
| 100003 | Page stack error. Too many pages are pushed. |
| 100004 | Named route error. The named route does not exist. |
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit'
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().pushNamedRoute({
name: 'myPage',
params: {
data1: 'message',
data2: {
data3: [123, 456, 789]
}
}
})
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### pushNamedRoute
pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void
跳转到指定的命名路由页面。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | --------- |
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 |
| callback | AsyncCallback<void> | 是 | 异常响应回调。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
| 100003 | Page stack error. Too many pages are pushed. |
| 100004 | Named route error. The named route does not exist. |
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().pushNamedRoute({
name: 'myPage',
params: {
data1: 'message',
data2: {
data3: [123, 456, 789]
}
}
}, (err: Error) => {
if (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
return;
}
console.info('pushNamedRoute success');
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### pushNamedRoute
pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void>
跳转到指定的命名路由页面,通过Promise获取跳转异常的返回结果。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ---------- |
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 |
| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ------- |
| Promise<void> | 异常返回结果。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
| 100003 | Page stack error. Too many pages are pushed. |
| 100004 | Named route error. The named route does not exist. |
**示例:**
```ts
import { router } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
class RouterTmp{
Standard:router.RouterMode = router.RouterMode.Standard
}
let rtm:RouterTmp = new RouterTmp()
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().pushNamedRoute({
name: 'myPage',
params: {
data1: 'message',
data2: {
data3: [123, 456, 789]
}
}
}, rtm.Standard)
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### pushNamedRoute
pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void
跳转到指定的命名路由页面。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ---------- |
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 跳转页面描述信息。 |
| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 |
| callback | AsyncCallback<void> | 是 | 异常响应回调。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
| 100003 | Page stack error. Too many pages are pushed. |
| 100004 | Named route error. The named route does not exist. |
**示例:**
```ts
import { router } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
class RouterTmp {
Standard: router.RouterMode = router.RouterMode.Standard
}
let rtm: RouterTmp = new RouterTmp()
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().pushNamedRoute({
name: 'myPage',
params: {
data1: 'message',
data2: {
data3: [123, 456, 789]
}
}
}, rtm.Standard, (err: Error) => {
if (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
return;
}
console.info('pushNamedRoute success');
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### replaceNamedRoute
replaceNamedRoute(options: router.NamedRouterOptions): Promise<void>
用指定的命名路由页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | --------- |
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ------- |
| Promise<void> | 异常返回结果。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------------- |
| 401 | if the number of parameters is less than 1 or the type of the url parameter is not string. |
| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
| 100004 | Named route error. The named route does not exist. |
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().replaceNamedRoute({
name: 'myPage',
params: {
data1: 'message'
}
})
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### replaceNamedRoute
replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void
用指定的命名路由页面替换当前页面,并销毁被替换的页面。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | --------- |
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 |
| callback | AsyncCallback<void> | 是 | 异常响应回调。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
| 100004 | Named route error. The named route does not exist. |
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().replaceNamedRoute({
name: 'myPage',
params: {
data1: 'message'
}
}, (err: Error) => {
if (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`);
return;
}
console.info('replaceNamedRoute success');
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### replaceNamedRoute
replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void>
用指定的命名路由页面替换当前页面,并销毁被替换的页面,通过Promise获取跳转异常的返回结果。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ---------- |
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 |
| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ------- |
| Promise<void> | 异常返回结果。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Failed to get the delegate. This error code is thrown only in the standard system. |
| 100004 | Named route error. The named route does not exist. |
**示例:**
```ts
import { router } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
class RouterTmp {
Standard: router.RouterMode = router.RouterMode.Standard
}
let rtm: RouterTmp = new RouterTmp()
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().replaceNamedRoute({
name: 'myPage',
params: {
data1: 'message'
}
}, rtm.Standard)
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`pushUrl failed, code is ${error.code}, message is ${error.message}`);
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### replaceNamedRoute
replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void
用指定的命名路由页面替换当前页面,并销毁被替换的页面。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ---------- |
| options | [router.NamedRouterOptions](js-apis-router.md#namedrouteroptions10) | 是 | 替换页面描述信息。 |
| mode | [router.RouterMode](js-apis-router.md#routermode9) | 是 | 跳转页面使用的模式。 |
| callback | AsyncCallback<void> | 是 | 异常响应回调。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------------- |
| 401 | if the number of parameters is less than 1 or the type of the url parameter is not string. |
| 100001 | The UI execution context is not found. This error code is thrown only in the standard system. |
| 100004 | Named route error. The named route does not exist. |
**示例:**
```ts
import { router } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
class RouterTmp {
Standard: router.RouterMode = router.RouterMode.Standard
}
let rtm: RouterTmp = new RouterTmp()
@Entry
@Component
struct Index {
async routePage() {
this.getUIContext().getRouter().replaceNamedRoute({
name: 'myPage',
params: {
data1: 'message'
}
}, rtm.Standard, (err: Error) => {
if (err) {
let message = (err as BusinessError).message;
let code = (err as BusinessError).code;
console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`);
return;
}
console.info('replaceNamedRoute success');
})
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() {
Text('next page')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => {
this.routePage()
})
}
.width('100%')
.height('100%')
}
}
```
### back
back(options?: router.RouterOptions ): void
返回上一页面或指定的页面。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 否 | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面不会重新构建,页面栈里面的page不会回收,出栈后会被回收。 |
**示例:**
```ts
import { Router } from '@kit.ArkUI';
let router: Router = uiContext.getRouter();
router.back({url:'pages/detail'});
```
### back12+
back(index: number, params?: Object): void;
返回指定的页面。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------- | ---- | ---------- |
| index | number | 是 | 跳转目标页面的索引值。
取值范围:[0, +∞) |
| params | Object | 否 | 页面返回时携带的参数。 |
**示例:**
```ts
import { Router } from '@kit.ArkUI';
let router: Router = uiContext.getRouter();
router.back(1);
```
```ts
import { Router } from '@kit.ArkUI';
let router: Router = uiContext.getRouter();
router.back(1, {info:'来自Home页'}); //携带参数返回
```
### clear
clear(): void
清空页面栈中的所有历史页面,仅保留当前页面作为栈顶页面。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**示例:**
```ts
import { Router } from '@kit.ArkUI';
let router: Router = uiContext.getRouter();
router.clear();
```
### getLength
getLength(): string
获取当前在页面栈内的页面数量。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ------ | ------------------ |
| string | 页面数量,页面栈支持最大数值是32。 |
**示例:**
```ts
import { Router } from '@kit.ArkUI';
let router: Router = uiContext.getRouter();
let size = router.getLength();
console.info('pages stack size = ' + size);
```
### getState
getState(): router.RouterState
获取当前页面的状态信息。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| router.[RouterState](js-apis-router.md#routerstate) | 页面状态信息。 |
**示例:**
```ts
import { Router } from '@kit.ArkUI';
let router: Router = uiContext.getRouter();
let page = router.getState();
console.info('current index = ' + page.index);
console.info('current name = ' + page.name);
console.info('current path = ' + page.path);
```
### getStateByIndex12+
getStateByIndex(index: number): router.RouterState | undefined
通过索引值获取对应页面的状态信息。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------- | ---- | ---------- |
| index | number | 是 | 表示要获取的页面索引。
取值范围:[0, +∞) |
**返回值:**
| 类型 | 说明 |
| --------------------------- | ------- |
| router.[RouterState](js-apis-router.md#outerstate) \| undefined | 返回页面状态信息。索引不存在时返回undefined。 |
**示例:**
```ts
import { Router } from '@kit.ArkUI';
let router: Router = uiContext.getRouter();
let options: router.RouterState | undefined = router.getStateByIndex(1);
if (options != undefined) {
console.info('index = ' + options.index);
console.info('name = ' + options.name);
console.info('path = ' + options.path);
console.info('params = ' + options.params);
}
```
### getStateByUrl12+
getStateByUrl(url: string): Array
通过url获取当前页面的状态信息。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------- | ---- | ---------- |
| url | string | 是 | 表示要获取对应页面信息的url。 |
**返回值:**
| 类型 | 说明 |
| --------------------------- | ------- |
| Array | 页面状态信息。 |
**示例:**
```ts
import { Router } from '@kit.ArkUI';
let router: Router = uiContext.getRouter();
let options:Array = router.getStateByUrl('pages/index');
for (let i: number = 0; i < options.length; i++) {
console.info('index = ' + options[i].index);
console.info('name = ' + options[i].name);
console.info('path = ' + options[i].path);
console.info('params = ' + options[i].params);
}
```
### showAlertBeforeBackPage
showAlertBeforeBackPage(options: router.EnableAlertOptions): void
开启页面返回询问对话框。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | --------- |
| options | [router.EnableAlertOptions](js-apis-router.md#enablealertoptions) | 是 | 文本弹窗信息描述。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.router(页面路由)](errorcode-router.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
**示例:**
```ts
import { Router } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
let router: Router = uiContext.getRouter();
try {
router.showAlertBeforeBackPage({
message: 'Message Info'
});
} catch(error) {
let message = (error as BusinessError).message;
let code = (error as BusinessError).code;
console.error(`showAlertBeforeBackPage failed, code is ${code}, message is ${message}`);
}
```
### hideAlertBeforeBackPage
hideAlertBeforeBackPage(): void
禁用页面返回询问对话框。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**示例:**
```ts
import { Router } from '@kit.ArkUI';
let router: Router = uiContext.getRouter();
router.hideAlertBeforeBackPage();
```
### getParams
getParams(): Object
获取发起跳转的页面往当前页传入的参数。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ------ | ----------------- |
| Object | 发起跳转的页面往当前页传入的参数。 |
**示例:**
```ts
import { Router } from '@kit.ArkUI';
let router: Router = uiContext.getRouter();
router.getParams();
```
## CustomBuilderWithId18+
type CustomBuilderWithId = (id: number) => void
组件属性方法参数可使用CustomBuilderWithId类型来自定义UI描述,并且可以指定组件ID生成用户自定义组件。
**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| id | number | 是 | 组件ID |
## TargetInfo18+
指定组件绑定的目标节点。
**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 名称 | 类型 | 只读 | 可选 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| id | string \| number | 否 | 否 | 指定popup或menu绑定的目标节点。
**说明:**
1. 当id是number时,对应组件实例的UniquelD,此id由系统保证唯一性。
2. 当id是string时,对应[通用属性id](arkui-ts/ts-universal-attributes-component-id.md#id)所指定的组件,此id的唯一性需由开发者确保,但实际可能会有多个。 |
| componentId | number | 否 | 是 | 目标节点所在的自定义组件的UniquelD。当上述id指定为string类型时,可通过此属性圈定范围。方便开发者在一定范围内保证id: string的唯一性。 |
## PromptAction
以下API需先使用UIContext中的[getPromptAction()](#getpromptaction)方法获取到PromptAction对象,再通过该对象调用对应方法。
### showToast
showToast(options: promptAction.ShowToastOptions): void
创建并显示文本提示框。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | 是 | 文本弹窗选项。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
**示例:**
```ts
import { PromptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
let promptAction: PromptAction = uiContext.getPromptAction();
try {
promptAction.showToast({
message: 'Message Info',
duration: 2000
});
} catch (error) {
let message = (error as BusinessError).message;
let code = (error as BusinessError).code;
console.error(`showToast args error code is ${code}, message is ${message}`);
};
```
### openToast18+
openToast(options: promptAction.ShowToastOptions): Promise<number>
**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------------------------------------ | ---- | -------------- |
| options | [promptAction.ShowToastOptions](js-apis-promptAction.md#showtoastoptions) | 是 | 文本弹窗选项。 |
**返回值**
| 类型 | 说明 |
| ---------------- | ------------------------------------ |
| Promise<number> | 返回供closeToast使用的文本提示框id。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| -------- | ------------------------------------------------------------ |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
**示例:**
```ts
import { PromptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct toastExample {
@State toastId: number = 0;
promptAction: PromptAction = this.getUIContext().getPromptAction()
build() {
Column() {
Button('Open Toast')
.height(100)
.onClick(() => {
this.promptAction.openToast({
message: 'Toast Massage',
duration: 10000,
}).then((toastId: number) => {
this.toastId = toastId;
})
.catch((error: BusinessError) => {
console.error(`openToast error code is ${error.code}, message is ${error.message}`)
})
})
Blank().height(50);
Button('Close Toast')
.height(100)
.onClick(() => {
try {
this.promptAction.closeToast(this.toastId);
} catch (error) {
let message = (error as BusinessError).message;
let code = (error as BusinessError).code;
console.error(`CloseToast error code is ${code}, message is ${message}`);
};
})
}.height('100%').width('100%').justifyContent(FlexAlign.Center)
}
}
```
### closeToast18+
closeToast(toastId: number): void
**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ----------------------------- |
| toastId | number | 是 | openToast返回的文本提示框id。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| -------- | ------------------------------------------------------------ |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
**示例:**
示例请看[openToaset18](#opentoast18)的示例。
### showDialog
showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse>): void
创建并显示对话框,对话框响应结果异步返回。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------ |
| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | 是 | 页面显示对话框信息描述。 |
| callback | AsyncCallback<[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | 是 | 对话框响应结果回调。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
**示例:**
```ts
import { PromptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
let promptAction: PromptAction = uiContext.getPromptAction();
try {
promptAction.showDialog({
title: 'showDialog Title Info',
message: 'Message Info',
buttons: [
{
text: 'button1',
color: '#000000'
},
{
text: 'button2',
color: '#000000'
}
]
}, (err, data) => {
if (err) {
console.error('showDialog err: ' + err);
return;
}
console.info('showDialog success callback, click button: ' + data.index);
});
} catch (error) {
let message = (error as BusinessError).message;
let code = (error as BusinessError).code;
console.error(`showDialog args error code is ${code}, message is ${message}`);
};
```
### showDialog
showDialog(options: promptAction.ShowDialogOptions): Promise<promptAction.ShowDialogSuccessResponse>
创建并显示对话框,对话框响应后同步返回结果,通过Promise获取对话框响应结果。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------ |
| options | [promptAction.ShowDialogOptions](js-apis-promptAction.md#showdialogoptions) | 是 | 对话框选项。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | -------- |
| Promise<[promptAction.ShowDialogSuccessResponse](js-apis-promptAction.md#showdialogsuccessresponse)> | 对话框响应结果。 |
**错误码:**
以下错误码的详细介绍请参见[ 通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
**示例:**
```ts
import { PromptAction } from '@kit.ArkUI';
let promptAction: PromptAction = uiContext.getPromptAction();
promptAction.showDialog({
title: 'Title Info',
message: 'Message Info',
buttons: [
{
text: 'button1',
color: '#000000'
},
{
text: 'button2',
color: '#000000'
}
],
})
.then(data => {
console.info('showDialog success, click button: ' + data.index);
})
.catch((err: Error) => {
console.error('showDialog error: ' + err);
})
```
### showActionMenu11+
showActionMenu(options: promptAction.ActionMenuOptions, callback: AsyncCallback<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)>):void
创建并显示操作菜单,菜单响应结果异步返回。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------ |
| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是 | 操作菜单选项。 |
| callback | AsyncCallback<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | 是 | 菜单响应结果回调。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| -------- | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
**示例:**
```ts
import { PromptAction, promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
let promptActionF: PromptAction = uiContext.getPromptAction();
try {
promptActionF.showActionMenu({
title: 'Title Info',
buttons: [
{
text: 'item1',
color: '#666666'
},
{
text: 'item2',
color: '#000000'
}
]
}, (err:BusinessError, data:promptAction.ActionMenuSuccessResponse) => {
if (err) {
console.error('showDialog err: ' + err);
return;
}
console.info('showDialog success callback, click button: ' + data.index);
});
} catch (error) {
let message = (error as BusinessError).message;
let code = (error as BusinessError).code;
console.error(`showActionMenu args error code is ${code}, message is ${message}`);
};
```
### showActionMenu(deprecated)
showActionMenu(options: promptAction.ActionMenuOptions, callback: [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)):void
创建并显示操作菜单,菜单响应结果异步返回。
从API version11开始不再维护,建议使用[showActionMenu](#showactionmenu11)。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------ |
| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是 | 操作菜单选项。 |
| callback | [promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse) | 是 | 菜单响应结果回调。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
**示例:**
```ts
import { PromptAction,promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
let promptActionF: PromptAction = uiContext.getPromptAction();
try {
promptActionF.showActionMenu({
title: 'Title Info',
buttons: [
{
text: 'item1',
color: '#666666'
},
{
text: 'item2',
color: '#000000'
}
]
}, { index:0 });
} catch (error) {
let message = (error as BusinessError).message;
let code = (error as BusinessError).code;
console.error(`showActionMenu args error code is ${code}, message is ${message}`);
};
```
### showActionMenu
showActionMenu(options: promptAction.ActionMenuOptions): Promise<promptAction.ActionMenuSuccessResponse>
创建并显示操作菜单,通过Promise获取菜单响应结果。
**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| options | [promptAction.ActionMenuOptions](js-apis-promptAction.md#actionmenuoptions) | 是 | 操作菜单选项。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| Promise<[promptAction.ActionMenuSuccessResponse](js-apis-promptAction.md#actionmenusuccessresponse)> | 菜单响应结果。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
**示例:**
```ts
import { PromptAction } from '@kit.ArkUI';
let promptAction: PromptAction = uiContext.getPromptAction();
promptAction.showActionMenu({
title: 'showActionMenu Title Info',
buttons: [
{
text: 'item1',
color: '#666666'
},
{
text: 'item2',
color: '#000000'
},
]
})
.then(data => {
console.info('showActionMenu success, click button: ' + data.index);
})
.catch((err: Error) => {
console.error('showActionMenu error: ' + err);
})
```
### openCustomDialog12+
openCustomDialog\(dialogContent: ComponentContent\, options?: promptAction.BaseDialogOptions): Promise<void>
创建并弹出dialogContent对应的自定义弹窗,使用Promise异步回调。通过该接口弹出的弹窗内容样式完全按照dialogContent中设置的样式显示,即相当于customdialog设置customStyle为true时的显示效果。暂不支持[isModal](js-apis-promptAction.md#basedialogoptions11) = true与[showInSubWindow](js-apis-promptAction.md#basedialogoptions11) = true同时使用。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| dialogContent | [ComponentContent\](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 |
| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | 否 | 弹窗样式。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| Promise<void> | 异常返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 103301 | The ComponentContent is incorrect. |
| 103302 | Dialog content already exists.|
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit';
import { ComponentContent } from '@kit.ArkUI';
class Params {
text: string = ""
constructor(text: string) {
this.text = text;
}
}
@Builder
function buildText(params: Params) {
Column() {
Text(params.text)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 36 })
}.backgroundColor('#FFF0F0F0')
}
@Entry
@Component
struct Index {
@State message: string = "hello"
build() {
Row() {
Column() {
Button("click me")
.onClick(() => {
let uiContext = this.getUIContext();
let promptAction = uiContext.getPromptAction();
let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
promptAction.openCustomDialog(contentNode)
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`);
})
})
}
.width('100%')
.height('100%')
}
.height('100%')
}
}
```
### openCustomDialogWithController18+
openCustomDialogWithController\(dialogContent: ComponentContent\, controller: promptAction.DialogController, options?: promptAction.BaseDialogOptions): Promise<void>
创建并弹出dialogContent对应的自定义弹窗,使用Promise异步回调。支持传入弹窗控制器与自定义弹窗绑定,后续可以通过控制器控制自定义弹窗。
通过该接口弹出的弹窗内容样式完全按照dialogContent中设置的样式显示,即相当于customdialog设置customStyle为true时的显示效果。
暂不支持[isModal](js-apis-promptAction.md#basedialogoptions11) = true与[showInSubWindow](js-apis-promptAction.md#basedialogoptions11) = true同时使用。
**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| dialogContent | [ComponentContent\](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 |
| controller | [promptAction.DialogController](js-apis-promptAction.md#dialogcontroller18) | 是 | 自定义弹窗的控制器。 |
| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | 否 | 自定义弹窗的样式。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| Promise<void> | 异常返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 103301 | The ComponentContent is incorrect. |
| 103302 | Dialog content already exists.|
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit';
import { ComponentContent, promptAction } from '@kit.ArkUI';
class Params {
text: string = ""
dialogController: promptAction.DialogController = new promptAction.DialogController();
constructor(text: string, dialogController: promptAction.DialogController) {
this.text = text;
this.dialogController = dialogController;
}
}
@Builder
function buildText(params: Params) {
Column() {
Text(params.text)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 36 })
Button('点我关闭弹窗:通过外部传递的DialogController')
.onClick(() => {
if (params.dialogController != undefined) {
params.dialogController.close()
}
})
}.backgroundColor('#FFF0F0F0')
}
@Entry
@ComponentV2
struct Index {
@Local message: string = "hello"
private dialogController: promptAction.DialogController = new promptAction.DialogController()
build() {
Row() {
Column() {
Button("click me")
.onClick(() => {
let uiContext = this.getUIContext();
let promptAction = uiContext.getPromptAction();
let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText),
new Params(this.message, this.dialogController));
promptAction.openCustomDialogWithController(contentNode, this.dialogController)
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`OpenCustomDialogWithController args error code is ${error.code}, message is ${error.message}`);
})
})
}
.width('100%')
.height('100%')
}
.height('100%')
}
}
```
### closeCustomDialog12+
closeCustomDialog\(dialogContent: ComponentContent\): Promise<void>
关闭已弹出的dialogContent对应的自定义弹窗,使用Promise异步回调。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| dialogContent | [ComponentContent\](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| Promise<void> | 异常返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 103301 | The ComponentContent is incorrect. |
| 103303 | The ComponentContent cannot be found. |
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit';
import { ComponentContent } from '@kit.ArkUI';
class Params {
text: string = ""
constructor(text: string) {
this.text = text;
}
}
@Builder
function buildText(params: Params) {
Column() {
Text(params.text)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 36 })
}.backgroundColor('#FFF0F0F0')
}
@Entry
@Component
struct Index {
@State message: string = "hello"
build() {
Row() {
Column() {
Button("click me")
.onClick(() => {
let uiContext = this.getUIContext();
let promptAction = uiContext.getPromptAction();
let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));
promptAction.openCustomDialog(contentNode)
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`);
})
setTimeout(() => {
promptAction.closeCustomDialog(contentNode)
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`OpenCustomDialog args error code is ${error.code}, message is ${error.message}`);
})
}, 2000); //2秒后自动关闭
})
}
.width('100%')
.height('100%')
}
.height('100%')
}
}
```
### updateCustomDialog12+
updateCustomDialog\(dialogContent: ComponentContent\, options: promptAction.BaseDialogOptions): Promise<void>
更新已弹出的dialogContent对应的自定义弹窗的样式,使用Promise异步回调。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | ------- |
| dialogContent | [ComponentContent\](./js-apis-arkui-ComponentContent.md) | 是 | 自定义弹窗中显示的组件内容。 |
| options | [promptAction.BaseDialogOptions](js-apis-promptAction.md#basedialogoptions11) | 是 | 弹窗样式,目前仅支持更新alignment、offset、autoCancel、maskColor。 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------- |
| Promise<void> | 异常返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| ------ | ---------------------------------- |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 103301 | The ComponentContent is incorrect. |
| 103303 | The ComponentContent cannot be found. |
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit';
import { ComponentContent } from '@kit.ArkUI';
class Params {
text: string = ""
constructor(text: string) {
this.text = text;
}
}
@Builder
function buildText(params: Params) {
Column() {
Text(params.text)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 36 })
}.backgroundColor('#FFF0F0F0')
}
@Entry
@Component
struct Index {
@State message: string = "hello"
build() {
Row() {
Column() {
Button("click me")
.onClick(() => {
let uiContext = this.getUIContext();
let promptAction = uiContext.getPromptAction();
let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message))
promptAction.openCustomDialog(contentNode)
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`updateCustomDialog args error code is ${error.code}, message is ${error.message}`)
})
setTimeout(() => {
promptAction.updateCustomDialog(contentNode, { alignment: DialogAlignment.CenterEnd })
.then(() => {
console.info('succeeded')
})
.catch((error: BusinessError) => {
console.error(`updateCustomDialog args error code is ${error.code}, message is ${error.message}`)
})
}, 2000); //2秒后自动更新弹窗位置
})
}
.width('100%')
.height('100%')
}
.height('100%')
}
}
```
### openCustomDialog12+
openCustomDialog(options: promptAction.CustomDialogOptions): Promise\
创建并弹出自定义弹窗。使用Promise异步回调,返回供closeCustomDialog使用的对话框id。暂不支持isModal = true与showInSubWindow = true同时使用。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------------------------------------ | ---- | ------------------ |
| options | [promptAction.CustomDialogOptions](js-apis-promptAction.md#customdialogoptions11) | 是 | 自定义弹窗的内容。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | --------------------------------------- |
| Promise<void> | 返回供closeCustomDialog使用的对话框id。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| -------- | ------------------------------------------------------------ |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
### presentCustomDialog18+
presentCustomDialog(builder: CustomBuilder \| CustomBuilderWithId, controller?: promptAction.DialogController, options?: promptAction.DialogOptions): Promise\
创建并弹出自定义弹窗。使用Promise异步回调,返回供closeCustomDialog使用的对话框id。
支持在自定义弹窗内容中持有弹窗ID进行对应操作。支持传入弹窗控制器与自定义弹窗绑定,后续可以通过控制器控制自定义弹窗。
暂不支持isModal = true与showInSubWindow = true同时使用。
**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------------------------------------ | ---- | ------------------ |
| builder | [CustomBuilder](arkui-ts/ts-types.md#custombuilder8) \| [CustomBuilderWithId](#custombuilderwithid18) | 是 | 自定义弹窗的内容。 |
| controller | [promptAction.DialogController](js-apis-promptAction.md#dialogcontroller18) | 否 | 自定义弹窗的控制器。 |
| options | [promptAction.DialogOptions](js-apis-promptAction.md#dialogoptions18) | 否 | 自定义弹窗的样式。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | --------------------------------------- |
| Promise<number> | 返回自定义弹窗ID。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| -------- | ------------------------------------------------------------ |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
**示例:**
```ts
import { BusinessError } from '@kit.BasicServicesKit';
import { PromptAction, promptAction } from '@kit.ArkUI';
@Entry
@ComponentV2
struct Index {
@Local message: string = "hello"
private ctx: UIContext = this.getUIContext()
private promptAction: PromptAction = this.ctx.getPromptAction()
private dialogController: promptAction.DialogController = new promptAction.DialogController()
private customDialogComponentId: number = 0
@Builder customDialogComponent() {
Column() {
Text(this.message).fontSize(30)
Row({ space: 10 }) {
Button("通过DialogId关闭").onClick(() => {
this.promptAction.closeCustomDialog(this.customDialogComponentId)
})
Button("通过DialogController关闭").onClick(() => {
this.dialogController.close()
})
}
}.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
}
@Builder customDialogComponentWithId(dialogId: number) {
Column() {
Text(this.message).fontSize(30)
Row({ space: 10 }) {
Button("通过DialogId关闭").onClick(() => {
this.promptAction.closeCustomDialog(dialogId)
})
Button("通过DialogController关闭").onClick(() => {
this.dialogController.close()
})
}
}.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
}
build() {
Row() {
Column({ space: 10 }) {
Button('presentCustomDialog')
.fontSize(20)
.onClick(() => {
this.promptAction.presentCustomDialog(() => {
this.customDialogComponent()
}, this.dialogController)
.then((dialogId: number) => {
this.customDialogComponentId = dialogId
})
.catch((err: BusinessError) => {
console.error("presentCustomDialog error: " + err.code + " " + err.message)
})
})
Button('presentCustomDialog with id')
.fontSize(20)
.onClick(() => {
this.promptAction.presentCustomDialog((dialogId: number) => {
this.customDialogComponentWithId(dialogId)
}, this.dialogController)
.catch((err: BusinessError) => {
console.error("presentCustomDialog with id error: " + err.code + " " + err.message)
})
})
}
.width('100%')
.height('100%')
}
.height('100%')
}
}
```
### closeCustomDialog12+
closeCustomDialog(dialogId: number): void
关闭自定义弹窗。
**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | -------------------------------- |
| dialogId | number | 是 | openCustomDialog返回的对话框id。 |
**错误码:**
以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[ohos.promptAction(弹窗)](errorcode-promptAction.md)错误码。
| 错误码ID | 错误信息 |
| -------- | ------------------------------------------------------------ |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed. |
| 100001 | Internal error. |
**示例:**
```ts
import { PromptAction } from '@kit.ArkUI';
@Entry
@Component
struct Index {
promptAction: PromptAction = this.getUIContext().getPromptAction()
private customDialogComponentId: number = 0
@Builder
customDialogComponent() {
Column() {
Text('弹窗').fontSize(30)
Row({ space: 50 }) {
Button("确认").onClick(() => {
this.promptAction.closeCustomDialog(this.customDialogComponentId)
})
Button("取消").onClick(() => {
this.promptAction.closeCustomDialog(this.customDialogComponentId)
})
}
}.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
}
build() {
Row() {
Column() {
Button("click me")
.onClick(() => {
this.promptAction.openCustomDialog({
builder: () => {
this.customDialogComponent()
},
onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
console.info("reason" + JSON.stringify(dismissDialogAction.reason))
console.log("dialog onWillDismiss")
if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
dismissDialogAction.dismiss()
}
if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
dismissDialogAction.dismiss()
}
}
}).then((dialogId: number) => {
this.customDialogComponentId = dialogId
})
})
}
.width('100%')
.height('100%')
}
.height('100%')
}
}
```
### getTopOrder18+
getTopOrder(): LevelOrder
返回最顶层显示的弹窗的顺序。
获取最顶层显示的弹窗的顺序,可以在下一个弹窗时指定期望的顺序。
**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
**系统能力:** SystemCapability.ArkUI.ArkUI.Full
**返回值:**
| 类型 | 说明 |
| ------------------- | --------------------------------------- |
| [LevelOrder](js-apis-promptAction.md#levelorder18) | 返回弹窗层级信息。 |
**示例:**
该示例通过调用getTopOrder接口,展示了获取最顶层显示的弹窗的顺序的功能。
```ts
import { ComponentContent, PromptAction, LevelOrder, promptAction, UIContext } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
class Params {
text: string = ""
constructor(text: string) {
this.text = text;
}
}
@Builder
function buildText(params: Params) {
Column({ space: 20 }) {
Text(params.text)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 36 })
}.backgroundColor('#FFF0F0F0')
}
@Entry
@Component
struct Index {
@State message: string = '弹窗'
private ctx: UIContext = this.getUIContext()
private promptAction: PromptAction = this.ctx.getPromptAction()
private contentNode: ComponentContent