任何运用都离不开弹窗,本日我们就基于ArkTS开拓措辞,先容下弹窗的实现办法。鸿蒙弹窗分为:
警告弹窗警告弹窗AlertDialog,由标题、内容、操作按钮三部分组成,详细代码为:
Button('点击显示警告弹窗') .onClick(() => { AlertDialog.show( { title: '这是标题', // 标题 message: '这里是内容啊,这里是内容', // 内容 autoCancel: false, // 点击遮障层时,是否关闭弹窗。 alignment: DialogAlignment.Bottom, // 弹窗在竖直方向的对齐办法 offset: { dx: 0, dy: -20 }, // 弹窗相对alignment位置的偏移量 primaryButton: { value: '取消', action: () => { console.info('Callback when the first button is clicked'); } }, secondaryButton: { value: '删除', fontColor: '#D94838', action: () => { console.info('Callback when the second button is clicked'); } }, cancel: () => { // 点击遮障层关闭dialog时的回调 console.info('Closed callbacks'); } } ) })

这类弹窗,多数运用于性别、出生日期、地区等选择。比如:
TextPickerDialogDatePickerDialog文本选择窗TextPickerDialog,代码为:
日期选择窗DatePickerDialog,代码为:
如果以上不能知足需求,我们还可以自定义自己的弹窗。
自定义弹窗自定义弹窗的利用更加灵巧,适用于更多的业务场景,在自定义弹窗中您可以自定义弹窗内容,构建更加丰富的弹窗界面。自定义弹窗的界面可以通过装饰器@CustomDialog定义的组件来实现,然后结合CustomDialogController来掌握自定义弹窗的显示和隐蔽。
上图可以看出,自定义弹窗实在是加载了一个自定义的构建构造体,也便是builder后面的构造体,本例中的AddTargetDialog,代码为:
import { CommonConstants } from '../common/constant/CommonConstant';@Preview@CustomDialogexport default struct AddTargetDialog { private controller?: CustomDialogController; private taskName: string = '' private onClickOk ?: (value: string) => void; build() { Column() { Text('添加子目录') .width(CommonConstants.FULL_WIDTH) .fontSize(20) .fontWeight(CommonConstants.FONT_WEIGHT) .fontColor('#182431') .textAlign(TextAlign.Center) TextInput({ placeholder: '请输入子目标名称' }) .placeholderColor(Color.Gray) .placeholderFont({ size: 16 }) .caretColor(Color.Blue) .backgroundColor('#0d182431') .width(CommonConstants.FULL_WIDTH) .height(CommonConstants.DIALOG_INPUT_HEIGHT) .margin({ top: CommonConstants.DIALOG_INPUT_MARGIN }) .fontSize(16) .onChange((value) => { this.taskName = value }) Blank() Row() { Button('取消') .dialogButtonStyle() .onClick(() => { this.controller.close() }) Divider().vertical(true) Button('确定') .dialogButtonStyle() .onClick(() => { if (this.onClickOk !== undefined) { this.onClickOk(this.taskName) } }) } .width(CommonConstants.DIALOG_OPERATION_WIDTH) .height(CommonConstants.DIALOG_OPERATION_HEIGHT) .justifyContent(FlexAlign.SpaceBetween) } .padding('24vp') .width(CommonConstants.DIALOG_WIDTH) .height('168vp') .borderRadius(32) .backgroundColor(Color.White) }}@Extend(Button) function dialogButtonStyle() { .fontSize(16) .height(32) .width(96) .backgroundColor(Color.White) .fontColor('#007dff')}
看着很多,实在很大略,首先是Column布局,从上到下分为:标题、输入框、操作按钮。实在它便是一个UI组件,嵌入到了CustomDialogController这个容器中,形成了一个弹窗。至于其他的属性,和上面两种类型的弹窗都差不多。
原创不易,鉴于本人水平有限,文中如有缺点之处欢迎大家示正。欢迎大家点个关注,我将连续为大家分享干系的技能内容。