• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 固定样式弹出框
2<!--Kit: ArkUI-->
3<!--Subsystem: ArkUI-->
4<!--Owner: @houguobiao-->
5<!--Designer: @houguobiao-->
6<!--Tester: @lxl007-->
7<!--Adviser: @HelloCrease-->
8
9固定样式弹出框采用固定的布局格式,这使得开发者无需关心具体的显示布局细节,只需输入所需显示的文本内容,从而简化了使用流程,提升了便捷性。
10
11## 使用约束
12
13- 可以通过调用UIContext或getUIContext,在非UI页面或某些异步回调中使用本文中的接口。CalendarPickerDialog当前不支持此操作。
14
15- 操作菜单 (showActionMenu)、对话框 (showDialog)需先使用UIContext中的[getPromptAction()](../reference/apis-arkui/arkts-apis-uicontext-uicontext.md#getpromptaction)方法获取到PromptAction对象,再通过该对象调用对应方法。
16
17- 列表选择弹出框 (ActionSheet)、警告弹出框 (AlertDialog)、选择器弹出框 (PickerDialog)中除CalendarPickerDialog都需先使用ohos.window中的[getUIContext()](../reference/apis-arkui/arkts-apis-window-Window.md#getuicontext10)方法获取UIContext实例,再通过此实例调用对应方法。或者可以通过自定义组件内置方法[getUIContext()](../reference/apis-arkui/arkui-ts/ts-custom-component-api.md#getuicontext)获取。
18
19操作菜单 (showActionMenu)、对话框 (showDialog)、列表选择弹出框 (ActionSheet)、警告弹出框 (AlertDialog)可以设置isModal为false变成非模态弹窗。
20
21操作菜单 (showActionMenu)、对话框 (showDialog)、列表选择弹出框 (ActionSheet)和警告弹出框 (AlertDialog)不支持设置内容区的字体样式,如字体颜色、大小换行等操作,如需自定义样式,建议使用[不依赖UI组件的全局自定义弹出框](arkts-uicontext-custom-dialog.md)或者[基础自定义弹出框](./arkts-common-components-custom-dialog.md)。
22
23## 生命周期
24
25弹出框提供了生命周期函数,用于通知用户该弹出框的生命周期。生命周期的触发时序依次为:onWillAppear -> onDidAppear -> onWillDisappear -> onDidDisappear,也可参照各组件API。
26
27从API version 19开始,对话框(showDialog)、列表选择弹出框(ActionSheet)、警告弹出框(AlertDialog)支持以下生命周期。
28
29| 名称            |类型| 说明                       |
30| ----------------- | ------ | ---------------------------- |
31| onWillAppear    | Callback&lt;void&gt; | 弹出框显示动效前的事件回调。 |
32| onDidAppear    | Callback&lt;void&gt;  | 弹出框弹出后的事件回调。    |
33| onWillDisappear | Callback&lt;void&gt; | 弹出框退出动效前的事件回调。 |
34| onDidDisappear | Callback&lt;void&gt;  | 弹出框消失后的事件回调。    |
35
36## 操作菜单 (showActionMenu)
37
38操作菜单通过UIContext中的getPromptAction方法获取到PromptAction对象,再通过该对象调用[showActionMenu](../reference/apis-arkui/arkts-apis-uicontext-promptaction.md#showactionmenu11)接口实现,支持在回调或开发者自定义类中使用。
39
40操作菜单中,title字段的字体最大放大倍数为2。
41
42创建并显示操作菜单后,菜单的响应结果会异步返回选中按钮在buttons数组中的索引。
43
44```ts
45import { PromptAction } from '@kit.ArkUI';
46@Entry
47@Component
48struct Index {
49  promptAction: PromptAction = this.getUIContext().getPromptAction();
50
51  build() {
52    Column() {
53      Button('showActionMenu')
54        .onClick(() => {
55          this.promptAction.showActionMenu({
56            title: 'showActionMenu Title Info',
57            buttons: [
58              {
59                text: 'item1',
60                color: '#666666'
61              },
62              {
63                text: 'item2',
64                color: '#000000'
65              },
66            ]
67          })
68            .then(data => {
69              console.info('showActionMenu success, click button: ' + data.index);
70            })
71            .catch((err: Error) => {
72              console.error('showActionMenu error: ' + err);
73            })
74        })
75    }.height('100%').width('100%').justifyContent(FlexAlign.Center)
76  }
77}
78```
79
80![image](figures/UIContextShowMenu.gif)
81
82## 对话框 (showDialog)
83
84对话框通过UIContext中的getPromptAction方法获取到PromptAction对象,再通过该对象调用[showDialog](../reference/apis-arkui/arkts-apis-uicontext-promptaction.md#showdialog)接口实现,支持在回调或开发者自定义类中使用。
85
86对话框中,title字段的字体最大放大倍数为2。
87
88创建并显示对话框,对话框响应后异步返回选中按钮在buttons数组中的索引。
89
90```ts
91// xxx.ets
92import { PromptAction } from '@kit.ArkUI';
93import { BusinessError } from '@kit.BasicServicesKit';
94
95@Entry
96@Component
97struct Index {
98  promptAction: PromptAction = this.getUIContext().getPromptAction();
99
100  build() {
101    Column() {
102      Button('showDialog')
103        .onClick(() => {
104          try {
105            this.promptAction.showDialog({
106              title: 'showDialog Title Info',
107              message: 'Message Info',
108              buttons: [
109                {
110                  text: 'button1',
111                  color: '#000000'
112                },
113                {
114                  text: 'button2',
115                  color: '#000000'
116                }
117              ]
118            }, (err, data) => {
119              if (err) {
120                console.error('showDialog err: ' + err);
121                return;
122              }
123              console.info('showDialog success callback, click button: ' + data.index);
124            });
125          } catch (error) {
126            let message = (error as BusinessError).message;
127            let code = (error as BusinessError).code;
128            console.error(`showDialog args error code is ${code}, message is ${message}`);
129          };
130        })
131    }.height('100%').width('100%').justifyContent(FlexAlign.Center)
132  }
133}
134```
135
136![image](figures/UIShowDialog.gif)
137
138## 选择器弹窗 (PickerDialog)
139
140选择器弹窗通常用于在用户进行某些操作(如点击按钮)时显示特定的信息或选项。
141
142### 日历选择器弹窗 (CalendarPickerDialog)
143
144日历选择器弹窗提供日历视图,包含年、月和星期信息,通过[CalendarPickerDialog](../reference/apis-arkui/arkui-ts/ts-methods-calendarpicker-dialog.md)接口实现。开发者可调用show函数,定义并弹出日历选择器弹窗。
145
146日历选择器弹窗的弹出依赖UI的执行上下文,不可在[UI上下文不明确](./arkts-global-interface.md)的地方使用,具体约束参见[UIContext](../reference/apis-arkui/arkts-apis-uicontext-uicontext.md)说明。
147
148通过配置 acceptButtonStyle、cancelButtonStyle可以实现自定义按钮样式。
149
150```ts
151// xxx.ets
152@Entry
153@Component
154struct CalendarPickerDialogExample {
155  private selectedDate: Date = new Date('2024-04-23');
156
157  build() {
158    Column() {
159      Button("Show CalendarPicker Dialog")
160        .margin(20)
161        .onClick(() => {
162          console.info("CalendarDialog.show")
163          CalendarPickerDialog.show({
164            selected: this.selectedDate,
165            acceptButtonStyle: {
166              fontColor: '#2787d9',
167              fontSize: '16fp',
168              backgroundColor: '#f7f7f7',
169              borderRadius: 10
170            },
171            cancelButtonStyle: {
172              fontColor: Color.Red,
173              fontSize: '16fp',
174              backgroundColor: '#f7f7f7',
175              borderRadius: 10
176            },
177            onAccept: (date: Date)=>{
178              // 当弹出框再次弹出时显示选中的是上一次确定的日期
179              this.selectedDate = date;
180            }
181          })
182        })
183    }.width('100%')
184  }
185}
186```
187
188![image](figures/UIContextShowCalendarpickerDialog.gif)
189
190### 日期滑动选择器弹窗 (DatePickerDialog)
191
192开发者可以利用指定的日期范围,创建日期滑动选择器弹窗,将日期信息清晰地展示在弹出的窗口上。
193
194日期滑动选择器弹窗通过UIContext中的[showDatePickerDialog](../reference/apis-arkui/arkts-apis-uicontext-uicontext.md#showdatepickerdialog)接口实现。
195
196弹窗中配置lunarSwitch、showTime为true时,会展示切换农历的开关和时间,当checkbox被选中时,会显示农历。当按下确定按钮时,弹窗会通过onDateAccept返回目前所选中的日期。如需弹窗再次弹出时显示选中的是上一次确定的日期,就要在回调中重新给selectTime进行赋值。
197
198```ts
199@Entry
200@Component
201struct DatePickerDialogExample {
202  @State selectTime: Date = new Date('2023-12-25T08:30:00');
203
204  build() {
205    Column() {
206      Button('showDatePickerDialog')
207        .margin(30)
208        .onClick(() => {
209          this.getUIContext().showDatePickerDialog({
210            start: new Date("2000-1-1"),
211            end: new Date("2100-12-31"),
212            selected: this.selectTime,
213            lunarSwitch: true,
214            showTime: true,
215            onDateAccept: (value: Date) => {
216              this.selectTime = value;
217              console.info("DatePickerDialog:onAccept()" + JSON.stringify(value));
218            },
219          });
220        })
221    }.width('100%').margin({ top: 5 })
222  }
223}
224
225```
226
227![image](figures/UIContextShowdatepickerDialog.gif)
228
229该示例通过配置disappearTextStyle、textStyle、selectedTextStyle、acceptButtonStyle、cancelButtonStyle实现了自定义文本以及按钮样式。
230
231```ts
232@Entry
233@Component
234struct DatePickerDialogExample {
235  @State selectTime: Date = new Date('2023-12-25T08:30:00');
236
237  build() {
238    Column() {
239      Button('showDatePickerDialog')
240        .margin(30)
241        .onClick(() => {
242          this.getUIContext().showDatePickerDialog({
243            start: new Date("2000-1-1"),
244            end: new Date("2100-12-31"),
245            selected: this.selectTime,
246            textStyle: { color: '#2787d9', font: { size: '14fp', weight: FontWeight.Normal } },
247            selectedTextStyle: { color: '#004aaf', font: { size: '18fp', weight: FontWeight.Regular } },
248            acceptButtonStyle: {
249              fontColor: '#2787d9',
250              fontSize: '16fp',
251              backgroundColor: '#f7f7f7',
252              borderRadius: 10
253            },
254            cancelButtonStyle: {
255              fontColor: Color.Red,
256              fontSize: '16fp',
257              backgroundColor: '#f7f7f7',
258              borderRadius: 10
259            }
260          })
261        })
262    }.width('100%').margin({ top: 5 })
263  }
264}
265```
266
267![image](figures/UIShowDatePickerDialog.gif)
268
269### 时间滑动选择器弹窗 (TimePickerDialog)
270
271开发者可根据24小时的时间区间,创建时间滑动选择器弹窗,将时间信息清晰地展示在弹出的窗口上。
272
273时间滑动选择器弹窗通过UIContext中的[showTimePickerDialog](../reference/apis-arkui/arkts-apis-uicontext-uicontext.md#showtimepickerdialog)接口实现。
274
275该示例通过配置disappearTextStyle、textStyle、selectedTextStyle、acceptButtonStyle、cancelButtonStyle实现了自定义文本以及按钮样式。
276
277```ts
278// xxx.ets
279
280@Entry
281@Component
282struct TimePickerDialogExample {
283  @State selectTime: Date = new Date('2023-12-25T08:30:00');
284
285  build() {
286    Column() {
287      Button('showTimePickerDialog')
288        .margin(30)
289        .onClick(() => {
290          this.getUIContext().showTimePickerDialog({
291            selected: this.selectTime,
292            textStyle: { color: '#2787d9', font: { size: '14fp', weight: FontWeight.Normal } },
293            selectedTextStyle: { color: '#004aaf', font: { size: '18fp', weight: FontWeight.Regular } },
294            acceptButtonStyle: {
295              fontColor: '#2787d9',
296              fontSize: '16fp',
297              backgroundColor: '#f7f7f7',
298              borderRadius: 10
299            },
300            cancelButtonStyle: {
301              fontColor: Color.Red,
302              fontSize: '16fp',
303              backgroundColor: '#f7f7f7',
304              borderRadius: 10
305            }
306          });
307        })
308    }.width('100%').margin({ top: 5 })
309  }
310}
311
312```
313
314![image](figures/UIContextShowTimepickerDialog.gif)
315
316### 文本滑动选择器弹窗 (TextPickerDialog)
317
318开发者可根据指定的选择范围,创建文本滑动选择器弹窗,将文本信息清晰地展示在弹出的窗口上。
319
320文本滑动选择器弹窗通过UIContext中的[showTextPickerDialog](../reference/apis-arkui/arkts-apis-uicontext-uicontext.md#showtextpickerdialog)接口实现。
321
322该示例通过设置range的参数类型为TextCascadePickerRangeContent[],实现3列文本选择器弹窗。当按下确定按钮时,弹窗会通过onAccept返回目前所选中文本和索引值。如需弹窗再次弹出时显示选中的是上一次确定的文本,就要在回调中重新给select进行赋值。
323
324```ts
325@Entry
326@Component
327struct TextPickerDialogExample {
328  private fruits: TextCascadePickerRangeContent[] = [
329    {
330      text: '辽宁省',
331      children: [{ text: '沈阳市', children: [{ text: '沈河区' }, { text: '和平区' }, { text: '浑南区' }] },
332        { text: '大连市', children: [{ text: '中山区' }, { text: '金州区' }, { text: '长海县' }] }]
333    },
334    {
335      text: '吉林省',
336      children: [{ text: '长春市', children: [{ text: '南关区' }, { text: '宽城区' }, { text: '朝阳区' }] },
337        { text: '四平市', children: [{ text: '铁西区' }, { text: '铁东区' }, { text: '梨树县' }] }]
338    },
339    {
340      text: '黑龙江省',
341      children: [{ text: '哈尔滨市', children: [{ text: '道里区' }, { text: '道外区' }, { text: '南岗区' }] },
342        { text: '牡丹江市', children: [{ text: '东安区' }, { text: '西安区' }, { text: '爱民区' }] }]
343    }
344  ];
345  private select : number  = 0;
346  build() {
347    Column() {
348      Button('showTextPickerDialog')
349        .margin(30)
350        .onClick(() => {
351          this.getUIContext().showTextPickerDialog({
352            range: this.fruits,
353            selected: this.select,
354            onAccept: (value: TextPickerResult) => {
355              this.select = value.index as number
356            }
357          });
358        })
359    }.width('100%').margin({ top: 5 })
360  }
361}
362```
363
364![image](figures/UIShowTextPickerDialog.gif)
365
366## 列表选择弹窗 (ActionSheet)
367
368列表选择器弹窗适用于呈现多个操作选项,尤其当界面中仅需展示操作列表而无其他内容时。
369
370列表选择器弹窗通过UIContext中的[showActionSheet](../reference/apis-arkui/arkts-apis-uicontext-uicontext.md#showactionsheet)接口实现。
371
372列表选择弹窗中,title字段的字体最大放大倍数为2。
373
374该示例通过配置width、height、transition等接口,定义了弹窗的样式以及弹出动效。
375
376```ts
377@Entry
378@Component
379struct showActionSheetExample {
380  build() {
381    Column() {
382      Button('showActionSheet')
383        .margin(30)
384        .onClick(() => {
385          this.getUIContext().showActionSheet({
386            title: 'ActionSheet title',
387            message: 'message',
388            autoCancel: false,
389            width: 300,
390            height: 300,
391            cornerRadius: 20,
392            borderWidth: 1,
393            borderStyle: BorderStyle.Solid,
394            borderColor: Color.Blue,
395            backgroundColor: Color.White,
396            transition: TransitionEffect.asymmetric(TransitionEffect.OPACITY
397              .animation({ duration: 3000, curve: Curve.Sharp })
398              .combine(TransitionEffect.scale({ x: 1.5, y: 1.5 }).animation({ duration: 3000, curve: Curve.Sharp })),
399              TransitionEffect.OPACITY.animation({ duration: 100, curve: Curve.Smooth })
400                .combine(TransitionEffect.scale({ x: 0.5, y: 0.5 }).animation({ duration: 100, curve: Curve.Smooth }))),
401            confirm: {
402              value: 'Confirm button',
403              action: () => {
404                console.info('Get Alert Dialog handled');
405              }
406            },
407            alignment: DialogAlignment.Center,
408            sheets: [
409              {
410                title: 'apples',
411                action: () => {
412                }
413              },
414              {
415                title: 'bananas',
416                action: () => {
417                }
418              },
419              {
420                title: 'pears',
421                action: () => {
422                  console.info('pears');
423                }
424              }
425            ]
426          });
427        })
428    }.width('100%').margin({ top: 5 })
429  }
430}
431```
432
433![image](figures/UIContextShowactionSheet.gif)
434
435## 警告弹窗 (AlertDialog)
436
437向用户提问或得到用户的许可时,使用警告弹窗。
438
439* 警告弹窗用来提示重要信息,但会中断当前任务,尽量提供必要的信息和有用的操作。
440* 避免仅使用警告弹窗提供信息,用户不喜欢被信息丰富但不可操作的警告打断。
441
442警告弹窗通过UIContext中的[showAlertDialog](../reference/apis-arkui/arkts-apis-uicontext-uicontext.md#showalertdialog)接口实现。
443
444警告弹窗中,title和subtitle字段的字体最大放大倍数为2。
445
446该示例通过配置width、height、transition等接口,定义了多个按钮弹窗的样式以及弹出动效。
447
448```ts
449@Entry
450@Component
451struct showAlertDialogExample {
452  build() {
453    Column() {
454      Button('showAlertDialog')
455        .margin(30)
456        .onClick(() => {
457          this.getUIContext().showAlertDialog(
458            {
459              title: 'title',
460              message: 'text',
461              autoCancel: true,
462              alignment: DialogAlignment.Center,
463              offset: { dx: 0, dy: -20 },
464              gridCount: 3,
465              transition: TransitionEffect.asymmetric(TransitionEffect.OPACITY
466                .animation({ duration: 3000, curve: Curve.Sharp })
467                .combine(TransitionEffect.scale({ x: 1.5, y: 1.5 }).animation({ duration: 3000, curve: Curve.Sharp })),
468                TransitionEffect.OPACITY.animation({ duration: 100, curve: Curve.Smooth })
469                  .combine(TransitionEffect.scale({ x: 0.5, y: 0.5 })
470                    .animation({ duration: 100, curve: Curve.Smooth }))),
471              buttons: [{
472                value: 'cancel',
473                action: () => {
474                  console.info('Callback when the first button is clicked');
475                }
476              },
477                {
478                  enabled: true,
479                  defaultFocus: true,
480                  style: DialogButtonStyle.HIGHLIGHT,
481                  value: 'ok',
482                  action: () => {
483                    console.info('Callback when the second button is clicked');
484                  }
485                }],
486            }
487          );
488        })
489    }.width('100%').margin({ top: 5 })
490  }
491}
492```
493
494![image](figures/UIContextShowAlertDialog.gif)
495
496
497