@ohos.arkui.UIContext (UIContext)

In the stage model, a window stage or window can use the loadContent API to load pages, create a UI instance, and render page content to the associated window. Naturally, UI instances and windows are associated on a one-by-one basis. Some global UI APIs are executed in the context of certain UI instances. When calling these APIs, you must identify the UI context, and consequently UI instance, by tracing the call chain. If these APIs are called on a non-UI page or in some asynchronous callback, the current UI context may fail to be identified, resulting in API execution errors.

@ohos.window adds the getUIContext API in API version 10 for obtaining the UIContext object of a UI instance. The API provided by the UIContext object can be directly applied to the corresponding UI instance.

NOTE

The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.

You can preview how this component looks on a real device, but not in DevEco Studio Previewer.

UIContext

In the following API examples, you must first use getUIContext() in @ohos.window to obtain a UIContext instance, and then call the APIs using the obtained instance. In this document, the UIContext instance is represented by uiContext.

getFont

getFont(): Font

Obtains a Font object.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Type Description
Font Font object.

Example

uiContext.getFont();

getComponentUtils

getComponentUtils(): ComponentUtils

Obtains the ComponentUtils object.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Type Description
ComponentUtils ComponentUtils object.

Example

uiContext.getComponentUtils();

getUIInspector

getUIInspector(): UIInspector

Obtains the UIInspector object.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Type Description
UIInspector UIInspector object.

Example

uiContext.getUIInspector();

getMediaQuery

getMediaQuery(): MediaQuery

Obtains a MediaQuery object.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Type Description
MediaQuery MediaQuery object.

Example

uiContext.getMediaQuery();

getRouter

getRouter(): Router

Obtains a Router object.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Type Description
Router Router object.

Example

uiContext.getRouter();

getPromptAction

getPromptAction(): PromptAction

Obtains a PromptAction object.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Type Description
PromptAction PromptAction object.

Example

uiContext.getPromptAction();

animateTo

animateTo(value: AnimateParam, event: () => void): void

Applies a transition animation for state changes.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value AnimateParam Yes Animation settings.
event () => void Yes Closure function that displays the dynamic effect. The system automatically inserts the transition animation if the state changes in the closure function.

Example

// xxx.ets
@Entry
@Component
struct AnimateToExample {
  @State widthSize: number = 250
  @State heightSize: number = 100
  @State rotateAngle: number = 0
  private flag: boolean = true

  build() {
    Column() {
      Button('change size')
        .width(this.widthSize)
        .height(this.heightSize)
        .margin(30)
        .onClick(() => {
          if (this.flag) {
            uiContext.animateTo({
              duration: 2000,
              curve: Curve.EaseOut,
              iterations: 3,
              playMode: PlayMode.Normal,
              onFinish: () => {
                console.info('play end')
              }
            }, () => {
              this.widthSize = 150
              this.heightSize = 60
            })
          } else {
            uiContext.animateTo({}, () => {
              this.widthSize = 250
              this.heightSize = 100
            })
          }
          this.flag = !this.flag
        })
      Button('change rotate angle')
        .margin(50)
        .rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
        .onClick(() => {
          uiContext.animateTo({
            duration: 1200,
            curve: Curve.Friction,
            delay: 500,
            iterations: -1, // The value -1 indicates that the animation is played for an unlimited number of times.
            playMode: PlayMode.Alternate,
            onFinish: () => {
              console.info('play end')
            }
          }, () => {
            this.rotateAngle = 90
          })
        })
    }.width('100%').margin({ top: 5 })
  }
}

showAlertDialog

showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions): void

Shows an alert dialog box.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions Yes Parameters of the <AlertDialog> component.

Example

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

Shows an action sheet in the given settings.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value ActionSheetOptions Yes Parameters of the action sheet.

Example

