HarmonyOS 鸿蒙应用开发( 六、实现自定义弹窗CustomDialog)

本文主要是介绍HarmonyOS 鸿蒙应用开发( 六、实现自定义弹窗CustomDialog),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

自定义弹窗(CustomDialog)可用于广告、中奖、警告、软件更新等与用户交互响应操作。开发者可以通过CustomDialogController类显示自定义弹窗。具体用法请参考自定义弹窗。

在应用的使用和开发中,弹窗是一个很常见的场景,自定义弹窗又因为极高的自由度得以广泛应用。本文以橘子购物中一个应用更新提示的弹窗介绍OpenHarmony的自定义弹窗。 

简单使用

1.1 创建自定义弹窗

使用@CustomDialog装饰器装饰自定义弹窗。
@CustomDialog装饰器用于装饰自定义弹框,此装饰器内进行自定义内容(也就是弹框内容)。

@CustomDialog
struct CustomDialogExample {controller: CustomDialogControllerbuild() {Column() {Text('我是内容').fontSize(20).margin({ top: 10, bottom: 10 })}}
}

1.2 创建构造器,与装饰器呼应相连

在创建好自定义弹窗之后,我们New出来它的对象,他的类型是CustomDialogController。

dialogController: CustomDialogController = new CustomDialogController({builder: CustomDialogExample({}),
})

CustomDialogController参数详解

接口函数原型:

CustomDialogController(value:{builder: CustomDialog, cancel?: () => void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean, gridCount?: number, maskColor?: ResourceColor, openAnimation?: AnimateParam, closeAnimation?: AnimateParam})

这其中最重要的就是builder,我们需要自己实现一个构造器,也就是这个弹窗的页面。上述简单示例的CustomDialogExample,就是一个弹窗页面。

简单示例代码:

// xxx.ets
@CustomDialog
struct CustomDialogExample {@Link textValue: string@Link inputValue: stringcontroller: CustomDialogController// 若尝试在CustomDialog中传入多个其他的Controller,以实现在CustomDialog中打开另一个或另一些CustomDialog,那么此处需要将指向自己的controller放在最后cancel: () => voidconfirm: () => voidbuild() {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(() => {this.inputValue = this.textValuethis.controller.close()this.confirm()}).backgroundColor(0xffffff).fontColor(Color.Red)}.margin({ bottom: 10 })}// dialog默认的borderRadius为24vp,如果需要使用border属性,请和borderRadius属性一起使用。}
}@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.existApp,autoCancel: true,alignment: DialogAlignment.Bottom,offset: { dx: 0, dy: -20 },gridCount: 4,customStyle: false})// 在自定义组件即将析构销毁时将dialogControlle删除和置空aboutToDisappear() {delete this.dialogController, // 删除dialogControllerthis.dialogController = undefined // 将dialogController置空}onCancel() {console.info('Callback when the first button is clicked')}onAccept() {console.info('Callback when the second button is clicked')}existApp() {console.info('Click the callback in the blank area')}build() {Column() {Button(this.inputValue).onClick(() => {if (this.dialogController != undefined) {this.dialogController.open()}}).backgroundColor(0x317aff)}.width('100%').margin({ top: 5 })}
}

升级弹窗界面示例

定义CustomDialogController

首先,我们需要定义一个CustomDialogController:

UpdateDialogController: CustomDialogController = new CustomDialogController({builder: UpdateDialog(),customStyle: true
})

这个CustomDialogController就代表弹窗,UpdateDialog()是弹窗的具体实现,customStyle为ture就表示弹窗样式可以自定义。 

设置调用时机

在这个场景中,我们想要每次打开应用的时候弹窗,其他时候不弹窗,我们需要在首页组件的aboutToAppear中加入以下代码:

aboutToAppear() {if(AppStorage.Get('nowIndex') === undefined || AppStorage.Get('nowIndex') === 0){this.UpdateDialogController.open()}
}

aboutToAppear函数的调用时机是创建自定义组件的新实例后,执行其build()函数之前,所以在首页组件的aboutToAppear加入CustomDialogController的打开开逻辑可使弹窗仅在应用打开的时候触发。

aboutToAppear参考文档:自定义组件的生命周期

