• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Alert Dialog Box (AlertDialog)
2
3You can set the text content and response callback for an alert dialog box.
4
5>  **NOTE**
6>
7> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
8>
9> 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](../js-apis-arkui-UIContext.md#uicontext).
10>
11> Since API version 10, you can use the [showAlertDialog](../js-apis-arkui-UIContext.md#showalertdialog) API in [UIContext](../js-apis-arkui-UIContext.md#uicontext), which ensures that the alert dialog box is shown in the intended UI instance.
12
13## AlertDialog
14
15### show
16
17static show(value: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions)
18
19Shows an alert dialog box.
20
21**Atomic service API**: This API can be used in atomic services since API version 11.
22
23**System capability**: SystemCapability.ArkUI.ArkUI.Full
24
25**Parameters**
26
27| Name  | Type | Mandatory| Description|
28| ---- | --------------- | -------- | -------- |
29| value | [AlertDialogParamWithConfirm](#alertdialogparamwithconfirm) \| [AlertDialogParamWithButtons](#alertdialogparamwithbuttons) \| [AlertDialogParamWithOptions](#alertdialogparamwithoptions10)<sup>10+</sup> | Yes| Options of the alert dialog box.|
30
31## AlertDialogParam
32
33**System capability**: SystemCapability.ArkUI.ArkUI.Full
34
35| Name                             | Type                                                        | Mandatory| Description                                                       |
36| --------------------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
37| title                             | [ResourceStr](ts-types.md#resourcestr)                       | No  | Title of the dialog box.<br>**Atomic service API**: This API can be used in atomic services since API version 11.                                                 |
38| subtitle<sup>10+</sup>            | [ResourceStr](ts-types.md#resourcestr)                       | No  | Subtitle of the dialog box.<br>**Atomic service API**: This API can be used in atomic services since API version 11.                                                |
39| message                           | [ResourceStr](ts-types.md#resourcestr)                       | Yes  | Content of the dialog box.<br>**Atomic service API**: This API can be used in atomic services since API version 11.                                                |
40| autoCancel                        | boolean                                                      | No  | Whether to close the dialog box when the overlay is clicked. The value **true** means to close the dialog box when the overlay is clicked, and **false** means the opposite.<br>Default value: **true**<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
41| cancel                            | () =&gt; void | No  | Callback invoked when the dialog box is closed after the overlay is clicked.<br>**Atomic service API**: This API can be used in atomic services since API version 11.                              |
42| alignment                         | [DialogAlignment](#dialogalignment)                  | No  | Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Default**<br>**Atomic service API**: This API can be used in atomic services since API version 11.<br>**NOTE**<br>If **showInSubWindow** is set to **true** in **UIExtension**, the dialog box is aligned with the host window based on **UIExtension**.|
43| offset                            | [Offset](ts-types.md#offset)                                 | No  | Offset of the dialog box relative to the alignment position.<br>Default value: **{ dx: 0 , dy: 0 }**<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
44| gridCount                         | number                                                       | No  | Number of grid columns occupied by the width of the dialog box.<br>Default value: **4**<br>**Atomic service API**: This API can be used in atomic services since API version 11.                   |
45| maskRect<sup>10+</sup>            | [Rectangle](#rectangle8)                             | No  | Mask area of the dialog box. Events outside the mask area are transparently transmitted, and events within the mask area are not.<br>Default value: **{ x: 0, y: 0, width: '100%', height: '100%' }**<br>**NOTE**<br>**maskRect** does not take effect when **showInSubWindow** is set to **true**.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
46| showInSubWindow<sup>11+</sup>     | boolean                                                      | No  | Whether to show the dialog box in a sub-window when the dialog box needs to be displayed outside the main window.<br>Default value: **false**<br>**NOTE**<br>A dialog box whose **showInSubWindow** attribute is **true** cannot trigger the display of another dialog box whose **showInSubWindow** attribute is also **true**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
47| isModal<sup>11+</sup>             | 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.<br>Default value: **true**<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
48| backgroundColor<sup>11+</sup>     | [ResourceColor](ts-types.md#resourcecolor)                   | No  | Background color of the dialog box.<br>Default value: **Color.Transparent**<br>**NOTE**<br>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.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
49| backgroundBlurStyle<sup>11+</sup> | [BlurStyle](ts-universal-attributes-background.md#blurstyle9)                 | No  | Background blur style of the dialog box.<br>Default value: **BlurStyle.COMPONENT_ULTRA_THICK**<br>**NOTE**<br>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.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
50| onWillDismiss<sup>12+</sup>       | Callback<[DismissDialogAction](#dismissdialogaction12)> | No  | Callback for interactive closure of the dialog box.<br>**NOTE**<br>1. If this callback is registered, the dialog box will not be closed 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 closed. The reason returned by the component does not support the value **CLOSE_BUTTON**.<br>2. In the **onWillDismiss** callback, another **onWillDismiss** callback is not allowed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
51| cornerRadius<sup>12+</sup>        |  [Dimension](ts-types.md#dimension10) \| [BorderRadiuses](ts-types.md#borderradiuses9) \| [LocalizedBorderRadiuses](ts-types.md#LocalizedBorderRadiuses12) | No  | Radius of the rounded corners of the background.<br>You can set separate radiuses for the four rounded corners.<br>Default value: **{ topLeft: '32vp', topRight: '32vp', bottomLeft: '32vp', bottomRight: '32vp' }**<br> 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.<br> When set to a percentage, the value defines the radius as a percentage of the parent component's width or height.<br>**NOTE**<br>When **cornerRadius** is of type LocalizedBorderRadiuses, the layout order can be dynamically adjusted based on the user's language settings.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
52| transition<sup>12+</sup>          | [TransitionEffect](ts-transition-animation-component.md#transitioneffect10) | No  | Transition effect for the entrance and exit of the dialog box.<br>**NOTE**<br> 1. If this parameter is not set, the default effect is used.<br> 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.<br> 3. Touching the Back button during the exit animation does not affect the animation playback. Touching the Back button again closes the application.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
53| width<sup>12+</sup>               | [Dimension](ts-types.md#dimension10) | No  | Width of the dialog box.<br>**NOTE**<br>- Default maximum width of the dialog box: 400 vp<br>- 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.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
54| height<sup>12+</sup>              | [Dimension](ts-types.md#dimension10)                         | No  | Height of the dialog box.<br>**NOTE**<br>- Default maximum height of the dialog box: 0.9 x (Window height – Safe area)<br>- 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.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
55| borderWidth<sup>12+</sup>         | [Dimension](ts-types.md#dimension10) \| [EdgeWidths](ts-types.md#edgewidths9) \| [LocalizedEdgeWidths](ts-types.md#LocalizedEdgeWidths12) | No  | <br>You can set the width for all four sides or set separate widths for individual sides.<br>Default value: **0**<br> When set to a percentage, the value defines the border width as a percentage of the parent dialog box's width.<br>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.<br>**NOTE**<br>When **borderWidth** is of type LocalizedEdgeWidths, the layout order can be dynamically adjusted based on the user's language settings.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
56| borderColor<sup>12+</sup>         | [ResourceColor](ts-types.md#resourcecolor) \| [EdgeColors](ts-types.md#edgecolors9) \| [LocalizedEdgeColors](ts-types.md#LocalizedEdgeColors12) | No  | Border color of the dialog box.<br>Default value: **Color.Black**<br> **borderColor** must be used with **borderWidth** in pairs. **NOTE**<br>When **borderColor** is of type LocalizedEdgeColors, the layout order can be dynamically adjusted based on the user's language settings.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
57| borderStyle<sup>12+</sup>         | [BorderStyle](ts-appendix-enums.md#borderstyle) \| [EdgeStyles](ts-types.md#edgestyles9) | No  | Border style of the dialog box.<br>Default value: **BorderStyle.Solid**<br>**borderStyle** must be used with **borderWidth** in pairs.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
58| shadow<sup>12+</sup>              | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions) \| [ShadowStyle](ts-universal-attributes-image-effect.md#shadowstyle10) | No  | Shadow of the dialog box.<br> Default value on 2-in-1 devices: **ShadowStyle.OUTER_FLOATING_MD** when the dialog box is focused and **ShadowStyle.OUTER_FLOATING_SM** otherwise<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
59| textStyle<sup>12+</sup>              | [TextStyle](#textstyle12) | No  | Text style of the message in the dialog box.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
60| enableHoverMode<sup>14+</sup>     | boolean | No  | Whether to enable the hover state.<br>Default value: **false**, meaning not to enable the hover state.<br>**Atomic service API**: This API can be used in atomic services since API version 14.|
61| hoverModeArea<sup>14+</sup>       | [HoverModeAreaType](ts-appendix-enums.md#hovermodeareatype14) | No  | Display area of the dialog box in the hover state.<br>Default value: **HoverModeAreaType.BOTTOM_SCREEN**<br>**Atomic service API**: This API can be used in atomic services since API version 14.|
62
63## AlertDialogParamWithConfirm
64
65Inherits [AlertDialogParam](#alertdialogparam).
66
67**Atomic service API**: This API can be used in atomic services since API version 11.
68
69**System capability**: SystemCapability.ArkUI.ArkUI.Full
70
71| Name      | Type    | Mandatory    | Description        |
72| ---------- | ---------------- | ---------- | ------------------------------- |
73| confirm    | {<br>enabled<sup>10+</sup>?: boolean,<br>defaultFocus<sup>10+</sup>?: boolean,<br>style<sup>10+</sup>?: [DialogButtonStyle](ts-appendix-enums.md#dialogbuttonstyle10),<br>value: [ResourceStr](ts-types.md#resourcestr),<br>fontColor?: [ResourceColor](ts-types.md#resourcecolor),<br>backgroundColor?:  [ResourceColor](ts-types.md#resourcecolor),<br>action: () =&gt; void<br>} | No  | Information about the confirm button. When the dialog box has focus and the **Tab** key is not pressed for sequential focus navigation, the button responds to the **Enter** key by default.<br>**enabled**: whether to respond when the button is clicked. The value **true** means to respond when the button is clicked, and **false** means the opposite.<br>Default value: **true**<br>**defaultFocus**: whether the button is the default focus. The value **true** means that the button is the default focus, and **false** means the opposite.<br>Default value: **false**<br>**style**: button style.<br>Default value: **DialogButtonStyle.DEFAULT**<br>**value**: button text.<br>**fontColor**: font color of the button.<br>**backgroundColor**: background color of the button.<br>**action**: callback upon button clicking.|
74
75Priorities of the **confirm** parameters: **fontColor** and **backgroundColor** > **style** > **defaultFocus**
76
77| backgroundColor | fontColor | style                       | defaultFocus | Effect    |
78| --------------- | --------- | --------------------------- | ------------ | -------- |
79| Green           | Red     | -                           | -            | Red text on green background|
80| Green           | -         | DialogButtonStyle.HIGHLIGHT | -            | White text on green background|
81| Green           | -         | DialogButtonStyle.DEFAULT   | -            | Blue text on green background|
82| Green           | -         | -                           | TRUE         | White text on green background|
83| Green           | -         | -                           | FALSE/-      | Blue text on green background|
84| -               | Red     | DialogButtonStyle.HIGHLIGHT | -            | Red text on blue background|
85| -               | Red     | DialogButtonStyle.DEFAULT   | -            | Red text on white background|
86| -               | Red     | -                           | TRUE         | Red text on blue background|
87| -               | Red     | -                           | FALSE/-      | Red text on white background|
88| -               | -         | DialogButtonStyle.HIGHLIGHT | -            | White text on blue background|
89| -               | -         | DialogButtonStyle.DEFAULT   | -            | Blue text on white background|
90| -               | -         | -                           | TRUE         | White text on blue background|
91| -               | -         | -                           | FALSE/-      | Blue text on white background|
92
93## AlertDialogParamWithButtons
94
95Inherits [AlertDialogParam](#alertdialogparam).
96
97**Atomic service API**: This API can be used in atomic services since API version 11.
98
99**System capability**: SystemCapability.ArkUI.ArkUI.Full
100
101| Name            | Type               | Mandatory    | Description                    |
102| --------------- | ---------------------- | ------------ | --------------------- |
103| primaryButton   | {<br>enabled<sup>10+</sup>?: boolean,<br>defaultFocus<sup>10+</sup>?: boolean,<br>style<sup>10+</sup>?: [DialogButtonStyle](ts-appendix-enums.md#dialogbuttonstyle10),<br>value: [ResourceStr](ts-types.md#resourcestr),<br>fontColor?: [ResourceColor](ts-types.md#resourcecolor),<br>backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),<br>action: () =&gt; void;<br>} | No| Information about the confirm button. When the dialog box has focus and the **Tab** key is not pressed for sequential focus navigation, the button responds to the **Enter** key by default.<br>**enabled**: whether to respond when the button is clicked.<br>Default value: **true**<br>**defaultFocus**: whether the button is the default focus.<br>Default value: **false**<br>**style**: button style.<br>Default value: **DialogButtonStyle.DEFAULT**<br>**value**: button text.<br>**fontColor**: font color of the button.<br>**backgroundColor**: background color of the button.<br>**action**: callback upon button clicking.|
104| secondaryButton | {<br>enabled<sup>10+</sup>?: boolean,<br>defaultFocus<sup>10+</sup>?: boolean,<br>style<sup>10+</sup>?: [DialogButtonStyle](ts-appendix-enums.md#dialogbuttonstyle10),<br>value: [ResourceStr](ts-types.md#resourcestr),<br>fontColor?: [ResourceColor](ts-types.md#resourcecolor),<br>backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),<br>action: () =&gt; void;<br>} | No | Information about the confirm button.<br>**enabled**: whether to respond when the button is clicked.<br>Default value: **true**<br>**defaultFocus**: whether the button is the default focus.<br>Default value: **false**<br>**style**: button style.<br>Default value: **DialogButtonStyle.DEFAULT**<br>**value**: button text.<br>**fontColor**: font color of the button.<br>**backgroundColor**: background color of the button.<br>**action**: callback upon button clicking.|
105
106## AlertDialogParamWithOptions<sup>10+</sup>
107
108Inherits [AlertDialogParam](#alertdialogparam).
109
110**Atomic service API**: This API can be used in atomic services since API version 11.
111
112**System capability**: SystemCapability.ArkUI.ArkUI.Full
113
114| Name            | Type               | Mandatory    | Description                   |
115| --------------- | ---------------------- | ------------ | --------------------- |
116| buttons       | Array&lt;[AlertDialogButtonOptions](#alertdialogbuttonoptions10)&gt;                 | Yes | Buttons in the dialog box.|
117|buttonDirection      | [DialogButtonDirection](#dialogbuttondirection10)| No | Direction in which buttons are laid out.<br>Default value: **DialogButtonDirection.AUTO**<br>When there are more than three buttons, the Auto mode (which automatically switches to the vertical layout when there are more than two buttons) is recommended. In non-Auto mode, buttons that extend beyond the display area are clipped.|
118
119## AlertDialogButtonOptions<sup>10+</sup>
120
121**System capability**: SystemCapability.ArkUI.ArkUI.Full
122
123| Name                 | Type   | Mandatory| Description                                                        |
124| --------------------- | ------- | ---- | ------------------------------------------------------------ |
125| enabled           | boolean | No    | Whether to respond when the button is clicked.<br>Default value: **true**<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
126| defaultFocus           | boolean | No    | Whether the button is the default focus.<br>Default value: **false**<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
127| style           | [DialogButtonStyle](ts-appendix-enums.md#dialogbuttonstyle10) | No    | Style of the button.<br>Default value: **DialogButtonStyle.DEFAULT**<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
128| value           | [ResourceStr](ts-types.md#resourcestr) | Yes    | Text of the button. If the value is null, the button is not displayed.<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
129| fontColor           | [ResourceColor](ts-types.md#resourcecolor) | No    | Font color of the button.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
130| backgroundColor           | [ResourceColor](ts-types.md#resourcecolor) | No    | Background color of the button.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
131| action           | () => void | Yes    | Callback upon button clicking.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
132| primary<sup>12+</sup> | 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. This parameter does not take effect when **defaultFocus** is set to **true**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
133
134## DialogButtonDirection<sup>10+</sup>
135
136**Atomic service API**: This API can be used in atomic services since API version 11.
137
138**System capability**: SystemCapability.ArkUI.ArkUI.Full
139
140| Name                      | Description   |
141| -------------------------- | --------- |
142| AUTO                      | Buttons are laid out horizontally when there are two or fewer buttons and vertically otherwise.|
143| HORIZONTAL                      | Buttons are laid out horizontally.|
144| VERTICAL                      | Buttons are laid out vertically.|
145
146## DialogAlignment
147
148**Atomic service API**: This API can be used in atomic services since API version 11.
149
150**System capability**: SystemCapability.ArkUI.ArkUI.Full
151
152| Name                    | Description          |
153| ------------------------ | -------------- |
154| Top                      | Vertical top alignment.|
155| Center                   | Vertical center alignment.|
156| Bottom                   | Vertical bottom alignment.|
157| Default                  | Default alignment.    |
158| TopStart<sup>8+</sup>    | Top left alignment.    |
159| TopEnd<sup>8+</sup>      | Top right alignment.    |
160| CenterStart<sup>8+</sup> | Center left alignment.    |
161| CenterEnd<sup>8+</sup>   | Center right alignment.    |
162| BottomStart<sup>8+</sup> | Bottom left alignment.    |
163| BottomEnd<sup>8+</sup>   | Bottom right alignment.    |
164
165## Rectangle<sup>8+</sup>
166
167The **Rectangle** type is used to represent a mask area of a dialog box.
168
169**Widget capability**: This API can be used in ArkTS widgets since API version 9.
170
171**Atomic service API**: This API can be used in atomic services since API version 11.
172
173**System capability**: SystemCapability.ArkUI.ArkUI.Full
174
175| Name    | Type                          | Mandatory| Description                              |
176|--------|------------------------------|----|-----------------------------------|
177| x      | [Length](ts-types.md#length) | No | X coordinate of the mask area of the dialog box relative to the upper left corner of the window.<br>Default value: **0vp**|
178| y      | [Length](ts-types.md#length) | No | Y coordinate of the mask area of the dialog box relative to the upper left corner of the window.<br>Default value: **0vp**|
179| width  | [Length](ts-types.md#length) | No | Width of the mask area of the dialog box.<br>Default value: **'100%'**       |
180| height | [Length](ts-types.md#length) | No | Height of the mask area of the dialog box.<br>Default value: **'100%'**       |
181
182>  **NOTE**
183>
184>  **x** and **y** can be set to a positive or negative percentage value. When **x** is set to **'100%'**, the mask area is moved rightward by the window width. When **x** is set to **'-100%'**, the mask area is moved leftward by the window width. When **y** is set to **'100%'**, the mask area is moved downward by the window height. When **y** is set to **'-100%'**, the mask area is moved upward by the window height.
185>
186>  **width** and **height** can be set in percentage and can only be set to positive values. If they are set to negative values, the default values are used instead.
187>
188>  The percentage is calculated based on the width and height of the window.
189
190## DismissDialogAction<sup>12+</sup>
191
192Provides information about the action to dismiss the dialog box.
193
194**Atomic service API**: This API can be used in atomic services since API version 12.
195
196**System capability**: SystemCapability.ArkUI.ArkUI.Full
197
198### Properties
199
200| Name   | Type                                                        | Readable| Writable| Description                                                        |
201| ------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
202| dismiss | Callback&lt;void&gt;                                         | No  | No  | Callback for closing the dialog box. This API is called only when the dialog box needs to be exited.|
203| reason  | [DismissReason](../js-apis-promptAction.md#dismissreason12) | No  | No  | Reason why the dialog box cannot be closed. You must specify whether to close the dialog box for each of the listed actions.|
204
205## TextStyle<sup>12+</sup>
206
207**Atomic service API**: This API can be used in atomic services since API version 12.
208
209**System capability**: SystemCapability.ArkUI.ArkUI.Full
210
211| Name    | Type                          | Mandatory| Description                               |
212|--------|------------------------------|----|-----------------------------------|
213| wordBreak      | [WordBreak](ts-appendix-enums.md#wordbreak11) | No | Word break rule.<br>Default value: **WordBreak.BREAK_ALL**|
214
215## Example
216
217### Example 1: Displaying Dialog Boxes with Different Numbers of Buttons
218
219> **NOTE**
220>
221> To avoid confusion with **AlertDialog** instances, it is recommended that you obtain a **UIContext** instance using the [getUIContext](../js-apis-arkui-UIContext.md#uicontext) API, and then use the [showAlertDialog](../js-apis-arkui-UIContext.md#showalertdialog) API to invoke the instance's **AlertDialog.show()** method.
222
223This example demonstrates how to display dialog boxes with one, two, and three buttons.
224
225```ts
226// xxx.ets
227@Entry
228@Component
229struct AlertDialogExample {
230  build() {
231    Column({ space: 5 }) {
232      Button('one button dialog')
233        .onClick(() => {
234          // You are advised to use this.getUIContext().showAlertDialog().
235          AlertDialog.show(
236            {
237              title: 'title',
238              message: 'text',
239              autoCancel: true,
240              alignment: DialogAlignment.Bottom,
241              offset: { dx: 0, dy: -20 },
242              gridCount: 3,
243              confirm: {
244                value: 'button',
245                action: () => {
246                  console.info('Button-clicking callback')
247                }
248              },
249              cancel: () => {
250                console.info('Closed callbacks')
251              },
252              onWillDismiss:(dismissDialogAction: DismissDialogAction)=> {
253                console.info("reason=" + JSON.stringify(dismissDialogAction.reason))
254                console.log("dialog onWillDismiss")
255                if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
256                  dismissDialogAction.dismiss()
257                }
258                if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
259                  dismissDialogAction.dismiss()
260                }
261              }
262            }
263          )
264        })
265        .backgroundColor(0x317aff)
266      Button('two button dialog')
267        .onClick(() => {
268          // You are advised to use this.getUIContext().showAlertDialog().
269          AlertDialog.show(
270            {
271              title: 'title',
272              subtitle: 'subtitle',
273              message: 'text',
274              autoCancel: true,
275              alignment: DialogAlignment.Bottom,
276              gridCount: 4,
277              offset: { dx: 0, dy: -20 },
278              primaryButton: {
279                value: 'cancel',
280                action: () => {
281                  console.info('Callback when the first button is clicked')
282                }
283              },
284              secondaryButton: {
285                enabled: true,
286                defaultFocus: true,
287                style: DialogButtonStyle.HIGHLIGHT,
288                value: 'ok',
289                action: () => {
290                  console.info('Callback when the second button is clicked')
291                }
292              },
293              cancel: () => {
294                console.info('Closed callbacks')
295              },
296              onWillDismiss:(dismissDialogAction: DismissDialogAction)=> {
297                console.info("reason=" + JSON.stringify(dismissDialogAction.reason))
298                console.log("dialog onWillDismiss")
299                if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
300                  dismissDialogAction.dismiss()
301                }
302                if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
303                  dismissDialogAction.dismiss()
304                }
305              }
306            }
307          )
308        }).backgroundColor(0x317aff)
309        Button('three button dialog')
310        .onClick(() => {
311          // You are advised to use this.getUIContext().showAlertDialog().
312          AlertDialog.show(
313            {
314              title: 'title',
315              subtitle: 'subtitle',
316              message: 'text',
317              autoCancel: true,
318              alignment: DialogAlignment.Bottom,
319              gridCount: 4,
320              offset: { dx: 0, dy: -20 },
321              buttonDirection: DialogButtonDirection.HORIZONTAL,
322              buttons: [
323                {
324                  value: 'Button',
325                  action: () => {
326                    console.info('Callback when button1 is clicked')
327                  }
328                },
329                {
330                  value: 'Button',
331                  action: () => {
332                    console.info('Callback when button2 is clicked')
333                  }
334                },
335                {
336                  value: 'Button',
337                  enabled: true,
338                  defaultFocus: true,
339                  style: DialogButtonStyle.HIGHLIGHT,
340                  action: () => {
341                    console.info('Callback when button3 is clicked')
342                  }
343                },
344              ],
345              cancel: () => {
346                console.info('Closed callbacks')
347              },
348              onWillDismiss:(dismissDialogAction: DismissDialogAction)=> {
349                console.info("reason=" + JSON.stringify(dismissDialogAction.reason))
350                console.log("dialog onWillDismiss")
351                if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
352                  dismissDialogAction.dismiss()
353                }
354                if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
355                  dismissDialogAction.dismiss()
356                }
357              }
358            }
359          )
360        }).backgroundColor(0x317aff)
361    }.width('100%').margin({ top: 5 })
362  }
363}
364```
365
366![en-us_image_alert](figures/en-us_image_alert.gif)
367
368### Example 2: Opening a Dialog Box Outside the Main Window
369
370This example demonstrates how to configure a dialog box to display outside the main window by setting **showInSubWindow** to **true**.
371
372> **NOTE**
373>
374> To avoid confusion with **AlertDialog** instances, it is recommended that you obtain a **UIContext** instance using the [getUIContext](../js-apis-arkui-UIContext.md#uicontext) API, and then use the [showAlertDialog](../js-apis-arkui-UIContext.md#showalertdialog) API to invoke the instance's **AlertDialog.show()** method.
375
376```ts
377// xxx.ets
378@Entry
379@Component
380struct AlertDialogExample {
381  build() {
382    Column({ space: 5 }) {
383      Button('one button dialog')
384        .onClick(() => {
385          // You are advised to use this.getUIContext().showAlertDialog().
386          AlertDialog.show(
387            {
388              title: 'title',
389              subtitle: 'subtitle',
390              message: 'text',
391              autoCancel: true,
392              alignment: DialogAlignment.Center,
393              gridCount: 4,
394              showInSubWindow: true,
395              isModal: true,
396              offset: { dx: 0, dy: -20 },
397              buttonDirection: DialogButtonDirection.HORIZONTAL,
398              buttons: [
399                {
400                  value: 'Button',
401                  action: () => {
402                    console.info('Callback when button1 is clicked')
403                  }
404                },
405                {
406                  value: 'Button',
407                  action: () => {
408                    console.info('Callback when button2 is clicked')
409                  }
410                },
411                {
412                  value: 'Button',
413                  enabled: true,
414                  defaultFocus: true,
415                  style: DialogButtonStyle.HIGHLIGHT,
416                  action: () => {
417                    console.info('Callback when button3 is clicked')
418                  }
419                },
420              ],
421              cancel: () => {
422                console.info('Closed callbacks')
423              },
424              onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
425                console.info("reason=" + JSON.stringify(dismissDialogAction.reason))
426                console.log("dialog onWillDismiss")
427                if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
428                  dismissDialogAction.dismiss()
429                }
430                if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
431                  dismissDialogAction.dismiss()
432                }
433              }
434            })
435        })
436    }.width('100%').margin({ top: 5 }).backgroundColor(0x317aff)
437  }
438}
439```
440
441![en-us_image_alert_showinsubwindow](figures/en-us_image_alert_showinsubwindow.jpg)
442
443### Example 3: Setting the Dialog Box Animation
444This example illustrates how to use the **transition** API to create custom animation effects for the dialog box's appearance and disappearance.
445
446> **NOTE**
447>
448> To avoid confusion with **AlertDialog** instances, it is recommended that you obtain a **UIContext** instance using the [getUIContext](../js-apis-arkui-UIContext.md#uicontext) API, and then use the [showAlertDialog](../js-apis-arkui-UIContext.md#showalertdialog) API to invoke the instance's **AlertDialog.show()** method.
449
450```ts
451// xxx.ets
452@Entry
453@Component
454struct AlertDialogExample {
455  build() {
456    Column({ space: 5 }) {
457      Button('AlertDialog Set Duration')
458        .onClick(()=>{
459            // You are advised to use this.getUIContext().showAlertDialog().
460            AlertDialog.show(
461              {
462                title: 'AlertDialog 1',
463                message: 'Set Animation Duration open 3 second, close 100ms',
464                autoCancel: true,
465                alignment: DialogAlignment.Top,
466                offset: { dx: 0, dy: -20 },
467                gridCount: 3,
468                transition:TransitionEffect.asymmetric(TransitionEffect.OPACITY
469                  .animation({ duration: 3000, curve: Curve.Sharp }).combine(TransitionEffect.scale({x: 1.5, y: 1.5}).animation({duration: 3000, curve: Curve.Sharp})),
470                  TransitionEffect.OPACITY.animation({ duration: 100, curve: Curve.Smooth })
471                    .combine(TransitionEffect.scale({x: 0.5, y: 0.5}).animation({duration: 100, curve: Curve.Smooth}))),
472                confirm: {
473                  value: 'button',
474                  action: () => {
475                    console.info('Button-clicking callback')
476                  }
477                },
478                cancel: () => {
479                  console.info('Closed callbacks')
480                }
481              }
482            )
483        })
484        .backgroundColor(0x317aff).height("88px")
485    }.width('100%').margin({ top: 5 })
486  }
487}
488```
489
490![en-us_image_alert_animation](figures/en-us_image_alert_animation.gif)
491
492### Example 4: Setting the Dialog Box Style
493This example demonstrates how to set styles of an alert dialog box, including the width, height, background color, and shadow.
494
495> **NOTE**
496>
497> To avoid confusion with **AlertDialog** instances, it is recommended that you obtain a **UIContext** instance using the [getUIContext](../js-apis-arkui-UIContext.md#uicontext) API, and then use the [showAlertDialog](../js-apis-arkui-UIContext.md#showalertdialog) API to invoke the instance's **AlertDialog.show()** method.
498
499```ts
500// xxx.ets
501@Entry
502@Component
503struct AlertDialogExample {
504  build() {
505    Column({ space: 5 }) {
506      Button('one button dialog')
507        .onClick(() => {
508          // You are advised to use this.getUIContext().showAlertDialog().
509          AlertDialog.show(
510            {
511              title: 'title',
512              message: 'text',
513              autoCancel: true,
514              alignment: DialogAlignment.Center,
515              offset: { dx: 0, dy: -20 },
516              gridCount: 3,
517              width: 300,
518              height: 200,
519              cornerRadius: 20,
520              borderWidth: 1,
521              borderStyle: BorderStyle.Dashed,// borderStyle must be used with borderWidth in pairs.
522              borderColor: Color.Blue,// borderColor must be used with borderWidth in pairs.
523              backgroundColor: Color.White,
524              shadow: ({ radius: 20, color: Color.Grey, offsetX: 50, offsetY: 0}),
525              textStyle: { wordBreak: WordBreak.BREAK_ALL },
526              confirm: {
527                value: 'button',
528                action: () => {
529                  console.info('Button-clicking callback')
530                }
531              },
532              cancel: () => {
533                console.info('Closed callbacks')
534              },
535              onWillDismiss:(dismissDialogAction: DismissDialogAction)=> {
536                console.info("reason=" + JSON.stringify(dismissDialogAction.reason))
537                console.log("dialog onWillDismiss")
538                if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
539                  dismissDialogAction.dismiss()
540                }
541                if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
542                  dismissDialogAction.dismiss()
543                }
544              }
545            }
546          )
547        })
548        .backgroundColor(0x317aff)
549    }.width('100%').margin({ top: 5 })
550  }
551}
552```
553
554![en-us_image_alert_style](figures/en-us_image_alert_style.gif)
555
556### Example 5: Configuring a Dialog Box in the Hover State
557
558This example demonstrates how to set the layout area of a dialog box in hover mode on a foldable device.
559
560```ts
561@Entry
562@Component
563struct AlertDialogExample {
564  build() {
565    Column({ space: 5 }) {
566      Button('one button dialog')
567        .onClick(() => {
568          AlertDialog.show(
569            {
570              title: 'title',
571              message: 'text',
572              autoCancel: true,
573              alignment: DialogAlignment.Bottom,
574              gridCount: 3,
575              confirm: {
576                value: 'button',
577                action: () => {
578                  console.info('Button-clicking callback')
579                }
580              },
581              cancel: () => {
582                console.info('Closed callbacks')
583              },
584              onWillDismiss:(dismissDialogAction: DismissDialogAction)=> {
585                console.info("reason=" + JSON.stringify(dismissDialogAction.reason));
586                console.log("dialog onWillDismiss");
587                if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {
588                  dismissDialogAction.dismiss();
589                }
590                if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {
591                  dismissDialogAction.dismiss();
592                }
593              },
594              enableHoverMode: true,
595              hoverModeArea: HoverModeAreaType.TOP_SCREEN
596            }
597          )
598        })
599        .backgroundColor(0x317aff)
600    }.width('100%').margin({ top: 5 })
601  }
602}
603```
604
605![en-us_image_alert](figures/en-us_image_alert_hovermode.gif)
606