抖音制作图片的软件360优化大师旧版
HarmonyOS各种弹窗的使用指南
- HarmonyOS各种弹窗的使用指南
- 1. 警告弹窗(AlertDialog)
- 功能特点
- 代码实例
- 效果
- 使用场景
- 改进建议
- 2. 列表选择弹窗(ActionSheet)
- 功能特点
- 代码实例
- 效果
- 使用场景
- 改进建议
- 3. 自定义弹窗(CustomDialog)
- 功能特点
- 代码实例
- 效果
- 使用场景
- 改进建议
- 4. 日期滑动选择器弹窗(DatePickerDialog)
- 功能特点
- 代码实例
- 效果
- 使用场景
- 改进建议
- 5. 文本滑动选择器弹窗(TextPickerDialog)
- 功能特点
- 代码实例
- 效果
- 使用场景
- 改进建议
- 6. 时间滑动选择器弹窗(TimePickerDialog)
- 功能特点
- 代码实例
- 效果
- 使用场景
- 改进建议
- 总结
HarmonyOS各种弹窗的使用指南
在HarmonyOS应用开发中,弹窗是一种常见的UI组件,用于向用户展示信息或获取用户输入。本文将详细介绍HarmonyOS中几种常见的弹窗组件及其使用方法,包括警告弹窗、列表选择弹窗、自定义弹窗、日期选择器弹窗、时间选择器弹窗和文本选择器弹窗。
详细请到官方技术文档仔细学习!官方文档链接
1. 警告弹窗(AlertDialog)
警告弹窗用于向用户展示警告信息,并提供确认按钮。它适用于需要用户确认操作的场景,比如删除数据或提交表单。
功能特点
- 单按钮模式:仅提供一个确认按钮。
- 双按钮模式:提供确认和取消两个按钮。
- 自定义按钮样式:可以设置按钮的文本、颜色和点击回调。
代码实例
@Entry
@Component
struct AlertDialogPage {build() {Column() {Button("警告弹窗,有一个按钮").onClick(() => {AlertDialog.show({title: '操作提示', // 弹窗标题message: '你确认删除吗?', // 弹窗内容autoCancel: true, //点击遮障层时,是否关闭弹窗。alignment: DialogAlignment.Center, //弹窗位置gridCount: 3, // 弹窗容器宽度所占用栅格数offset: { dx: 0, dy: 0 }, //弹窗相对alignment所在位置的偏移量// 单个按钮confirm: {value: '确定',action: () => {console.info('xxxxxx')},fontColor: '#00f'},})})Button("警告弹窗,有两个按钮").onClick(() => {AlertDialog.show({title: '操作提示', // 弹窗标题message: '你确认删除吗?', // 弹窗内容autoCancel: true, //点击遮障层时,是否关闭弹窗。alignment: DialogAlignment.Center, //弹窗位置gridCount: 3, // 弹窗容器宽度所占用栅格数offset: { dx: 0, dy: 0 }, //弹窗相对alignment所在位置的偏移量// 多个按钮primaryButton: { //主按钮的文本内容、文本色、按钮背景色和点击回调。value: '确认', //按钮文字action: () => { //按钮回调console.info('成功点击')},fontColor: '#f00'},secondaryButton: { //副按钮的文本内容、文本色、按钮背景色和点击回调。value: '取消', //按钮文字action: () => { //按钮回调console.info('取消了')},fontColor: '#00f'},})})}.width("100%").height("100%").justifyContent(FlexAlign.Center) // 垂直居中.alignItems(HorizontalAlign.Center) // 水平居中}
}
效果
- 第一个弹窗
- 第二个弹窗
使用场景
- 确认删除操作。
- 提示用户重要信息。
改进建议
- 在确认按钮中添加实际的逻辑操作,比如删除数据。
- 在取消按钮中添加用户友好的提示。
2. 列表选择弹窗(ActionSheet)
列表选择弹窗用于向用户提供了一个列表供用户选择。它适用于需要用户从多个选项中选择一个的场景。
功能特点
- 选项列表:支持多个选项项,每个选项可以设置文本和点击回调。
- 确认按钮:提供一个确认按钮,用户选择后可以确认。
- 取消回调:点击遮障层时触发取消回调。
代码实例
@Entry
@Component
struct ActionSheetPage {@State selectedFruit: string = '' // 1. 添加状态变量记录选中项build() {Column() {Button("列表选择弹窗").onClick(() => {ActionSheet.show({title: '请选择水果',message: '水果信息',autoCancel: true,confirm: {value: '确认按钮',action: () => {console.log('确认点击成功')}},cancel: () => {console.log('你点击了关闭')},alignment: DialogAlignment.Bottom,offset: { dx: 0, dy: -20 },sheets: [{title: 'apples',action: () => {this.selectedFruit = 'apples' // 2. 更新选中状态}},{title: 'bananas',action: () => {this.selectedFruit = 'bananas'}},{title: 'pears',action: () => {this.selectedFruit = 'pears'}}]})})Text(this.selectedFruit ? `已选择:${this.selectedFruit}` : '请选择水果').fontSize(20).margin(20)}.width("100%").height("100%")}
}
效果
- 点击选择弹窗按钮
- 点击bananas
- 显示信息
使用场景
- 选择水果、颜色等选项。
- 提供多个操作选项,比如分享、收藏等。
改进建议
- 在选项项中添加图标或图片,增强视觉效果。
- 在确认按钮中添加实际的逻辑操作。
3. 自定义弹窗(CustomDialog)
自定义弹窗允许开发者自定义弹窗的样式和内容。它适用于需要高度自定义的场景,比如用户输入或复杂交互。
功能特点
- 自定义内容:可以完全自定义弹窗的内容和布局。
- 嵌套弹窗:支持在一个弹窗中打开另一个弹窗。
- 状态管理:通过状态变量管理弹窗的显示和关闭。
代码实例
// xxx.ets
@CustomDialog
struct CustomDialogExampleTwo {controllerTwo?: CustomDialogControllerbuild() {Column() {Text('我是第二个弹窗').fontSize(30).height(100)Button('点我关闭第二个弹窗').onClick(() => {if (this.controllerTwo != undefined) {this.controllerTwo.close()}}).margin(20)}}
}@CustomDialog
struct CustomDialogExample {@Link textValue: string@Link inputValue: stringdialogControllerTwo: CustomDialogController = new CustomDialogController({builder: CustomDialogExampleTwo(),alignment: DialogAlignment.Bottom,offset: { dx: 0, dy: -25 } })controller?: CustomDialogController// 若尝试在CustomDialog中传入多个其他的Controller,以实现在CustomDialog中打开另一个或另一些CustomDialog,那么此处需要将指向自己的controller放在所有controller的后面cancel: () => void = () => {}confirm: () => void = () => {}build() {Column() {Text('Change text').fontSize(20).margin({ top: 10, bottom: 10 })TextInput({ placeholder: '', text: this.textValue }).height(60).width('90%').onChange((value: string) => {this.textValue = value})Text('Whether to change a text?').fontSize(16).margin({ bottom: 10 })Flex({ justifyContent: FlexAlign.SpaceAround }) {Button('cancel').onClick(() => {this.controller.close()this.cancel()}).backgroundColor(0xffffff).fontColor(Color.Black)Button('confirm').onClick(() => {if (this.controller != undefined) {this.inputValue = this.textValuethis.controller.close()this.confirm()}}).backgroundColor(0xffffff).fontColor(Color.Red)}.margin({ bottom: 10 })Button('点我打开第二个弹窗').onClick(() => {this.dialogControllerTwo.open()}).margin(20)}.borderRadius(10)}
}@Entry
@Component
struct CustomDialogUser {@State textValue: string = ''@State inputValue: string = 'click me'dialogController: CustomDialogController = new CustomDialogController({builder: CustomDialogExample({cancel: this.onCancel,confirm: this.onAccept,textValue: $textValue,inputValue: $inputValue}),cancel: this.exitApp,autoCancel: true,alignment: DialogAlignment.Bottom,offset: { dx: 0, dy: -20 },gridCount: 4,customStyle: false})// 在自定义组件即将析构销毁时将dialogControlle置空aboutToDisappear() {this.dialogController = null // 将dialogController置空}onCancel() {console.info('Callback when the first button is clicked')}onAccept() {console.info('Callback when the second button is clicked')}exitApp() {console.info('Click the callback in the blank area')}build() {Column() {Button(this.inputValue).onClick(() => {this.dialogController.open()}).backgroundColor(0x317aff)}.width('100%').margin({ top: 5 })}
}
效果
- 点击按钮
- 点击第二个弹窗按钮
- 显示第二个弹窗
- 输入Change text,点击confirm
- 按钮名称变成对应字符
使用场景
- 用户输入表单。
- 复杂的交互逻辑,比如多步骤操作。
改进建议
- 在弹窗中添加更多的输入字段或验证逻辑。
- 在关闭回调中添加用户友好的提示。
4. 日期滑动选择器弹窗(DatePickerDialog)
日期滑动选择器弹窗用于让用户选择日期。它支持阳历和阴历的切换。
功能特点
- 日期范围:可以设置起始日期和结束日期。
- 阳历/阴历:支持阳历和阴历的切换。
- 回调函数:提供
onAccept
、onCancel
和onChange
回调。
代码实例
@Entry
@Component
struct DatePickDialogPage {@State selectedDate: Date = new Date("2010-1-1")@State displayDate: string = ''// 日期格式化方法private formatDate(date: Date): string {const year = date.getFullYear()const month = (date.getMonth() + 1).toString().padStart(2, '0')const day = date.getDate().toString().padStart(2, '0')return `${year}-${month}-${day}`}build() {Column() {Text(this.displayDate || '请选择日期').fontSize(24).margin(20).fontColor('#07c160')Button("阳历日期").margin(10).width(200).onClick(() => {DatePickerDialog.show({start: new Date("2000-1-1"),end: new Date("2100-12-31"),selected: this.selectedDate,onAccept: (value: DatePickerResult) => {// 重点:必须创建新对象才能触发状态更新this.selectedDate = new Date(value.year, value.month, value.day)this.displayDate = this.formatDate(this.selectedDate)console.info("阳历选择:", JSON.stringify(value))},onCancel: () => {console.info("取消阳历选择")},onChange: (value: DatePickerResult) => {console.info("阳历滚动变化:", JSON.stringify(value))}})})Button("阴历日期").margin(10).width(200).onClick(() => {DatePickerDialog.show({start: new Date("2000-1-1"),end: new Date("2100-12-31"),selected: this.selectedDate,lunar: true,onAccept: (value: DatePickerResult) => {this.selectedDate = new Date(value.year, value.month, value.day)this.displayDate = this.formatDate(this.selectedDate)console.info("阴历选择:", JSON.stringify(value))},onCancel: () => {console.info("取消阴历选择")},onChange: (value: DatePickerResult) => {console.info("阴历滚动变化:", JSON.stringify(value))}})})}.width("100%").height("100%").justifyContent(FlexAlign.Center).alignItems(HorizontalAlign.Center)}
}
效果
- 点击阳历日期按钮
- 点击阴历日期按钮
使用场景
- 选择生日、预约日期等。
- 需要显示农历的场景,比如传统节日。
改进建议
- 在选择日期后,自动填充到表单中。
- 添加日期范围的动态调整。
5. 文本滑动选择器弹窗(TextPickerDialog)
文本滑动选择器弹窗用于让用户从列表中选择一个文本项。它适用于需要用户从固定选项中选择的场景。
功能特点
- 选项范围:可以设置选项的范围。
- 初始选中项:可以设置初始选中项的索引。
- 回调函数:提供
onAccept
、onCancel
和onChange
回调。
代码实例
@Entry
@Component
struct TextPickerDialogDemo {@State select: number = 2;private fruits: string[] = ['苹果', '橘子', '香蕉', '猕猴桃', '西瓜'];build() {Column(){Button("TextPickerDialog").margin(20).onClick(() => {TextPickerDialog.show({range: this.fruits, // 设置文本选择器的选择范围selected: this.select, // 设置初始选中项的索引值onAccept: (value: TextPickerResult) => { // 点击弹窗中的“确定”按钮时触发该回调。// 设置select为按下确定按钮时的选中项index,这样当弹窗再次弹出时显示选中的是上一次确定的选项this.select = value.index;console.info("TextPickerDialog:onAccept()" + JSON.stringify(value));},onCancel: () => { // 点击弹窗中的“取消”按钮时触发该回调。console.info("TextPickerDialog:onCancel()");},onChange: (value: TextPickerResult) => { // 滑动弹窗中的选择器使当前选中项改变时触发该回调。console.info("TextPickerDialog:onCancel()" + JSON.stringify(value));}})})}.width('100%')}
}
效果
- 点击按钮
使用场景
- 选择性别、职业等固定选项。
- 需要用户从多个选项中选择一个的场景。
改进建议
- 在选项项中添加图标或图片,增强视觉效果。
- 在选择后,自动填充到表单中。
6. 时间滑动选择器弹窗(TimePickerDialog)
时间滑动选择器弹窗用于让用户选择时间。它支持12小时制和24小时制的切换。
功能特点
- 时间格式:支持12小时制和24小时制。
- 回调函数:提供
onAccept
、onCancel
和onChange
回调。 - 时间范围:可以设置时间的范围。
代码实例
@Entry
@Component
struct TimePickerDialogPage {private selectTime: Date = new Date('2025-04-03T00:00:00') // 修改为 2025 年 4 月 3 日build() {Column() {Button("TimePickerDialog 12小时制").margin(20).onClick(() => {TimePickerDialog.show({selected: this.selectTime,onAccept: (value: TimePickerResult) => {// 设置 selectTime 为 2025 年 4 月 2 日,确保下次弹窗时标题不变this.selectTime = new Date('2025-04-02T' + value.hour + ':' + value.minute + ':00')console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))},onCancel: () => {console.info("TimePickerDialog:onCancel()")},onChange: (value: TimePickerResult) => {console.info("TimePickerDialog:onChange()" + JSON.stringify(value))}})})Button("TimePickerDialog 24小时制").margin(20).onClick(() => {TimePickerDialog.show({selected: this.selectTime,useMilitaryTime: true,onAccept: (value: TimePickerResult) => {// 设置 selectTime 为 2025 年 4 月 2 日,确保下次弹窗时标题不变this.selectTime = new Date('2025-04-02T' + value.hour + ':' + value.minute + ':00')console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))},onCancel: () => {console.info("TimePickerDialog:onCancel()")},onChange: (value: TimePickerResult) => {console.info("TimePickerDialog:onChange()" + JSON.stringify(value))}})})}.width("100%").height("100%").justifyContent(FlexAlign.Center) // 垂直居中.alignItems(HorizontalAlign.Center) // 水平居中}
}
效果
- 点击第一个按钮,12小时制
- 点击第一个按钮,24小时制
使用场景
- 选择预约时间、闹钟时间等。
- 需要用户输入具体时间的场景。
改进建议
- 在选择时间后,自动填充到表单中。
- 添加时间范围的限制。
总结
通过以上示例,我们可以看到HarmonyOS提供了丰富的弹窗组件,开发者可以根据实际需求选择合适的组件来实现弹窗功能。希望本文能够帮助您更好地理解和使用HarmonyOS的弹窗组件。如果您有任何问题或建议,欢迎在评论区留言!