当前仓库属于关闭状态,部分功能使用受限,详情请查阅 仓库状态说明
1.4K Star 7.4K Fork 8.2K

OpenHarmony/docs
关闭

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
.gitee/ISSUE_TEMPLATE
docker
en
application-dev
IDL
accessibility
ads-service
ai
application-models
application-test
arkts-utils
basic-services
calendarmanager
connectivity
contacts
database
device-usage-statistics
device
dfx
displaymanager
distributedservice
enterprise-device-management
faqs
ffrt
file-management
form
graphics
graphics3d
inputmethod
internationalization
ipc
mdm
media
napi
network
notification
performance
public_sys-resources
quick-start
reference
apis-ability-kit
apis-accessibility-kit
apis-ads-kit
apis-arkdata
apis-arkgraphics2d
apis-arkgraphics3d
apis-arkts
apis-arkui
arkui-js-lite
arkui-js
arkui-ts
figures
js-service-widget-ui
Readme-EN.md
_a_r_k_u_i___text_picker_cascade_range_content.md
_a_r_k_u_i___text_picker_range_content.md
_ark_u_i___animate_complete_callback.md
_ark_u_i___attribute_item.md
_ark_u_i___color_stop.md
_ark_u_i___context_callback.md
_ark_u_i___event_module.md
_ark_u_i___expected_frame_rate_range.md
_ark_u_i___int_offset.md
_ark_u_i___int_size.md
_ark_u_i___margin.md
_ark_u_i___native_animate_a_p_i__1.md
_ark_u_i___native_dialog_a_p_i__1.md
_ark_u_i___native_dialog_a_p_i__2.md
_ark_u_i___native_gesture_a_p_i__1.md
_ark_u_i___native_module.md
_ark_u_i___native_node_a_p_i__1.md
_ark_u_i___node_component_event.md
_ark_u_i___rect.md
_ark_u_i___rotation_options.md
_ark_u_i___scale_options.md
_ark_u_i___string_async_event.md
_ark_u_i___text_change_event.md
_ark_u_i___translation_options.md
_native_display_manager___cutout_info.md
_native_display_manager___display_color_space.md
_native_display_manager___display_hdr_format.md
_native_display_manager___display_info.md
_native_display_manager___displays_info.md
_native_display_manager___rect.md
_o_h___display_manager.md
_o_h___native_x_component.md
_o_h___native_x_component___callback.md
_o_h___native_x_component___expected_rate_range.md
_o_h___native_x_component___mouse_event.md
_o_h___native_x_component___mouse_event___callback.md
_o_h___native_x_component___touch_event.md
_o_h___native_x_component___touch_point.md
_window_manager___avoid_area.md
_window_manager___native_module.md
_window_manager___rect.md
_window_manager___window_properties.md
arkui_native_interface_accessibility.md
drag__and__drop_8h.md
drawable__descriptor_8h.md
errorcode-animator.md
errorcode-bindSheet.md
errorcode-display.md
errorcode-drag-event.md
errorcode-focus.md
errorcode-image-analyzer.md
errorcode-promptAction.md
errorcode-router.md
errorcode-scroll.md
errorcode-system-resource.md
errorcode-uiappearance.md
errorcode-window.md
ive_display_manager___waterfall_display_area_rects.md
js-apis-StateManagement.md
js-apis-animator.md
js-apis-application-windowExtensionAbility-sys.md
js-apis-arkui-AttributeUpdater.md
js-apis-arkui-ComponentContent.md
js-apis-arkui-Content.md
js-apis-arkui-NodeContent.md
js-apis-arkui-Prefetcher.md
js-apis-arkui-UIContext-sys.md
js-apis-arkui-UIContext.md
js-apis-arkui-builderNode.md
js-apis-arkui-componentSnapshot.md
js-apis-arkui-componentUtils.md
js-apis-arkui-dragController.md
js-apis-arkui-drawableDescriptor-sys.md
js-apis-arkui-drawableDescriptor.md
js-apis-arkui-frameNode.md
js-apis-arkui-graphics.md
js-apis-arkui-inspector.md
js-apis-arkui-node.md
js-apis-arkui-nodeController.md
js-apis-arkui-observer.md
js-apis-arkui-performancemonitor-sys.md
js-apis-arkui-renderNode.md
js-apis-arkui-shape.md
js-apis-arkui-theme.md
js-apis-arkui-uiExtension-sys.md
js-apis-arkui-uiExtension.md
js-apis-arkui-xcomponentNode.md
js-apis-curve.md
js-apis-devicestatus-draginteraction-sys.md
js-apis-display-sys.md
js-apis-display.md
js-apis-font.md
js-apis-getContext.md
js-apis-inner-application-windowExtensionContext-sys.md
js-apis-matrix4.md
js-apis-measure.md
js-apis-mediaquery.md
js-apis-pipWindow.md
js-apis-plugincomponent-sys.md
js-apis-plugincomponent.md
js-apis-postCardAction.md
js-apis-prompt.md
js-apis-promptAction-sys.md
js-apis-promptAction.md
js-apis-router.md
js-apis-screen-sys.md
js-apis-screenshot-sys.md
js-apis-screenshot.md
js-apis-system-app.md
js-apis-system-configuration.md
js-apis-system-mediaquery.md
js-apis-system-prompt.md
js-apis-system-router.md
js-apis-uiExtensionHost-sys.md
js-apis-uiappearance-sys.md
js-apis-window-sys.md
js-apis-window.md
js-apis-windowAnimationManager-sys.md
native__animate_8h.md
native__dialog_8h.md
native__gesture_8h.md
native__interface_8h.md
native__interface__accessibility_8h.md
native__interface__focus_8h.md
native__interface__xcomponent_8h.md
native__key_event_8h.md
native__node_8h.md
native__node__napi_8h.md
native__type_8h.md
native__xcomponent__key__event_8h.md
oh__display__capture_8h.md
oh__display__info_8h.md
oh__display__manager_8h.md
oh__window_8h.md
oh__window__comm_8h.md
oh__window__event__filter_8h.md
styled__string_8h.md
ui__input__event_8h.md
union_ark_u_i___number_value.md
apis-arkweb
apis-asset-store-kit
apis-audio-kit
apis-avcodec-kit
apis-avsession-kit
apis-backgroundtasks-kit
apis-basic-services-kit
apis-calendar-kit
apis-camera-kit
apis-connectivity-kit
apis-contacts-kit
apis-core-file-kit
apis-crypto-architecture-kit
apis-data-protection-kit
apis-device-certificate-kit
apis-distributedservice-kit
apis-driverdevelopment-kit
apis-drm-kit
apis-ffrt-kit
apis-form-kit
apis-image-kit
apis-ime-kit
apis-input-kit
apis-ipc-kit
apis-localization-kit
apis-location-kit
apis-mdm-kit
apis-media-kit
apis-media-library-kit
apis-mindspore-lite-kit
apis-multimodalawareness-kit
apis-network-kit
apis-neural-network-runtime-kit
apis-notification-kit
apis-performance-analysis-kit
apis-sensor-service-kit
apis-telephony-kit
apis-test-kit
apis-universal-keystore-kit
apis-user-authentication-kit
common
figures
native-lib
Readme-EN.md
development-intro.md
errorcode-universal.md
syscap-list.md
syscap.md
security
task-management
telephony
tools
ui
web
webgl
windowmanager
Readme-EN.md
application-dev-guide-for-gitee.md
application-dev-guide.md
website.md
contribute
design
device-dev
figures
readme
release-notes
third-party-components
Legal-Notices.md
OpenHarmony-Overview.md
glossary.md
readme.md
website.md
zh-cn
.gitattributes
.gitignore
CODEOWNERS
DCO.txt
LICENSE
OAT.xml
README.md
README_zh.md
fix.patch
image.png
克隆/下载
js-apis-promptAction.md 53.96 KB
一键复制 编辑 原始数据 按行查看 历史
ester.zhou 提交于 4个月前 . Update docs (74930)