实现builder实例

实现实例可以直接在builder后面直接实现,也可以定义在其他文件中,然后通过调用的方式获取,本文以调用方式实现。

实例组件的定义前需加export才能暴露出去:

export struct UpdateDialog {}
@CustomDialog
export struct UpdateDialog {@State currentVersion: string = ''@State richTextData: string = ''@State lastVersion: string = ''@State updateContent: string = ''private context?: AbilityContextprivate customDialogController?: CustomDialogControllerasync aboutToAppear() {this.context = getContext(this) as AbilityContextthis.richTextData = await dialogFeature.getRichTextData(this.context)Logger.info(TAG, `this.richTextData = ${this.richTextData}`)await this.getData()}async getData() {try {this.currentVersion = await dialogFeature.getCurrentVersion()let requestResponseContent: RequestResponseContent = await dialogFeature.getLastVersion()if (requestResponseContent.content === null || requestResponseContent.content === undefined) {return}this.updateContent = requestResponseContent.contentif (requestResponseContent.versionName === null || requestResponseContent.versionName === undefined) {return}this.lastVersion = requestResponseContent.versionName} catch (err) {Logger.info(TAG, `getApplicationVersion is fail`)}}...

 弹窗具体实现

自定义弹窗的实现就是在原页面的基础上再加一层页面,页面内容自定义。

弹窗页面我们可以通过stack组件实现,stack组件会使容器内的子组件堆叠布局,使用stack的好处是可以添加一层遮罩效果。

Stack() {// mask 遮罩层Column().width('100%').height('100%').backgroundColor('#000000').opacity(.4)...

以上代码在stack的第一层设置了backgroundColor和opacity属性,这样会产生如开始示意图的遮罩效果。

需要注意的是,需要在取消按钮的调用函数中关闭弹窗,具体代码如下:

Button($r('app.string.cancel')).onClick(() => {this.customDialogController.close()})

 弹窗界面完整代码

build() {Stack() {// mask 遮罩层Column().width('100%').height('100%').backgroundColor('#000000').opacity(.4)Column() {Stack({ alignContent: Alignment.TopStart }) {Text($r('app.string.update_title')).fontSize(30).fontColor('#FFFFFF').fontWeight(500).margin({ top: 70, left: 76 })Text(`V${(this.lastVersion || updateData.versionName)}`).fontSize(16).backgroundColor('#FFFFFF').textAlign(TextAlign.Center).fontColor('#E9304E').borderRadius(20).width(80).aspectRatio(2.8).margin({ top: 110, left: 76 })Column() {// 富文本容器Scroll() {Column() {if (this.richTextData) {RichText((this.updateContent || this.richTextData)).width('100%').height('100%')}}.width('100%')}.height(200)Row() {Button($r('app.string.cancel')).commonButtonStyle().fontSize(20).margin({ left: 10 }).fontColor('#E92F4F').backgroundColor('rgba(0,0,0,0.05)').margin({ right: 10 }).onClick(() => {this.customDialogController.close()}).key("cancel")Button($r('app.string.update_now')).commonButtonStyle().fontSize(20).margin({ right: 10 }).fontColor('#FFFFFF').backgroundColor('#E92F4F').margin({ left: 10 }).onClick(() => {this.customDialogController.close()}).key("Now")}.margin({ top: 30 })}.width('100%').padding({ left: 25, right: 25 }).margin({ top: 230 })}.height(600).width('100%').backgroundImage($r('app.media.update'), ImageRepeat.NoRepeat).backgroundImageSize(ImageSize.Contain)}.width(480).padding({ left: 16, right: 16 })}.width('100%').height('100%')
}

参考

本文供稿:刘家辉 (JaysonLiu3) - Gitee.com

本例参考的官方文档:橘子购物

自定义弹窗官方文档

自定义组件的生命周期-aboutToAppear

写在最后

  • 如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
  • 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
  • 关注博主,同时可以期待后续文章ing🚀,不定期分享原创知识。
  • 想要获取更多完整鸿蒙最新VIP学习资料,请关注猫哥公众号【猫青年】,回复“鸿蒙”获取

 

其他资源 

层叠布局(Stack)-构建布局-开发布局-基于ArkTS的声明式开发范式-UI开发-开发-HarmonyOS应用开发

线性布局(Row/Column)-构建布局-开发布局-基于ArkTS的声明式开发范式-UI开发-开发-HarmonyOS应用开发

按钮(Button)-添加常用组件-添加组件-基于ArkTS的声明式开发范式-UI开发-开发-HarmonyOS应用开发

【鸿蒙软件开发】自定义弹窗(CustomDialog)_harmonyos developer自定义弹框-CSDN博客

免费的api接口网站有哪些? - 知乎

文档中心

applications_app_samples: We provide a series of app samples to help you quickly get familiar with the APIs and app development process of the OpenHarmony SDKs. | 为帮助开发者快速熟悉OpenHarmony SDK所提供的API和应用开发流程,我们提供了一系列的应用示例

Codelabs: 分享知识与见解,一起探索HarmonyOS的独特魅力。

这篇关于HarmonyOS 鸿蒙应用开发( 六、实现自定义弹窗CustomDialog)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/648460

相关文章

使用Python实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Python实现微信自动锁定工具

《Python实现微信自动锁定工具》在数字化办公时代,微信已成为职场沟通的重要工具,但临时离开时忘记锁屏可能导致敏感信息泄露,下面我们就来看看如何使用Python打造一个微信自动锁定工具吧... 目录引言:当微信隐私遇到自动化守护效果展示核心功能全景图技术亮点深度解析1. 无操作检测引擎2. 微信路径智能获

Python中pywin32 常用窗口操作的实现

《Python中pywin32常用窗口操作的实现》本文主要介绍了Python中pywin32常用窗口操作的实现,pywin32主要的作用是供Python开发者快速调用WindowsAPI的一个... 目录获取窗口句柄获取最前端窗口句柄获取指定坐标处的窗口根据窗口的完整标题匹配获取句柄根据窗口的类别匹配获取句

在 Spring Boot 中实现异常处理最佳实践

《在SpringBoot中实现异常处理最佳实践》本文介绍如何在SpringBoot中实现异常处理,涵盖核心概念、实现方法、与先前查询的集成、性能分析、常见问题和最佳实践,感兴趣的朋友一起看看吧... 目录一、Spring Boot 异常处理的背景与核心概念1.1 为什么需要异常处理?1.2 Spring B

Python位移操作和位运算的实现示例

《Python位移操作和位运算的实现示例》本文主要介绍了Python位移操作和位运算的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一... 目录1. 位移操作1.1 左移操作 (<<)1.2 右移操作 (>>)注意事项:2. 位运算2.1

如何在 Spring Boot 中实现 FreeMarker 模板

《如何在SpringBoot中实现FreeMarker模板》FreeMarker是一种功能强大、轻量级的模板引擎,用于在Java应用中生成动态文本输出(如HTML、XML、邮件内容等),本文... 目录什么是 FreeMarker 模板?在 Spring Boot 中实现 FreeMarker 模板1. 环

Qt实现网络数据解析的方法总结

《Qt实现网络数据解析的方法总结》在Qt中解析网络数据通常涉及接收原始字节流,并将其转换为有意义的应用层数据,这篇文章为大家介绍了详细步骤和示例,感兴趣的小伙伴可以了解下... 目录1. 网络数据接收2. 缓冲区管理(处理粘包/拆包)3. 常见数据格式解析3.1 jsON解析3.2 XML解析3.3 自定义

SpringMVC 通过ajax 前后端数据交互的实现方法

《SpringMVC通过ajax前后端数据交互的实现方法》:本文主要介绍SpringMVC通过ajax前后端数据交互的实现方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价... 在前端的开发过程中,经常在html页面通过AJAX进行前后端数据的交互,SpringMVC的controll

Spring Security自定义身份认证的实现方法

《SpringSecurity自定义身份认证的实现方法》:本文主要介绍SpringSecurity自定义身份认证的实现方法,下面对SpringSecurity的这三种自定义身份认证进行详细讲解,... 目录1.内存身份认证(1)创建配置类(2)验证内存身份认证2.JDBC身份认证(1)数据准备 (2)配置依

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too