
回复
最近在开发鸿蒙应用时,经常需要用到各种弹窗。SDK文档看着还行,真用起来发现坑还不少。这里把踩过的坑和实现细节都记下来,省得以后自己或者同事再掉坑里。
弹窗就是在应用界面上弹出的一个临时窗口,用于展示重要信息、收集用户输入或者进行确认操作。鸿蒙提供了多种弹窗组件,可以根据需求选择合适的类型。
我们项目需要做个问卷调查,本来想自己写个表单,后来发现太麻烦了。正好有个现成的问卷系统,就想着用网页弹窗来实现。这样既能复用已有的问卷系统,又能保持统一的用户体验,一举两得。
// 该引的都得引,不然编译直接报错
import { webview } from '@kit.ArkWeb';
import { BreakpointConstants } from '../../utils/BreakpointConstants';
// 配置网页Cookie,这个很重要,不配置的话问卷可能提交不了
webview.once("webInited", () => {
console.log("配置Cookie同步");
webview.WebCookieManager.configCookieSync("你的问卷地址", "1");
});
// 自定义弹窗组件,这里用@CustomDialog装饰器
@CustomDialog
export struct 问卷调查弹窗 {
// 弹窗控制器,用来控制弹窗的显示和隐藏
控制器: CustomDialogController;
// 网页控制器,用来控制网页的加载和刷新
网页控制器: webview.WebviewController = new webview.WebviewController();
// 当前断点,用来适配不同屏幕尺寸
@StorageLink('当前断点') 当前断点: string = BreakpointConstants.BREAKPOINT_LG;
build() {
Column() {
// 标题栏,这里可以自定义样式
Row() {
Text('问卷调查')
.fontSize(20)
.fontWeight(FontWeight.Medium)
.fontColor($r('app.color.text_primary'))
Blank()
// 关闭按钮,记得加点击事件
Button({ type: ButtonType.Circle }) {
Text('✕')
.fontSize(20)
.fontColor($r('app.color.text_secondary'))
}
.width(32)
.height(32)
.backgroundColor('transparent')
.onClick(() => this.控制器.close())
}
.width('100%')
.padding({ left: 24, right: 16 })
.margin({ top: 16, bottom: 16 })
// 网页内容,这里可以加载任何网页
Column() {
Web({
src: '你的问卷地址',
controller: this.网页控制器
})
.height("90%")
}
}
// 根据屏幕尺寸调整弹窗大小
.width(this.当前断点 === BreakpointConstants.BREAKPOINT_LG ? '50%' : '100%')
.height('90%')
.backgroundColor($r('app.color.background'))
.borderRadius({ topLeft: 24, topRight: 24 })
}
}
// 在页面中使用弹窗,这里展示最简单的用法
@Entry
@Component
struct 主页面 {
// 弹窗控制器,记得设置对齐方式和偏移量
问卷调查弹窗控制器: CustomDialogController = new CustomDialogController({
builder: 问卷调查弹窗(),
alignment: DialogAlignment.Center,
offset: { dx: 0, dy: 0 },
customStyle: true
});
build() {
Column() {
Button('打开问卷')
.onClick(() => {
this.问卷调查弹窗控制器.open();
})
}
}
}
弹窗样式问题
网页加载问题
性能问题
开发配置
安全考虑
性能优化
用户体验
弹窗设计
代码组织
测试建议
弹窗不显示
网页加载失败
性能问题
有问题欢迎留言,大家一起踩坑一起填。方案适合大部分场景,特殊需求记得多测几遍。
这个弹窗组件已经集成到鸿蒙开发者工具箱里了,欢迎下载体验!
作者:在人间耕耘
版权声明:本文为博主原创文章,转载请附上原文出处链接及本声明。