uiContext.showActionSheet({
  title: 'ActionSheet title',
  message: 'message',
  autoCancel: true,
  confirm: {
    value: 'Confirm button',
    action: () => {
      console.log('Get Alert Dialog handled')
    }
  },
  cancel: () => {
    console.log('actionSheet canceled')
  },
  alignment: DialogAlignment.Bottom,
  offset: { dx: 0, dy: -10 },
  sheets: [
    {
      title: 'apples',
      action: () => {
        console.log('apples')
      }
    },
    {
      title: 'bananas',
      action: () => {
        console.log('bananas')
      }
    },
    {
      title: 'pears',
      action: () => {
        console.log('pears')
      }
    }
  ]
})

showDatePickerDialog

showDatePickerDialog(options: DatePickerDialogOptions): void

Shows a date picker dialog box in the given settings.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options DatePickerDialogOptions Yes Parameters of the date picker dialog box.

Example

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) => {
    // Use the setFullYear method to set the date when the OK button is touched. In this way, when the date picker dialog box is displayed again, the selected date is the date last confirmed.
    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

Shows a time picker dialog box in the given settings.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options TimePickerDialogOptions Yes Parameters of the time picker dialog box.

Example

// 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(() => {
          uiContext.showTimePickerDialog({
            selected: this.selectTime,
            onAccept: (value: TimePickerResult) => {
              // Set selectTime to the time when the OK button is clicked. In this way, when the dialog box is displayed again, the selected time is the time when the operation was confirmed last time.
              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

Shows a text picker dialog box in the given settings.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options TextPickerDialogOptions Yes Parameters of the text picker dialog box.

Example

// 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(() => {
          uiContext.showTextPickerDialog({
            range: this.fruits,
            selected: this.select,
            onAccept: (value: TextPickerResult) => {
              // Set select to the index of the item selected when the OK button is touched. In this way, when the text picker dialog box is displayed again, the selected item is the one last confirmed.
              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

Creates an Animator object.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options AnimatorOptions Yes Animator options.

Return value

Type Description
AnimatorResult Animator result.

Example

import { AnimatorOptions } from '@ohos.animator';
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);
  });
}

runScopedTask

runScopedTask(callback: () => void): void

Executes the specified callback in this UI context.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
callback () => void Yes Callback used to return the result.

Example

uiContext.runScopedTask(
  () => {
    console.log('Succeeded in runScopedTask');
  }
);

Font

In the following API examples, you must first use getFont() in UIContext to obtain a Font instance, and then call the APIs using the obtained instance.

registerFont

registerFont(options: font.FontOptions): void

Registers a custom font with the font manager.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options font.FontOptions Yes Information about the custom font to register.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
let font:Font = uiContext.getFont();
font.registerFont({
  familyName: 'medium',
  familySrc: '/font/medium.ttf'
});

getSystemFontList

getSystemFontList(): Array<string>

Obtains the list of supported fonts.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Type Description
Array<string> List of supported fonts.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
let font:Font|undefined = uiContext.getFont();
if(font){
  font.getSystemFontList()
}

getFontByName

getFontByName(fontName: string): font.FontInfo

Obtains information about a system font based on the font name.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
fontName string Yes System font name.

Return value

Type Description
font.FontInfo Information about the system font.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
let font:Font|undefined = uiContext.getFont();
if(font){
  font.getFontByName('Sans Italic')
}

ComponentUtils

In the following API examples, you must first use getComponentUtils() in UIContext to obtain a ComponentUtils instance, and then call the APIs using the obtained instance.

getRectangleById

getRectangleById(id: string): componentUtils.ComponentInfo

Obtains the size, position, translation, scaling, rotation, and affine matrix information of the specified component.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
id string Yes Unique component ID.

Return value

Type Description
ComponentInfo Size, position, translation, scaling, rotation, and affine matrix information of the component.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
let componentUtils:ComponentUtils = uiContext.getComponentUtils();
let modePosition = componentUtils.getRectangleById("onClick");
let localOffsetWidth = modePosition.size.width;
let localOffsetHeight = modePosition.size.height;

UIInspector

In the following API examples, you must first use getUIInspector() in UIContext to obtain a UIInspector instance, and then call the APIs using the obtained instance.

createComponentObserver

createComponentObserver(id: string): inspector.ComponentObserver

Creates an observer for the specified component.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
id string Yes Component ID.

Return value

Type Description
inspector.ComponentObserver Component observer, which is used to register or unregister listeners for completion of component layout or drawing.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
let inspector:UIInspector = uiContext.getUIInspector();
let listener = inspector.createComponentObserver('COMPONENT_ID');

MediaQuery

In the following API examples, you must first use getMediaQuery() in UIContext to obtain a MediaQuery instance, and then call the APIs using the obtained instance.

matchMediaSync

matchMediaSync(condition: string): mediaQuery.MediaQueryListener

Sets the media query criteria and returns the corresponding listening handle.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
condition string Yes Media query condition. For details, see Syntax.

Return value

Type Description
mediaQuery.MediaQueryListener Listening handle to a media event, which is used to register or unregister the listening callback.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
let mediaquery: MediaQuery = uiContext.getMediaQuery();
let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events.

Router

In the following API examples, you must first use getRouter() in UIContext to obtain a Router instance, and then call the APIs using the obtained instance.

pushUrl

pushUrl(options: router.RouterOptions): Promise<void>

Navigates to a specified page in the application.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.RouterOptions Yes Page routing parameters.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found.
100002 if the uri is not exist.
100003 if the pages are pushed too much.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router:Router = uiContext.getRouter();
try {
  router.pushUrl({
    url: 'pages/routerpage2',
    params: {
      data1: 'message',
      data2: {
        data3: [123, 456, 789]
      }
    }
  })
} catch (err) {
  let message = (err as BusinessError).message;
  let code = (err as BusinessError).code;
  console.error(`pushUrl failed, code is ${code}, message is ${message}`);
}

pushUrl

pushUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void

Navigates to a specified page in the application.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.RouterOptions Yes Page routing parameters.
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found.
100002 if the uri is not exist.
100003 if the pages are pushed too much.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router:Router = uiContext.getRouter();
router.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');
})

pushUrl

pushUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void>

Navigates to a specified page in the application.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.RouterOptions Yes Page routing parameters.
mode router.RouterMode Yes Routing mode.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found.
100002 if the uri is not exist.
100003 if the pages are pushed too much.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
import router from '@ohos.router';
let routerF:Router = uiContext.getRouter();
class RouterTmp{
  Standard:router.RouterMode = router.RouterMode.Standard
}
let rtm:RouterTmp = new RouterTmp()
try {
  routerF.pushUrl({
    url: 'pages/routerpage2',
    params: {
      data1: 'message',
      data2: {
        data3: [123, 456, 789]
      }
    }
  }, rtm.Standard)
} catch (err) {
  let message = (err as BusinessError).message;
  let code = (err as BusinessError).code;
  console.error(`pushUrl failed, code is ${code}, message is ${message}`);
}

pushUrl

pushUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void

Navigates to a specified page in the application.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.RouterOptions Yes Page routing parameters.
mode router.RouterMode Yes Routing mode.
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found.
100002 if the uri is not exist.
100003 if the pages are pushed too much.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
import router from '@ohos.router';
let routerF:Router = uiContext.getRouter();
class RouterTmp{
  Standard:router.RouterMode = router.RouterMode.Standard
}
let rtm:RouterTmp = new RouterTmp()
routerF.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');
})

