可以通过使用自定义弹窗和定时器达到类似Toast的效果。
场景一:自定义弹窗实现弹窗中加入icon和文字,支持Button。
方案:
⦁ 使用@CustomDialog装饰器装饰自定义弹窗,在此装饰器内进行自定义内容(也就是弹框内容)、并创建构造器,与装饰器呼应相连。
⦁ 使用定时器,在页面的生命周期onPageShow中设置定时任务,页面显示时打开弹窗。
核心代码
@CustomDialog
struct CustomDialogExample {
controller?: CustomDialogController
build() {
Row() {
Image($r('app.media.huawei'))
.height(60)
.width(60)
.margin(20)
.borderRadius(10)
Text('Toast弹窗')
Button('进入')
.onClick(() => {
if (this.controller != undefined) {
this.controller.close()
}
})
.margin(20)
}
.width('100%')
.backgroundColor(Color.Grey)
}
}
@Entry
@Component
struct CustomDialogUser {
dialogController: CustomDialogController | null = new CustomDialogController({
builder: CustomDialogExample(),
autoCancel: true,
alignment: DialogAlignment.CenterStart,
offset: { dx: 10, dy: 10 },
gridCount: 4,
showInSubWindow: false,
isModal: true,
customStyle: false,
cornerRadius: 10,
})
// 使用定时器,在页面的生命周期 onPageShow中设置定时任务,页面显示时打开弹窗
onPageShow() {
setTimeout(() => {
if (this.dialogController != null) {
this.dialogController.open()
}
}, 2000);
}
build() {
Column() {
// ...
}
}
}
场景二:自定义弹窗样式。
⦁ 可自定义弹窗位置,5.0规格,未设置alignment弹窗默认居中显示。
⦁ 可设置弹窗宽度、高度。gridCount弹窗宽度占栅格宽度的个数最大为4栅格宽度(400vp),API 12可通过width和height属性指定宽高。
弹窗高度最大值:0.9 *(窗口高度 - 安全区域)
⦁ 可设置是否有蒙层,有蒙层时可自定义蒙层颜色。
⦁ 可设置弹框边框样式、边框宽度、边框颜色。