1.项目开发中,鸿蒙自带的弹窗样式和UI设计的不一样,这时候就需要我们自己去自定义弹窗,自定义确认和取消弹窗为实例,代码如下
@CustomDialog是一个装饰器(弹窗装饰器)
使用@CustomDialog装饰自定义弹窗。里面的弹窗布局自己写
/**
* @FileName : CustomDialogConfirmExample
* @Author : 晖
* @Time : 2024/7/18 9:52
* @Description : 文件描述
*/
@CustomDialog
export struct CustomDialogConfirmExample {
@State title: string = '这是自定义弹窗'
//dialog控制器
controller: CustomDialogController
build() {
Column() {
Text(this.title)
.fontSize(16)
.fontColor($r('app.color.color_35363C'))
.fontWeight(FontWeight.Bold)
.margin({ top: 24 })
}.backgroundColor($r('app.color.white'))
.borderRadius(12)
.margin({ left: 16, right: 16 })
}
}
2.构建构造器,链接装饰器,title是修改里面标题信息,cornerRadius设置圆角backgroundBlurStyle设置弹窗显示样式
dialogCacheController: CustomDialogController = new CustomDialogController({
builder: CustomDialogConfirmExample({
title: '这是自定义弹窗',
}), cornerRadius: 12, backgroundBlurStyle: BlurStyle.NONE
})
3.显示自定义弹窗方法this.dialogCacheController.open()
this.dialogCacheController.open()
4.下面是完整的一个确认和取消弹窗的完整代码:
自定义好自己需要的样式,下方布局中的颜色自己去资源文件里面定义,或者直接写死颜色代码
/**
* @FileName : CustomDialogConfirmExample
* @Author : 晖
* @Time : 2024/7/18 9:52
* @Description : 文件描述
*/
@CustomDialog
export struct CustomDialogConfirmExample {
//取消按钮点击事件
cancel?: () => void
//确定按钮点击事情
confirm?: () => void
@State title: string = '确认提示'
@State content: string = '确认内容'
@State cancelText: string = '取消'
@State confirmText: string = '确定'
//dialog控制器
controller: CustomDialogController
build() {
Column() {
Text(this.title)
.fontSize(16)
.fontColor($r('app.color.color_35363C'))
.fontWeight(FontWeight.Bold)
.margin({ top: 24 })
Text(this.content)
.fontSize(15)
.fontColor($r('app.color.color_35363C'))
.margin(20)
Line().width('100%').height(1).backgroundColor($r('app.color.dialog_line'))
Row() {
Button(this.cancelText)
.fontSize(16)
.fontWeight(FontWeight.Bold)
.backgroundColor($r('app.color.white'))
.fontColor($r('app.color.color_35363C'))
.layoutWeight(1)
.onClick(() => {
this.controller.close()
if (this.cancel) {
this.cancel()
}
})
Line().width(1).height(50).backgroundColor($r('app.color.dialog_line'))
Button(this.confirmText)
.fontSize(16)
.fontWeight(FontWeight.Bold)
.fontColor($r('app.color.theme_red'))
.backgroundColor($r('app.color.white'))
.layoutWeight(1)
.onClick(() => {
this.controller.close()
if (this.confirm) {
this.confirm()
}
})
}
.height(50)
}.backgroundColor($r('app.color.white'))
.borderRadius(12)
.margin({ left: 16, right: 16 })
}
}
.在你需要地方创建构造器,然后调用
//退出登录
dialogCacheController: CustomDialogController = new CustomDialogController({
builder: CustomDialogConfirmExample({
confirm: () => {
//确定按钮单击事情
//this.onCacheConfirm() 也可自己定义一个方法,把单击事件放到外面去
},
cancel:()=>{
//取消单击事件
},
title: '退出该账提示',
content: '确定退出该账号吗'
}), cornerRadius: 12, backgroundBlurStyle: BlurStyle.NONE
})
// 确定单击事件
// onCacheConfirm() {
// StringUtils.cleanAppCache(getContext())
// this.CacheSize = 0;
// }
调用显示方法this.dialogCacheController.open(),弹窗消失方法this.dialogCacheController.close()
this.dialogCacheController.open()