replaceUrl

replaceUrl(options: router.RouterOptions): Promise<void>

Replaces the current page with another one in the application and destroys the current page.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.RouterOptions Yes Description of the new page.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found, only throw in standard system.
200002 if the uri is not exist.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router:Router = uiContext.getRouter();
try {
  router.replaceUrl({
    url: 'pages/detail',
    params: {
      data1: 'message'
    }
  })
} catch (err) {
  let message = (err as BusinessError).message;
  let code = (err as BusinessError).code;
  console.error(`replaceUrl failed, code is ${code}, message is ${message}`);
}

replaceUrl

replaceUrl(options: router.RouterOptions, callback: AsyncCallback<void>): void

Replaces the current page with another one in the application and destroys the current page.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.RouterOptions Yes Description of the new page.
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found, only throw in standard system.
200002 if the uri is not exist.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router:Router = uiContext.getRouter();
router.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');
})

replaceUrl

replaceUrl(options: router.RouterOptions, mode: router.RouterMode): Promise<void>

Replaces the current page with another one in the application and destroys the current page.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.RouterOptions Yes Description of the new page.
mode router.RouterMode Yes Routing mode.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if can not get the delegate, only throw in standard system.
200002 if the uri is not exist.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
import router from '@ohos.router';
let routerF:Router = uiContext.getRouter();
class RouterTmp{
  Standard:router.RouterMode = router.RouterMode.Standard
}
let rtm:RouterTmp = new RouterTmp()
try {
  routerF.replaceUrl({
    url: 'pages/detail',
    params: {
      data1: 'message'
    }
  }, rtm.Standard)
} catch (err) {
  let message = (err as BusinessError).message;
  let code = (err as BusinessError).code;
  console.error(`replaceUrl failed, code is ${code}, message is ${message}`);
}