@ohos.promptAction (Prompt)

The PromptAction module provides APIs for creating and showing toasts, dialog boxes, and action menus.

NOTE

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

This module cannot be used in the file declaration of the UIAbility. In other words, the APIs of this module can be used only after a component instance is created; they cannot be called in the lifecycle of the UIAbility.

The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see UIContext. Except for UI-less scenarios such as ServiceExtension, it is recommended that you use the dialog APIs provided by UIContext.

Since API version 10, you can use the getPromptAction API in UIContext to obtain the PromptAction object associated with the current UI context.

Modules to Import

import { promptAction } from '@kit.ArkUI';

promptAction.showToast

showToast(options: ShowToastOptions): void

Shows a toast.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options ShowToastOptions Yes Toast options.

Error codes

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

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001 Internal error.

Example

import { promptAction } from '@kit.ArkUI'
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct toastExample {
  build() {
    Column() {
      Button('Show toast').fontSize(20)
        .onClick(() => {
          try {
            promptAction.showToast({
              message: 'Hello World',
              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}`);
          };
        })
    }.height('100%').width('100%').justifyContent(FlexAlign.Center)
  }
}

Below is a toast in API version 11 and earlier versions.

en-us_image_0001

Below is a toast in API version 12 and later versions.

en-us_image_0001

promptAction.showDialog

showDialog(options: ShowDialogOptions): Promise<ShowDialogSuccessResponse>

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

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options ShowDialogOptions Yes Dialog box options.

Return value

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

Error codes

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

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001 Internal error.

Example

import { promptAction } from '@kit.ArkUI'

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);
  })

en-us_image_0002

promptAction.showDialog

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

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

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

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

Error codes

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

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001 Internal error.

Example

import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

try {
  promptAction.showDialog({
    title: 'showDialog Title Info',
    message: 'Message Info',
    buttons: [
      {
        text: 'button1',
        color: '#000000'
      },
      {
        text: 'button2',
        color: '#000000'
      }
    ]
  }, (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}`);
};

en-us_image_0004

When the showInSubWindow attribute is set to true, the toast can be displayed outside the window.

import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

try {
  promptAction.showDialog({
    title: 'showDialog Title Info',
    message: 'Message Info',
    isModal: true,
    showInSubWindow: true,
    buttons: [
      {
        text: 'button1',
        color: '#000000'
      },
      {
        text: 'button2',
        color: '#000000'
      }
    ]
  }, (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}`);
};

en-us_image_0002_showinsubwindow

promptAction.showActionMenu

showActionMenu(options: ActionMenuOptions, callback: AsyncCallback<ActionMenuSuccessResponse>):void

Shows an action menu. This API uses a callback to return the result asynchronously.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

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

Error codes

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

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001 Internal error.

Example

import { promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';

try {
  promptAction.showActionMenu({
    title: 'Title Info',
    buttons: [
      {
        text: 'item1',
        color: '#666666'
      },
      {
        text: 'item2',
        color: '#000000'
      },
    ]
  }, (err, data) => {
    if (err) {
      console.info('showActionMenu err: ' + err);
      return;
    }
    console.info('showActionMenu 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}`);
};

en-us_image_0005

promptAction.showActionMenu

showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse>

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

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options ActionMenuOptions Yes Action menu options.

Return value

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

Error codes

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

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001 Internal error.

Example

import { promptAction } from '@kit.ArkUI';

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);
  })

en-us_image_0006

promptAction.openCustomDialog11+

openCustomDialog(options: CustomDialogOptions): Promise<number>

Opens a custom dialog box.

This API cannot be used in **ServiceExtension**.

isModal = true and showInSubWindow = true cannot be used at the same time.

By default, the width of the dialog box in portrait mode is the width of the window where it is located minus the left and right margins (40 vp for 2-in-1 devices and 16 vp for other devices), and the maximum width is 400 vp.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options CustomDialogOptions Yes Content of the custom dialog box.

Return value

Type Description
Promise<number> ID of the custom dialog box, which can be used in closeCustomDialog.

Error codes

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

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001 Internal error.

Example

import { promptAction } from '@kit.ArkUI'
import { BusinessError } from '@kit.BasicServicesKit'

@Entry
@Component
struct Index {
  private customDialogComponentId: number = 0

  @Builder
  customDialogComponent() {
    Column() {
      Text('Dialog box').fontSize(30)
      Row({ space: 50 }) {
        Button("OK").onClick(() => {
          try {
            promptAction.closeCustomDialog(this.customDialogComponentId)
          } catch (error) {
            let message = (error as BusinessError).message;
            let code = (error as BusinessError).code;
            console.error(`closeCustomDialog error code is ${code}, message is ${message}`);
          }
        })
        Button("Cancel").onClick(() => {
          try {
            promptAction.closeCustomDialog(this.customDialogComponentId)
          } catch (error) {
            let message = (error as BusinessError).message;
            let code = (error as BusinessError).code;
            console.error(`closeCustomDialog error code is ${code}, message is ${message}`);
          }
        })
      }
    }.height(200).padding(5).justifyContent(FlexAlign.SpaceBetween)
  }

  build() {
    Row() {
      Column({ space: 20 }) {
        Text('In-component dialog box')
          .fontSize(30)
          .onClick(() => {
            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
            })
              .catch((error: BusinessError) => {
                console.error(`openCustomDialog error code is ${error.code}, message is ${error.message}`)
              })
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

This example demonstrates how to set styles of a dialog box, including the width, height, background color, and shadow.

import { promptAction, LevelMode, ImmersiveMode } from '@kit.ArkUI'

let customDialogId: number = 0

@Builder
function customDialogBuilder() {
  Column() {
    Text('Custom dialog Message').fontSize(10)
    Row() {
      Button("OK").onClick(() => {
        promptAction.closeCustomDialog(customDialogId)
      })
      Blank().width(50)
      Button("Cancel").onClick(() => {
        promptAction.closeCustomDialog(customDialogId)
      })
    }
  }
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  @Builder
  customDialogComponent() {
    customDialogBuilder()
  }

  build() {
    Row() {
      Column() {
        Text(this.message).id("test_text")
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            const node: FrameNode | null = this.getUIContext().getFrameNodeById("test_text") || null;
            promptAction.openCustomDialog({
              builder: () => {
                this.customDialogComponent()
              },
              keyboardAvoidMode: KeyboardAvoidMode.NONE,
              showInSubWindow: false,
              offset: { dx: 5, dy: 5 },
              backgroundColor: 0xd9ffffff,
              cornerRadius: 20,
              width: '80%',
              height: 200,
              borderWidth: 1,
              borderStyle: BorderStyle.Dashed, // borderStyle must be used with borderWidth in pairs.
              borderColor: Color.Blue, // borderColor must be used with borderWidth in pairs.
              shadow: ({
                radius: 20,
                color: Color.Grey,
                offsetX: 50,
                offsetY: 0
              }),
              levelMode: LevelMode.EMBEDDED,
              levelUniqueId: node?.getUniqueId(),
              immersiveMode: ImmersiveMode.DEFAULT,
            }).then((dialogId: number) => {
              customDialogId = dialogId
            })
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

en-us_image_0007

This example shows how to implement a dialog box on a page.

// Index.ets
import { promptAction, LevelMode, ImmersiveMode, router } from '@kit.ArkUI'

let customDialogId: number = 0

@Builder
function customDialogBuilder() {
  Column() {
    Text('Custom dialog Message').fontSize(10).height(100)
    Row() {
      Button("Next").onClick(() => {
        router.pushUrl({url: 'pages/Next'})
      })
      Blank().width(50)
      Button("Close").onClick(() => {
        promptAction.closeCustomDialog(customDialogId)
      })
    }
  }.padding(20)
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  @Builder
  customDialogComponent() {
    customDialogBuilder()
  }

  build() {
    Row() {
      Column() {
        Text(this.message).id("test_text")
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            const node: FrameNode | null = this.getUIContext().getFrameNodeById("test_text") || null;
            promptAction.openCustomDialog({
              builder: () => {
                this.customDialogComponent()
              },
              levelMode: LevelMode.EMBEDDED,
              levelUniqueId: node?.getUniqueId(),
              immersiveMode: ImmersiveMode.DEFAULT,
            }).then((dialogId: number) => {
              customDialogId = dialogId
            })
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
// Next.ets
import { router } from '@kit.ArkUI'

@Entry
@Component
struct Next {
  @State message: string = 'Back'

  build() {
    Row() {
      Column() {
        Button(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            router.back()
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

embedded_dialog

promptAction.closeCustomDialog11+

closeCustomDialog(dialogId: number): void

Closes the specified custom dialog box.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
dialogId number Yes ID of the custom dialog box to close. It is returned from openCustomDialog.

Error codes

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

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2.Incorrect parameters types; 3. Parameter verification failed.
100001 Internal error.

Example

See the example of promptAction.openCustomDialog.

ShowToastOptions

Describes the options for showing the toast.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Mandatory Description
message string | Resource Yes Text to display.
NOTE
The default font is 'Harmony Sans'. Other fonts are not supported.
Atomic service API: This API can be used in atomic services since API version 11.
duration number No Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.
Atomic service API: This API can be used in atomic services since API version 11.
bottom string | number No Distance from the bottom of the toast to the navigation bar. In ToastShowMode.TOP_MOST mode, if the soft keyboard is raised and the bottom value is too small, the toast will automatically avoid being blocked by the soft keyboard by moving up 80 vp above it. In ToastShowMode.DEFAULT mode, the toast will move up by the height of the soft keyboard.
Default value: 80vp
NOTE
When there is no navigation bar at the bottom, bottom sets the distance from the bottom of the toast to the bottom of the window.
If the alignment property is set, bottom will not take effect.
Atomic service API: This API can be used in atomic services since API version 11.
showMode11+ ToastShowMode No Whether to show the toast above the application.
Default value: ToastShowMode.DEFAULT, which means to show the toast in the application.
Atomic service API: This API can be used in atomic services since API version 12.
alignment12+ Alignment No Alignment mode.
Default value: undefined, indicating bottom start
Atomic service API: This API can be used in atomic services since API version 12.
offset12+ Offset No Offset in the specified alignment mode.
Default value: { dx: 0, dy: 0 }, indicating no offset
NOTE
Only values in the px unit are accepted. To use the vp unit, convert them to px first.
Atomic service API: This API can be used in atomic services since API version 12.
backgroundColor12+ ResourceColor No Background color of the toast.
Default value: Color.Transparent
NOTE
When backgroundColor is set to a non-transparent color, backgroundBlurStyle must be set to BlurStyle.NONE; otherwise, the color display may not meet the expected effect.
Atomic service API: This API can be used in atomic services since API version 12.
textColor12+ ResourceColor No Font color of the toast.
Default value: Color.Black
Atomic service API: This API can be used in atomic services since API version 12.
backgroundBlurStyle12+ BlurStyle No Background blur style of the toast.
Default value: BlurStyle.COMPONENT_ULTRA_THICK
NOTE
Setting this parameter to BlurStyle.NONE disables the background blur. When backgroundBlurStyle is set to a value other than NONE, do not set backgroundColor. If you do, the color display may not produce the expected visual effect.
Atomic service API: This API can be used in atomic services since API version 12.
shadow12+ ShadowOptions | ShadowStyle No Background shadow of the toast.
Default value: ShadowStyle.OUTER_DEFAULT_MD
Atomic service API: This API can be used in atomic services since API version 12.
enableHoverMode14+ boolean No Whether to enable the hover state.
Default value: False, meaning not to enable the hover state.
Atomic service API: This API can be used in atomic services since API version 14.
hoverModeArea14+ HoverModeAreaType No Display area of the toast in the hover state.
Default value: HoverModeAreaType.BOTTOM_SCREEN, indicating that the toast is displayed in the lower half screen
Atomic service API: This API can be used in atomic services since API version 14.

ToastShowMode11+

Describes the mode in which the toast is shown.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Value Description
DEFAULT 0 The toast is shown within the application.
TOP_MOST 1 The toast is shown above the application.

ShowDialogOptions

Describes the options for showing the dialog box.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Mandatory Description
title string | Resource No Title of the dialog box.
Atomic service API: This API can be used in atomic services since API version 11.
message string | Resource No Text body.
Atomic service API: This API can be used in atomic services since API version 11.
buttons Array<Button> No Array of buttons in the dialog box. The array structure is {text:'button', color: '#666666'}. More than one button is supported.
Atomic service API: This API can be used in atomic services since API version 11.
alignment10+ DialogAlignment No Alignment mode of the dialog box in the vertical direction.
Default value: DialogAlignment.Default
NOTE
If showInSubWindow is set to true in UIExtension, the dialog box is aligned with the host window based on UIExtension.
Atomic service API: This API can be used in atomic services since API version 11.
offset10+ Offset No Offset of the dialog box based on the alignment settings.
Default value: { dx: 0 , dy: 0 }
Atomic service API: This API can be used in atomic services since API version 11.
maskRect10+ Rectangle No Mask area of the dialog box. Events outside the mask area are transparently transmitted, and events within the mask area are not.
Default value: { x: 0, y: 0, width: '100%', height: '100%' }
NOTE
maskRect does not take effect when showInSubWindow is set to true.
Atomic service API: This API can be used in atomic services since API version 11.
showInSubWindow11+ boolean No Whether to show the dialog box in a subwindow when it is not in the main window.
Default value: false, meaning the dialog box is displayed within the application, not in a separate subwindow
NOTE
A dialog box whose showInSubWindow attribute is true cannot trigger the display of another dialog box whose showInSubWindow attribute is also true.
Atomic service API: This API can be used in atomic services since API version 12.
isModal11+ boolean No Whether the dialog box is a modal. A modal dialog box has a mask applied, while a non-modal dialog box does not.
Default value: true
Atomic service API: This API can be used in atomic services since API version 12.
backgroundColor12+ ResourceColor No Background color of the dialog box.
Default value: Color.Transparent
NOTE
When backgroundColor is set to a non-transparent color, backgroundBlurStyle must be set to BlurStyle.NONE; otherwise, the color display may not meet the expected effect.
Atomic service API: This API can be used in atomic services since API version 12.
backgroundBlurStyle12+ BlurStyle No Background blur style of the dialog box.
Default value: BlurStyle.COMPONENT_ULTRA_THICK
NOTE
Setting this parameter to BlurStyle.NONE disables the background blur. When backgroundBlurStyle is set to a value other than NONE, do not set backgroundColor. If you do, the color display may not produce the expected visual effect.
Atomic service API: This API can be used in atomic services since API version 12.
shadow12+ ShadowOptions | ShadowStyle No Shadow of the dialog box.
Default value on 2-in-1 devices: ShadowStyle.OUTER_FLOATING_MD when the dialog box is focused and ShadowStyle.OUTER_FLOATING_SM otherwise
Atomic service API: This API can be used in atomic services since API version 12.
enableHoverMode14+ boolean No Whether to enable the hover state.
Default value: false, meaning not to enable the hover state.
Atomic service API: This API can be used in atomic services since API version 14.
hoverModeArea14+ HoverModeAreaType No Display area of the dialog box in the hover state.
Default value: HoverModeAreaType.BOTTOM_SCREEN
Atomic service API: This API can be used in atomic services since API version 14.
levelMode15+ LevelMode No Display level of the dialog box.
NOTE
- Default value: LevelMode.OVERLAY
- This parameter takes effect only when showInSubWindow is set to false.
Atomic service API: This API can be used in atomic services since API version 15.
levelUniqueId15+ number No Unique ID of the node under the display level for the page-level dialog box.
NOTE
- This parameter takes effect only when levelMode is set to LevelMode.EMBEDDED.
Atomic service API: This API can be used in atomic services since API version 15.
immersiveMode15+ ImmersiveMode No Overlay effect for the page-level dialog box.
NOTE
- Default value: ImmersiveMode.DEFAULT
- This parameter takes effect only when levelMode is set to LevelMode.EMBEDDED.
Atomic service API: This API can be used in atomic services since API version 15.

ShowDialogSuccessResponse

Describes the dialog box response result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Mandatory Description
index number Yes Index of the selected button in the buttons array.

ActionMenuOptions

Describes the options for showing the action menu.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Mandatory Description
title string | Resource No Title of the dialog box.
Atomic service API: This API can be used in atomic services since API version 11.
buttons [Button,Button?,Button?,Button?,Button?,Button?] Yes Array of menu item buttons. The array structure is {text:'button', color: '#666666'}. Up to six buttons are supported. If there are more than six buttons, only the first six buttons will be displayed.
Atomic service API: This API can be used in atomic services since API version 11.
showInSubWindow11+ boolean No Whether to show the dialog box in a subwindow when it is not in the main window.
Default value: false, indicating that the dialog box is not displayed in the subwindow
NOTE
- A dialog box whose showInSubWindow attribute is true cannot trigger the display of another dialog box whose showInSubWindow attribute is also true.
- If showInSubWindow is set to true in UIExtension, the dialog box is aligned with the host window based on UIExtension.
Atomic service API: This API can be used in atomic services since API version 12.
isModal11+ boolean No Whether the dialog box is a modal. A modal dialog box has a mask applied, while a non-modal dialog box does not.
Default value: true
Atomic service API: This API can be used in atomic services since API version 12.
levelMode15+ LevelMode No Display level of the dialog box.
NOTE
- Default value: LevelMode.OVERLAY
- This parameter takes effect only when showInSubWindow is set to false.
Atomic service API: This API can be used in atomic services since API version 15.
levelUniqueId15+ number No Unique ID of the node under the display level for the page-level dialog box.
NOTE
- This parameter takes effect only when levelMode is set to LevelMode.EMBEDDED.
Atomic service API: This API can be used in atomic services since API version 15.
immersiveMode15+ ImmersiveMode No Overlay effect for the page-level dialog box.
NOTE
- Default value: ImmersiveMode.DEFAULT
- This parameter takes effect only when levelMode is set to LevelMode.EMBEDDED.
Atomic service API: This API can be used in atomic services since API version 15.

ActionMenuSuccessResponse

Describes the action menu response result.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Mandatory Description
index number Yes Index of the selected button in the buttons array, starting from 0.

CustomDialogOptions11+

Defines the options of a custom dialog box, which inherit from BaseDialogOptions.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Mandatory Description
builder CustomBuilder Yes Content of the custom dialog box.
NOTE
The builder needs to be assigned an arrow function in the following format: () => { this.XXX() }, where XXX indicates the internal builder name.
If you are working with a global builder, you need to call it within a local builder within a component.
The aspect ratio of the root node of a builder is relative to the size of the dialog box container.
The aspect ratio of a non-root node is relative to the size of its parent node.
Atomic service API: This API can be used in atomic services since API version 12.
backgroundColor 12+ ResourceColor No Background color of the dialog box.
Default value: Color.Transparent
NOTE
When backgroundColor is set to a non-transparent color, backgroundBlurStyle must be set to BlurStyle.NONE; otherwise, the color display may not meet the expected effect.
cornerRadius12+ Dimension | BorderRadiuses No Radius of the rounded corners of the background.
You can set separate radiuses for the four rounded corners.
Default value: { topLeft: '32vp', topRight: '32vp', bottomLeft: '32vp', bottomRight: '32vp' }
The radius of the rounded corners is subject to the component size. Its maximum value is half of the component width or height. If the value is negative, the default value is used.
When set to a percentage, the value defines the radius as a percentage of the parent component's width or height.
borderWidth12+ Dimension | EdgeWidths No Border width of the dialog box.
You can set the width for all four sides or set separate widths for individual sides.
Default value: 0
When set to a percentage, the value defines the border width as a percentage of the parent dialog box's width.
If the left and right borders are greater than its width, or the top and bottom borders are greater than its height, the dialog box may not display as expected.
borderColor12+ ResourceColor | EdgeColors No Border color of the dialog box.
Default value: Color.Black
borderColor must be used with borderWidth in pairs.
borderStyle12+ BorderStyle | EdgeStyles No Border style of the dialog box.
Default value: BorderStyle.Solid
borderStyle must be used with borderWidth in pairs.
width12+ Dimension No Width of the dialog box.
NOTE
- Default maximum width of the dialog box: 400 vp
- When this parameter is set to a percentage, the reference width of the dialog box is the width of the window where the dialog box is located. You can decrease or increase the width as needed.
height12+ Dimension No Height of the dialog box.
NOTE
- Default maximum height of the dialog box: 0.9 x (Window height – Safe area)
- When this parameter is set to a percentage, the reference height of the dialog box is the height of the window where the dialog box is located minus the safe area. You can decrease or increase the height as needed.
shadow12+ ShadowOptions | ShadowStyle No Shadow of the dialog box.
Default value on 2-in-1 devices: ShadowStyle.OUTER_FLOATING_MD when the dialog box is focused and ShadowStyle.OUTER_FLOATING_SM otherwise
backgroundBlurStyle12+ BlurStyle No Background blur style of the dialog box.
Default value: BlurStyle.COMPONENT_ULTRA_THICK
NOTE
Setting this parameter to BlurStyle.NONE disables the background blur. When backgroundBlurStyle is set to a value other than NONE, do not set backgroundColor. If you do, the color display may not produce the expected visual effect.

BaseDialogOptions11+

Defines the options of the dialog box.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Mandatory Description
maskRect Rectangle No Mask area.
Default value: { x: 0, y: 0, width: '100%', height: '100%' }
NOTE
maskRect does not take effect when showInSubWindow is set to true.
Atomic service API: This API can be used in atomic services since API version 12.
alignment DialogAlignment No Alignment mode of the dialog box in the vertical direction.
Default value: DialogAlignment.Default
NOTE
If showInSubWindow is set to true in UIExtension, the dialog box is aligned with the host window based on UIExtension.
Atomic service API: This API can be used in atomic services since API version 12.
offset Offset No Offset of the dialog box based on the alignment settings.
Default value: { dx: 0 , dy: 0 }
Atomic service API: This API can be used in atomic services since API version 12.
isModal boolean No Whether the dialog box is a modal. A modal dialog box has a mask applied, while a non-modal dialog box does not.
Default value: true
Atomic service API: This API can be used in atomic services since API version 12.
showInSubWindow boolean No Whether to show the dialog box in a subwindow when it is not in the main window.
Default value: false, meaning the dialog box is displayed within the application, not in a separate subwindow
Atomic service API: This API can be used in atomic services since API version 12.
onWillDismiss12+ Callback<DismissDialogAction> No Callback for interactive dismissal of the dialog box.
NOTE
1. If this callback is registered, the dialog box will not be dismissed immediately after the user touches the mask or the Back button, presses the Esc key, or swipes left or right on the screen. The reason parameter in the callback is used to determine whether the dialog box can be dismissed. The reason returned by the component does not support the value CLOSE_BUTTON.
2. In the onWillDismiss callback, another onWillDismiss callback is not allowed.
Atomic service API: This API can be used in atomic services since API version 12.
autoCancel12+ boolean No Whether to dismiss the dialog box when the mask is touched. The value true means to dismiss the dialog box when the mask is touched, and false means the opposite.
Default value: true
Atomic service API: This API can be used in atomic services since API version 12.
maskColor12+ ResourceColor No Mask color.
Default value: 0x33000000
Atomic service API: This API can be used in atomic services since API version 12.
transition12+ TransitionEffect No Transition effect for the entrance and exit of the dialog box.
NOTE
1. If this parameter is not set, the default effect is used.
2. Touching the Back button during the entrance animation pauses the entrance animation and starts the exit animation. The final effect is one obtained after the curves of the entrance and exit animations are combined.
3. Touching the Back button during the exit animation does not affect the animation playback. Touching the Back button again closes the application.
Atomic service API: This API can be used in atomic services since API version 12.
onDidAppear12+ () => void No Event callback when the dialog box appears.
NOTE
1. The normal timing sequence is as follows: onWillAppear > onDidAppear > (onDateAccept/onCancel/onDateChange) > onWillDisappear > onDidDisappear.
2. You can set the callback event for changing the dialog box display effect in onDidAppear. The settings take effect next time the dialog box appears.
3. If the user dismisses the dialog box immediately after it appears, onWillDisappear is invoked before onDidAppear.
4. If the dialog box is dismissed before its entrance animation is finished, this callback is not invoked.
Atomic service API: This API can be used in atomic services since API version 12.
onDidDisappear12+ () => void No Event callback when the dialog box disappears.
NOTE
The normal timing sequence is as follows: onWillAppear > onDidAppear > (onDateAccept/onCancel/onDateChange) > onWillDisappear > onDidDisappear.
Atomic service API: This API can be used in atomic services since API version 12.
onWillAppear12+ () => void No Event callback when the dialog box is about to appear.
NOTE
1. The normal timing sequence is as follows: onWillAppear > onDidAppear > (onDateAccept/onCancel/onDateChange) > onWillDisappear > onDidDisappear.
2. You can set the callback event for changing the dialog box display effect in onWillAppear. The settings take effect next time the dialog box appears.
Atomic service API: This API can be used in atomic services since API version 12.
onWillDisappear12+ () => void No Event callback when the dialog box is about to disappear.
NOTE
1. The normal timing sequence is as follows: onWillAppear > onDidAppear > (onDateAccept/onCancel/onDateChange) > onWillDisappear > onDidDisappear.
2. If the user dismisses the dialog box immediately after it appears, onWillDisappear is invoked before onDidAppear.
Atomic service API: This API can be used in atomic services since API version 12.
keyboardAvoidMode12+ KeyboardAvoidMode No How the dialog box avoids the soft keyboard when it is brought up.
Default value: KeyboardAvoidMode.DEFAULT
Atomic service API: This API can be used in atomic services since API version 12.
enableHoverMode14+ boolean No Whether to enable the hover state.
Default value: false, meaning not to enable the hover state.
Atomic service API: This API can be used in atomic services since API version 14.
hoverModeArea14+ HoverModeAreaType No Display area of the dialog box in the hover state.
Default value: HoverModeAreaType.BOTTOM_SCREEN
Atomic service API: This API can be used in atomic services since API version 14.
keyboardAvoidDistance15+ LengthMetrics No Minimum distance between the dialog box and the keyboard after keyboard avoidance is applied.
NOTE
- Default value: 16vp
- Default unit: vp
- This parameter takes effect only when keyboardAvoidMode is set to DEFAULT.
Atomic service API: This API can be used in atomic services since API version 16.
levelMode15+ LevelMode No Display level of the dialog box.
NOTE
- Default value: LevelMode.OVERLAY
- This parameter takes effect only when showInSubWindow is set to false.
Atomic service API: This API can be used in atomic services since API version 15.
levelUniqueId15+ number No Unique ID of the node under the display level for the page-level dialog box.
NOTE
- This parameter takes effect only when levelMode is set to LevelMode.EMBEDDED.
Atomic service API: This API can be used in atomic services since API version 15.
immersiveMode15+ ImmersiveMode No Overlay effect for the page-level dialog box.
NOTE
- Default value: ImmersiveMode.DEFAULT
- This parameter takes effect only when levelMode is set to LevelMode.EMBEDDED.
Atomic service API: This API can be used in atomic services since API version 15.

DismissDialogAction12+

Provides information about the action to dismiss the dialog box.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Attributes

Name Type Readable Writable Description
dismiss Callback<void> No No Callback for dismissing the dialog box. This API is called only when the dialog box needs to be exited.
reason DismissReason No No Reason why the dialog box cannot be dismissed. You must specify whether to dismiss the dialog box for each of the listed actions.

DismissReason12+

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Value Description
PRESS_BACK 0 Touching the Back button, swiping left or right on the screen, or pressing the Esc key.
TOUCH_OUTSIDE 1 Touching the mask.
CLOSE_BUTTON 2 Touching the Close button.
SLIDE_DOWN 3 Sliding down.
NOTE
This API is effective only in sheet transition.

LevelMode15+

Enumerates the display level modes of the dialog box.

Atomic service API: This API can be used in atomic services since API version 15.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Value Description
OVERLAY 0 The dialog box is displayed at the root node level of the application window and remain visible during navigation.
EMBEDDED 1 The dialog box is a child of the page's route/navigation and is hidden when the page is hidden.

ImmersiveMode15+

Enumerates the display area modes of the dialog box overlay within a page.

Atomic service API: This API can be used in atomic services since API version 15.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Value Description
DEFAULT 0 The dialog box overlay follows the layout constraints of its parent node.
EXTEND 1 The dialog box overlay can extend to cover the status bar and navigation bar for a more immersive look.

Button

Describes the menu item button in the action menu.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Mandatory Description
text string | Resource Yes Button text.
Atomic service API: This API can be used in atomic services since API version 11.
color string | Resource Yes Text color of the button.
Atomic service API: This API can be used in atomic services since API version 11.
primary12+ boolean No Whether the button responds to the Enter key by default when the dialog box has focus and the Tab key is not pressed for sequential focus navigation. If there are multiple buttons, set this parameter to true for only one button. Otherwise, no button will respond. Multiple dialog boxes can automatically gain focus and respond to user interactions in a sequential manner.
Atomic service API: This API can be used in atomic services since API version 12.
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
其他
1
https://gitee.com/openharmony/docs.git
git@gitee.com:openharmony/docs.git
openharmony
docs
docs
OpenHarmony-5.0.3-Release

搜索帮助