• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Fixed-Style Dialog Box
2
3The fixed-style dialog box uses a predefined layout format, allowing you to focus on providing the required text content without worrying about specific display layout details. This simplifies usage and improves convenience.
4
5## Constraints
6
7- You can use the APIs in this document in non-UI pages or certain asynchronous callbacks by calling **UIContext** or **getUIContext**. This operation is not supported by **CalendarPickerDialog**.
8
9- For **showActionMenu** and **showDialog** APIs, you must first call [getPromptAction()](../reference/apis-arkui/js-apis-arkui-UIContext.md#getpromptaction) in **UIContext** to obtain the **PromptAction** object, and then use the object to call the corresponding API.
10
11- For **ActionSheet**, **AlertDialog**, and **PickerDialog** APIs, except **CalendarPickerDialog**, you must first call [getUIContext()](../reference/apis-arkui/arkts-apis-window-Window.md#getuicontext10) in **ohos.window** to obtain the **UIContext** instance, and then use the instance to call the corresponding API. Alternatively, you can obtain a **UIContext** instance through the built-in method [getUIContext()](../reference/apis-arkui/arkui-ts/ts-custom-component-api.md#getuicontext) of the custom component.
12
13The dialog boxes created using **showActionMenu**, **showDialog**, **ActionSheet**, or **AlertDialog** can be changed to a non-modal dialog box by setting its **isModal** attribute to **false**.
14
15The dialog boxes created using **showActionMenu**, **showDialog**, **ActionSheet**, or **AlertDialog** do not support setting the font style of the content area, such as font color, size and line breaks. For custom styles, you are advised to use [global custom dialog boxes independent of UI components](arkts-uicontext-custom-dialog.md) or [basic custom dialog boxes](./arkts-common-components-custom-dialog.md).
16
17## Lifecycle
18
19The dialog box provides lifecycle functions to notify users of its lifecycle events. The order in which these lifecycle events are triggered is as follows: **onWillAppear** -> **onDidAppear** -> **onWillDisappear** -> **onDidDisappear**. You can also refer to the API documentation for each component.
20
21Since API version 19, the dialog boxes created using **showDialog**, **ActionSheet**, or **AlertDialog** support the following lifecycle events.
22
23| Name           |Type| Description                      |
24| ----------------- | ------ | ---------------------------- |
25| onWillAppear    | Callback<void> | Triggered before the dialog box display animation.|
26| onDidAppear    | Callback<void>  | Triggered after the dialog box appears.   |
27| onWillDisappear | Callback<void> | Triggered before the dialog box exit animation.|
28| onDidDisappear | Callback<void>  | Triggered after the dialog box disappears.   |
29
30## Action Menu (showActionMenu)
31
32The action menu is implemented by obtaining the **PromptAction** object from the [showActionMenu](../reference/apis-arkui/js-apis-arkui-UIContext.md#showactionmenu11) method in **UIContext** and then calling the [showActionMenu](../reference/apis-arkui/js-apis-arkui-UIContext.md#showactionmenu11) API through this object. It can be used in callbacks or in classes you define.
33
34After an action menu is created and displayed, the index of the selected button in the **buttons** array will be returned asynchronously as the response result.
35
36```ts
37import { PromptAction } from '@kit.ArkUI';
38
39let uiContext = this.getUIContext();
40let promptAction: PromptAction = uiContext.getPromptAction();
41try {
42  promptAction.showActionMenu({
43    title: 'showActionMenu Title Info',
44    buttons: [
45      {
46        text: 'item1',
47        color: '#666666'
48      },
49      {
50        text: 'item2',
51        color: '#000000'
52      },
53    ]
54  })
55    .then(data => {
56      console.info('showActionMenu success, click button: ' + data.index);
57    })
58    .catch((err: Error) => {
59      console.error('showActionMenu error: ' + err);
60    })
61} catch (error) {
62}
63```
64
65![image](figures/UIContextShowMenu.gif)
66
67## Common Dialog Box (showDialog)
68
69The common dialog box is implemented by obtaining the **PromptAction** object from the **getPromptAction** method in **UIContext** and then calling the [showDialog](../reference/apis-arkui/js-apis-arkui-UIContext.md#showdialog) API through this object. It can be used in callbacks or in classes you define.
70
71After a common dialog box is created and displayed, the index of the selected button in the **buttons** array will be returned asynchronously as the response result.
72
73```ts
74// xxx.ets
75import { PromptAction } from '@kit.ArkUI';
76
77let uiContext = this.getUIContext();
78let promptAction: PromptAction = uiContext.getPromptAction();
79try {
80  promptAction.showDialog({
81    title: 'showDialog Title Info',
82    message: 'Message Info',
83    buttons: [
84      {
85        text: 'button1',
86        color: '#000000'
87      },
88      {
89        text: 'button2',
90        color: '#000000'
91      }
92    ]
93  }, (err, data) => {
94    if (err) {
95      console.error('showDialog err: ' + err);
96      return;
97    }
98    console.info('showDialog success callback, click button: ' + data.index);
99  });
100} catch (error) {
101}
102```
103
104![image](figures/UIShowDialog.gif)
105
106## Picker Dialog Box (PickerDialog)
107
108The picker dialog box is typically used to display specific information or options when a user performs certain actions, such as touching a button.
109
110### Calendar Picker Dialog Box (CalendarPickerDialog)
111
112The calendar picker dialog box provides a calendar view that includes year, month, and weekday information, implemented through the [CalendarPickerDialog](../reference/apis-arkui/arkui-ts/ts-methods-calendarpicker-dialog.md) API. You can call the **show** API to define and display the calendar picker dialog box.
113
114The display of the calendar picker dialog box depends on the UI execution context and cannot be used in places where the [UI context is ambiguous](./arkts-global-interface.md). For specific constraints, see the [UIContext](../reference/apis-arkui/js-apis-arkui-UIContext.md#uicontext) documentation.
115
116You can also define custom button styles by configuring **acceptButtonStyle** and **cancelButtonStyle**.
117
118```ts
119// xxx.ets
120@Entry
121@Component
122struct CalendarPickerDialogExample {
123  private selectedDate: Date = new Date('2024-04-23');
124
125  build() {
126    Column() {
127      Button("Show CalendarPicker Dialog")
128        .margin(20)
129        .onClick(() => {
130          console.info("CalendarDialog.show")
131          CalendarPickerDialog.show({
132            selected: this.selectedDate,
133            acceptButtonStyle: {
134              fontColor: '#2787d9',
135              fontSize: '16fp',
136              backgroundColor: '#f7f7f7',
137              borderRadius: 10
138            },
139            cancelButtonStyle: {
140              fontColor: Color.Red,
141              fontSize: '16fp',
142              backgroundColor: '#f7f7f7',
143              borderRadius: 10
144            },
145            onAccept: (date: Date)=>{
146              // Display the last selected date when the dialog box is shown again.
147              this.selectedDate = date;
148            }
149          })
150        })
151    }.width('100%')
152  }
153}
154```
155
156![image](figures/UIContextShowCalendarpickerDialog.gif)
157
158### Date Picker Dialog Box (DatePickerDialog)
159
160The date picker dialog box allows users to select a date from the given range, presenting the date information clearly.
161
162You use the [showDatePickerDialog](../reference/apis-arkui/js-apis-arkui-UIContext.md#showdatepickerdialog) API in **UIContext** to implement a date picker dialog box.
163
164When **lunarSwitch** and **showTime** are set to **true** for the dialog box, it displays a switch for toggling the lunar calendar and time. When the check box is selected, the lunar calendar is shown. When the confirm button is touched, the dialog box returns the currently selected date through **onDateAccept**. To display the last confirmed date when the dialog box is shown again, reassign the value to **selectTime** in the callback.
165
166```ts
167@Entry
168@Component
169struct DatePickerDialogExample {
170  @State selectTime: Date = new Date('2023-12-25T08:30:00');
171
172  build() {
173    Column() {
174      Button('showDatePickerDialog')
175        .margin(30)
176        .onClick(() => {
177          this.getUIContext().showDatePickerDialog({
178            start: new Date("2000-1-1"),
179            end: new Date("2100-12-31"),
180            selected: this.selectTime,
181            lunarSwitch: true,
182            showTime: true,
183            onDateAccept: (value: Date) => {
184              this.selectTime = value;
185              console.info("DatePickerDialog:onAccept()" + JSON.stringify(value));
186            },
187          });
188        })
189    }.width('100%').margin({ top: 5 })
190  }
191}
192
193```
194
195![image](figures/UIContextShowdatepickerDialog.gif)
196
197In this example, **disappearTextStyle**, **textStyle**, **selectedTextStyle**, **acceptButtonStyle**, and **cancelButtonStyle** are configured to customize the text and button style.
198
199```ts
200@Entry
201@Component
202struct DatePickerDialogExample {
203  @State selectTime: Date = new Date('2023-12-25T08:30:00');
204
205  build() {
206    Column() {
207      Button('showDatePickerDialog')
208        .margin(30)
209        .onClick(() => {
210          this.getUIContext().showDatePickerDialog({
211            start: new Date("2000-1-1"),
212            end: new Date("2100-12-31"),
213            selected: this.selectTime,
214            textStyle: { color: '#2787d9', font: { size: '14fp', weight: FontWeight.Normal } },
215            selectedTextStyle: { color: '#004aaf', font: { size: '18fp', weight: FontWeight.Regular } },
216            acceptButtonStyle: {
217              fontColor: '#2787d9',
218              fontSize: '16fp',
219              backgroundColor: '#f7f7f7',
220              borderRadius: 10
221            },
222            cancelButtonStyle: {
223              fontColor: Color.Red,
224              fontSize: '16fp',
225              backgroundColor: '#f7f7f7',
226              borderRadius: 10
227            }
228          })
229        })
230    }.width('100%').margin({ top: 5 })
231  }
232}
233```
234
235![image](figures/UIShowDatePickerDialog.gif)
236
237### Time Picker Dialog Box (TimePickerDialog)
238
239The time picker dialog box allows users to select a time from the 24-hour range, presenting the time information clearly.
240
241You use the [showTimePickerDialog](../reference/apis-arkui/js-apis-arkui-UIContext.md#showtimepickerdialog) API in **UIContext** to implement a time picker dialog box.
242
243In this example, **disappearTextStyle**, **textStyle**, **selectedTextStyle**, **acceptButtonStyle**, and **cancelButtonStyle** are configured to customize the text and button style.
244
245```ts
246// xxx.ets
247
248@Entry
249@Component
250struct TimePickerDialogExample {
251  @State selectTime: Date = new Date('2023-12-25T08:30:00');
252
253  build() {
254    Column() {
255      Button('showTimePickerDialog')
256        .margin(30)
257        .onClick(() => {
258          this.getUIContext().showTimePickerDialog({
259            selected: this.selectTime,
260            textStyle: { color: '#2787d9', font: { size: '14fp', weight: FontWeight.Normal } },
261            selectedTextStyle: { color: '#004aaf', font: { size: '18fp', weight: FontWeight.Regular } },
262            acceptButtonStyle: {
263              fontColor: '#2787d9',
264              fontSize: '16fp',
265              backgroundColor: '#f7f7f7',
266              borderRadius: 10
267            },
268            cancelButtonStyle: {
269              fontColor: Color.Red,
270              fontSize: '16fp',
271              backgroundColor: '#f7f7f7',
272              borderRadius: 10
273            }
274          });
275        })
276    }.width('100%').margin({ top: 5 })
277  }
278}
279
280```
281
282![image](figures/UIContextShowTimepickerDialog.gif)
283
284### Text Picker Dialog Box (TextPickerDialog)
285
286The text picker dialog box allows users to select text from the given range, presenting the text information clearly.
287
288You use the [showTextPickerDialog](../reference/apis-arkui/js-apis-arkui-UIContext.md#showtextpickerdialog) API in **UIContext** to implement a date picker dialog box.
289
290This example demonstrates how to implement a three-column text picker dialog box by setting the **range** parameter type to **TextCascadePickerRangeContent[]**. When the confirm button is touched, the dialog box returns the currently selected text and index value through the **onAccept** callback. To display the last confirmed text when the dialog box is shown again, reassign the value to **select** in the callback.
291
292```ts
293@Entry
294@Component
295struct TextPickerDialogExample {
296  private fruits: TextCascadePickerRangeContent[] = [
297    {
298      text: 'Liaoning Province',
299      children: [{ text: 'Shenyang', children: [{ text: 'Shenhe District' }, { text: 'Heping District' }, { text: 'Hunnan District' }] },
300        { text: 'Dalian', children: [{ text: 'Zhongshan District' }, { text: 'Jinzhou District' }, { text: 'Changhai County' }] }]
301    },
302    {
303      text: 'Jilin Province',
304      children: [{ text: 'Changchun', children: [{ text: 'Nanguan District' }, { text: 'Kuancheng District' }, { text: 'Chaoyang District' }] },
305        { text: 'Siping', children: [{ text: 'Tiexi District' }, { text: 'Tiedong District' }, { text: 'Lishu County' }] }]
306    },
307    {
308      text: 'Heilongjiang Province',
309      children: [{ text: 'Harbin', children: [{ text: 'Daoli District' }, { text: 'Daowai District' }, { text: 'Nangang District' }] },
310        { text: 'Mudanjiang', children: [{ text: `Dong'an District` }, { text: `Xi'an District` }, { text: 'Aimin District' }] }]
311    }
312  ];
313  private select : number  = 0;
314  build() {
315    Column() {
316      Button('showTextPickerDialog')
317        .margin(30)
318        .onClick(() => {
319          this.getUIContext().showTextPickerDialog({
320            range: this.fruits,
321            selected: this.select,
322            onAccept: (value: TextPickerResult) => {
323              this.select = value.index as number
324            }
325          });
326        })
327    }.width('100%').margin({ top: 5 })
328  }
329}
330```
331
332![image](figures/UIShowTextPickerDialog.gif)
333
334## Action Sheet (ActionSheet)
335
336The action sheet is ideal for presenting multiple action options, especially when the UI only needs to display a list of actions without additional content.
337
338You use the [showActionSheet](../reference/apis-arkui/js-apis-arkui-UIContext.md#showactionsheet) API in UIContext to implement an action sheet.
339
340This example shows how to configure the style and animation effects of the action sheet by setting APIs like **width**, **height**, and **transition**.
341
342```ts
343@Entry
344@Component
345struct showActionSheetExample {
346  build() {
347    Column() {
348      Button('showActionSheet')
349        .margin(30)
350        .onClick(() => {
351          this.getUIContext().showActionSheet({
352            title: 'ActionSheet title',
353            message: 'Message',
354            autoCancel: false,
355            width: 300,
356            height: 300,
357            cornerRadius: 20,
358            borderWidth: 1,
359            borderStyle: BorderStyle.Solid,
360            borderColor: Color.Blue,
361            backgroundColor: Color.White,
362            transition: TransitionEffect.asymmetric(TransitionEffect.OPACITY
363              .animation({ duration: 3000, curve: Curve.Sharp })
364              .combine(TransitionEffect.scale({ x: 1.5, y: 1.5 }).animation({ duration: 3000, curve: Curve.Sharp })),
365              TransitionEffect.OPACITY.animation({ duration: 100, curve: Curve.Smooth })
366                .combine(TransitionEffect.scale({ x: 0.5, y: 0.5 }).animation({ duration: 100, curve: Curve.Smooth }))),
367            confirm: {
368              value: 'OK',
369              action: () => {
370                console.info('Get Alert Dialog handled');
371              }
372            },
373            alignment: DialogAlignment.Center,
374            sheets: [
375              {
376                title: 'Apples',
377                action: () => {
378                }
379              },
380              {
381                title: 'Bananas',
382                action: () => {
383                }
384              },
385              {
386                title: 'Pears',
387                action: () => {
388                  console.info('Pears');
389                }
390              }
391            ]
392          });
393        })
394    }.width('100%').margin({ top: 5 })
395  }
396}
397```
398
399![image](figures/UIContextShowactionSheet.gif)
400
401## Alert Dialog Box (AlertDialog)
402
403The alert dialog box is used when you need to ask a question or get permission from the user.
404
405* The alert dialog box interrupts the current task. Therefore, only use it to provide necessary information and useful operations.
406* Avoid using alert dialog boxes to provide information only; users do not like to be interrupted by information-rich but non-operable alerts.
407
408You use the [showAlertDialog](../reference/apis-arkui/js-apis-arkui-UIContext.md#showalertdialog) API in UIContext to implement an alert dialog box.
409
410This example shows how to configure the style and animation effects of an alert dialog with multiple buttons by setting APIs like **width**, **height**, and **transition**.
411
412```ts
413@Entry
414@Component
415struct showAlertDialogExample {
416  build() {
417    Column() {
418      Button('showAlertDialog')
419        .margin(30)
420        .onClick(() => {
421          this.getUIContext().showAlertDialog(
422            {
423              title: 'Title',
424              message: 'Text',
425              autoCancel: true,
426              alignment: DialogAlignment.Center,
427              offset: { dx: 0, dy: -20 },
428              gridCount: 3,
429              transition: TransitionEffect.asymmetric(TransitionEffect.OPACITY
430                .animation({ duration: 3000, curve: Curve.Sharp })
431                .combine(TransitionEffect.scale({ x: 1.5, y: 1.5 }).animation({ duration: 3000, curve: Curve.Sharp })),
432                TransitionEffect.OPACITY.animation({ duration: 100, curve: Curve.Smooth })
433                  .combine(TransitionEffect.scale({ x: 0.5, y: 0.5 })
434                    .animation({ duration: 100, curve: Curve.Smooth }))),
435              buttons: [{
436                value: 'Cancel',
437                action: () => {
438                  console.info('Callback when the first button is clicked');
439                }
440              },
441                {
442                  enabled: true,
443                  defaultFocus: true,
444                  style: DialogButtonStyle.HIGHLIGHT,
445                  value: 'OK',
446                  action: () => {
447                    console.info('Callback when the second button is clicked');
448                  }
449                }],
450            }
451          );
452        })
453    }.width('100%').margin({ top: 5 })
454  }
455}
456```
457
458![image](figures/UIContextShowAlertDialog.gif)
459