replaceUrl

replaceUrl(options: router.RouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void

Replaces the current page with another one in the application and destroys the current page.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.RouterOptions Yes Description of the new page.
mode router.RouterMode Yes Routing mode.
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found, only throw in standard system.
200002 if the uri is not exist.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector,  MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
import router from '@ohos.router';
let routerF:Router = uiContext.getRouter();
class RouterTmp{
  Standard:router.RouterMode = router.RouterMode.Standard
}
let rtm:RouterTmp = new RouterTmp()
routerF.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');
});

pushNamedRoute

pushNamedRoute(options: router.NamedRouterOptions): Promise<void>

Navigates to a page using the named route. This API uses a promise to return the result.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.NamedRouterOptions Yes Page routing parameters.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found.
100003 if the pages are pushed too much.
100004 if the named route is not exist.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router:Router = uiContext.getRouter();
try {
  router.pushNamedRoute({
    name: 'myPage',
    params: {
      data1: 'message',
      data2: {
        data3: [123, 456, 789]
      }
    }
  })
} catch (err) {
  let message = (err as BusinessError).message;
  let code = (err as BusinessError).code;
  console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
}

pushNamedRoute

pushNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void

Navigates to a page using the named route. This API uses a promise to return the result.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.NamedRouterOptions Yes Page routing parameters.
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found.
100003 if the pages are pushed too much.
100004 if the named route is not exist.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router:Router = uiContext.getRouter();
router.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');
})

pushNamedRoute

pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void>

Navigates to a page using the named route. This API uses a promise to return the result.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.NamedRouterOptions Yes Page routing parameters.
mode router.RouterMode Yes Routing mode.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found.
100003 if the pages are pushed too much.
100004 if the named route is not exist.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
import router from '@ohos.router';
let routerF:Router = uiContext.getRouter();
class RouterTmp{
  Standard:router.RouterMode = router.RouterMode.Standard
}
let rtm:RouterTmp = new RouterTmp()
try {
  routerF.pushNamedRoute({
    name: 'myPage',
    params: {
      data1: 'message',
      data2: {
        data3: [123, 456, 789]
      }
    }
  }, rtm.Standard)
} catch (err) {
  let message = (err as BusinessError).message;
  let code = (err as BusinessError).code;
  console.error(`pushNamedRoute failed, code is ${code}, message is ${message}`);
}

pushNamedRoute

pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void

Navigates to a page using the named route. This API uses a promise to return the result.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.NamedRouterOptions Yes Page routing parameters.
mode router.RouterMode Yes Routing mode.
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found.
100003 if the pages are pushed too much.
100004 if the named route is not exist.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
import router from '@ohos.router';
let routerF:Router = uiContext.getRouter();
class RouterTmp{
  Standard:router.RouterMode = router.RouterMode.Standard
}
let rtm:RouterTmp = new RouterTmp()
routerF.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');
})

replaceNamedRoute

replaceNamedRoute(options: router.NamedRouterOptions): Promise<void>

Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.NamedRouterOptions Yes Description of the new page.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found, only throw in standard system.
100004 if the named route is not exist.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router:Router = uiContext.getRouter();
try {
  router.replaceNamedRoute({
    name: 'myPage',
    params: {
      data1: 'message'
    }
  })
} catch (err) {
  let message = (err as BusinessError).message;
  let code = (err as BusinessError).code;
  console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`);
}

replaceNamedRoute

replaceNamedRoute(options: router.NamedRouterOptions, callback: AsyncCallback<void>): void

Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.NamedRouterOptions Yes Description of the new page.
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found, only throw in standard system.
100004 if the named route is not exist.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router:Router = uiContext.getRouter();
router.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');
})

replaceNamedRoute

replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode): Promise<void>

Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.NamedRouterOptions Yes Description of the new page.
mode router.RouterMode Yes Routing mode.

Return value

Type Description
Promise<void> Promise used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if can not get the delegate, only throw in standard system.
100004 if the named route is not exist.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
import router from '@ohos.router';
let routerF:Router = uiContext.getRouter();
class RouterTmp{
  Standard:router.RouterMode = router.RouterMode.Standard
}
let rtm:RouterTmp = new RouterTmp()
try {
  routerF.replaceNamedRoute({
    name: 'myPage',
    params: {
      data1: 'message'
    }
  }, rtm.Standard)
} catch (err) {
  let message = (err as BusinessError).message;
  let code = (err as BusinessError).code;
  console.error(`replaceNamedRoute failed, code is ${code}, message is ${message}`);
}

replaceNamedRoute

replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void

Replaces the current page with another one using the named route and destroys the current page. This API uses a promise to return the result.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.NamedRouterOptions Yes Description of the new page.
mode router.RouterMode Yes Routing mode.
callback AsyncCallback<void> Yes Callback used to return the result.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found, only throw in standard system.
100004 if the named route is not exist.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
import router from '@ohos.router';
let routerF:Router = uiContext.getRouter();
class RouterTmp{
  Standard:router.RouterMode = router.RouterMode.Standard
}
let rtm:RouterTmp = new RouterTmp()
routerF.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');
});

back

back(options?: router.RouterOptions ): void

Returns to the previous page or a specified page.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.RouterOptions No Description of the page. The url parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If no URL is set, the application returns to the previous page, and the page is not rebuilt. The page in the page stack is not reclaimed. It will be reclaimed after being popped up.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router: Router = uiContext.getRouter();
router.back({url:'pages/detail'});    

clear

clear(): void

Clears all historical pages in the stack and retains only the current page at the top of the stack.

System capability: SystemCapability.ArkUI.ArkUI.Full

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router: Router = uiContext.getRouter();
router.clear();    

getLength

getLength(): string

Obtains the number of pages in the current stack.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Type Description
string Number of pages in the stack. The maximum value is 32.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router: Router = uiContext.getRouter();
let size = router.getLength();        
console.log('pages stack size = ' + size);    

getState

getState(): router.RouterState

Obtains state information about the current page.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Type Description
RouterState Page routing state.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router: Router = uiContext.getRouter();
let page = router.getState();
console.log('current index = ' + page.index);
console.log('current name = ' + page.name);
console.log('current path = ' + page.path);

showAlertBeforeBackPage

showAlertBeforeBackPage(options: router.EnableAlertOptions): void

Enables the display of a confirm dialog box before returning to the previous page.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options router.EnableAlertOptions Yes Description of the dialog box.

Error codes

For details about the error codes, see Router Error Codes.

ID Error Message
100001 if UI execution context not found.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
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

Disables the display of a confirm dialog box before returning to the previous page.

System capability: SystemCapability.ArkUI.ArkUI.Full

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router: Router = uiContext.getRouter();
router.hideAlertBeforeBackPage();    

getParams

getParams(): Object

Obtains the parameters passed from the page that initiates redirection to the current page.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Type Description
object Parameters passed from the page that initiates redirection to the current page.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let router: Router = uiContext.getRouter();
router.getParams();

PromptAction

In the following API examples, you must first use getPromptAction() in UIContext to obtain a PromptAction instance, and then call the APIs using the obtained instance.

showToast

showToast(options: promptAction.ShowToastOptions): void

Shows a toast in the given settings.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options promptAction.ShowToastOptions Yes Toast options.

Error codes

For details about the error codes, see promptAction Error Codes.

ID Error Message
100001 if UI execution context not found.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
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}`);
};

showDialog

showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse>): void

Shows a dialog box in the given settings. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options promptAction.ShowDialogOptions Yes Dialog box options.
callback AsyncCallback<promptAction.ShowDialogSuccessResponse> Yes Callback used to return the dialog box response result.

Error codes

For details about the error codes, see promptAction Error Codes.

ID Error Message
100001 if UI execution context not found.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
class ButtonsModel {
  text: string = ""
  color: string = ""
}
let promptAction: PromptAction = uiContext.getPromptAction();
try {
  promptAction.showDialog({
    title: 'showDialog Title Info',
    message: 'Message Info',
    buttons: [
      {
        text: 'button1',
        color: '#000000'
      } as ButtonsModel,
      {
        text: 'button2',
        color: '#000000'
      } as ButtonsModel
    ]
  }, (err, data) => {
    if (err) {
      console.info('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>

Shows a dialog box. This API uses a promise to return the result synchronously.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options promptAction.ShowDialogOptions Yes Dialog box options.

Return value

Type Description
Promise<promptAction.ShowDialogSuccessResponse> Promise used to return the dialog box response result.

Error codes

For details about the error codes, see promptAction Error Codes.

ID Error Message
100001 if UI execution context not found.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let promptAction: PromptAction = uiContext.getPromptAction();
try {
  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.info('showDialog error: ' + err);
    })
} 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}`);
};

showActionMenu

showActionMenu(options: promptAction.ActionMenuOptions, callback:promptAction.ActionMenuSuccessResponse):void

Shows an action menu in the given settings. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options promptAction.ActionMenuOptions Yes Action menu options.
callback promptAction.ActionMenuSuccessResponse Yes Callback used to return the action menu response result.

Error codes

For details about the error codes, see promptAction Error Codes.

ID Error Message
100001 if UI execution context not found.

Example

import { PromptAction } from '@ohos.arkui.UIContext';
import promptAction from '@ohos.promptAction';
import { BusinessError } from '@ohos.base';

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>

Shows an action menu. This API uses a promise to return the result synchronously.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options promptAction.ActionMenuOptions Yes Action menu options.

Return value

Type Description
Promise<promptAction.ActionMenuSuccessResponse> Promise used to return the action menu response result.

Error codes

For details about the error codes, see promptAction Error Codes.

ID Error Message
100001 if UI execution context not found.

Example

import { ComponentUtils, Font, PromptAction, Router, UIInspector, MediaQuery } from '@ohos.arkui.UIContext';
import { BusinessError } from '@ohos.base';
let promptAction: PromptAction = uiContext.getPromptAction();
try {
  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.info('showActionMenu error: ' + err);
    })
} 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}`);
};