HarmonyOS鸿蒙开发 弹窗及加载中指示器HUD功能实现

HarmonyOS鸿蒙开发 弹窗及加载中指示器HUD功能实现

最近在学习鸿蒙开发过程中,阅读了官方文档,在之前做flutter时候,经常使用overlay,使用OverlayEntry加入到overlayState来做添加悬浮按钮、提示弹窗、加载中指示器、加载失败的toast等功能。那在HarmonyOS鸿蒙开发中也可能有类似的功能需求。

HarmonyOS鸿蒙开发的使用弹窗文档中已经非常详细了
地址:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-use-dialog-V5

一、子窗口window

在弹出的loading指示器中,我们可以使用创建子window的方式,调用window的loadContentByName方法来实现。
实现步骤

效果预览

在这里插入图片描述

  • 1、实现加载中的loading组件,这里定义名字为LoadingHud

在LoadingHud中有LoadingProgress、Text提示文本,Text显示的信息由LocalStorage进行传递
需要传递的数据message,在aboutToAppear进行赋值

@Local message: string = '';aboutToAppear(): void {this.message = LocalStorage.getShared().get("message") ?? "";}

当然在调用window的loadContentByName时候,需要确定加载的主角的routeName,这就需要在LoadingHud组件中使用装饰器来设置

/// 通用的hud,弹出框,或者loading框
@Entry({ routeName: "hudLoading", storage: LocalStorage.getShared() })
@ComponentV2
export struct LoadingHud {... 其他代码
}

LoadingHud的完整代码如下:

/// 通用的hud,弹出框,或者loading框
@Entry({ routeName: "hudLoading", storage: LocalStorage.getShared() })
@ComponentV2
export struct LoadingHud {@Local message: string = '';aboutToAppear(): void {this.message = LocalStorage.getShared().get("message") ?? "";}build() {Column() {Column(){Row() {// 从左往右,1号环形进度条,默认前景色为蓝色渐变,默认strokeWidth进度条宽度为2.0vpLoadingProgress().color($r('app.color.success')).width(40).height(40)// messageText(this.message).fontSize(14).fontColor($r('app.color.dataset_empty_message')).margin({left: 10})}.padding({top: 15,bottom: 15,left: 15,right: 20}).justifyContent(FlexAlign.Center)Button("点击消失").width(100).height(40).fontSize(12).backgroundColor('#ef04792c').margin({top: 10}).onClick(()=> {LoadingHudUtil.dismissLoading();})}.justifyContent(FlexAlign.Center).constraintSize({minWidth: 200,minHeight: 150,}).backgroundColor($r('app.color.white')).borderRadius(10)}.justifyContent(FlexAlign.Center).width('100%').height('100%').backgroundColor('#00000000').hitTestBehavior(HitTestMode.Transparent)}
}
  • 2、创建子Window并显示

在创建LoadingHud后,我们需要创建创建子Window并显示window,显示我们的loadingHUD
创建window的createWindow,这里使用的windowType是window.WindowType.TYPE_DIALOG,也可以换成其他的试试看。

let windowName = "loading";// 创建窗口let subWindow = await window.createWindow({name: windowName,windowType: window.WindowType.TYPE_DIALOG,ctx: ctx,});

设置LocalStorage数据,存储message

//创建存储let storage = new LocalStorage();//存储数据storage.setOrCreate('message',  tip);

调用window的loadContentByName,设置Window的大小及背景颜色,显示Window

await subWindow.loadContentByName('hudLoading', storage);let dp = display.getDefaultDisplaySync();await subWindow.resize(dp.width, dp.height);subWindow.setWindowBackgroundColor('#30000000');await subWindow.showWindow();

显示后Window,在需要消失的时候调用destroyWindow

static async dismissLoading(): Promise<void> {if (LoadingHudUtil.cacheWindow) {await LoadingHudUtil.cacheWindow.destroyWindow();}}

完整的LoadingHudUtil的代码如下

import { display, window } from '@kit.ArkUI';
import { common } from '@kit.AbilityKit';
import('../components/hud/LoadingHud'); // 引入命名路由页面// 自定义弹出窗口
export class LoadingHudUtil {private static cacheWindow: window.Window;static async showLoading(tip: string): Promise<void> {let ctx = getContext() as common.UIAbilityContext;try {let windowName = "loading";// 创建窗口let subWindow = await window.createWindow({name: windowName,windowType: window.WindowType.TYPE_DIALOG,ctx: ctx,});LoadingHudUtil.cacheWindow = subWindow;//创建存储let storage = new LocalStorage();//存储数据storage.setOrCreate('message',  tip);console.log("LoadingHudUtil loadContentByName" + tip);// subWindow.setGestureBackEnabled(false);// subWindow.setDialogBackGestureEnabled(false);// subWindow.setWindowTouchable(true);await subWindow.loadContentByName('hudLoading', storage);let dp = display.getDefaultDisplaySync();await subWindow.resize(dp.width, dp.height);subWindow.setWindowBackgroundColor('#30000000');await subWindow.showWindow();} catch (e) {console.log("LoadingHudUtil showLoading e:" + JSON.stringify(e));}}static async dismissLoading(): Promise<void> {if (LoadingHudUtil.cacheWindow) {await LoadingHudUtil.cacheWindow.destroyWindow();}}
}

二、自定义Dialog

在HarmonyOS鸿蒙开发中,可以使用CustomDialogController来实现自定义的弹窗。

效果预览
在这里插入图片描述

  • 1.自定义弹窗组件CustomAlertDialog

在CustomAlertDialog中实现一个消息提示,并且点击按钮可以关闭dialog
代码如下:

@CustomDialog
export struct CustomAlertDialog {controller?: CustomDialogControllertitle?: stringbuild() {Column() {Column() {// messageText(this.title).fontSize(14).fontColor($r('app.color.dataset_empty_message')).margin({left: 10})Button("点击消失").width(100).height(40).fontSize(12).backgroundColor('#ef04792c').margin({top: 10}).onClick(() => {this.controller?.close();})}.justifyContent(FlexAlign.Center).constraintSize({minWidth: 200,minHeight: 100,}).backgroundColor($r('app.color.white')).borderRadius(10)}.justifyContent(FlexAlign.Center).width('100%').height('100%').backgroundColor(Color.Transparent).hitTestBehavior(HitTestMode.Transparent)}
}
  • 2.使用CustomDialogController来展示弹窗

定义CustomDialogController

// 自定义CustomDialogcustomDialogController: CustomDialogController | null = new CustomDialogController({builder: CustomAlertDialog({title: "温馨提示"}),alignment: DialogAlignment.Center,onWillDismiss: (dismissDialogAction: DismissDialogAction) => {console.info("reason=" + JSON.stringify(dismissDialogAction.reason))console.log("dialog onWillDismiss")if (dismissDialogAction.reason == DismissReason.PRESS_BACK) {dismissDialogAction.dismiss()}if (dismissDialogAction.reason == DismissReason.TOUCH_OUTSIDE) {dismissDialogAction.dismiss()}},autoCancel: true,customStyle: true,});

在需要展示弹窗的时候调用customDialogController的open方法。

 if (this.customDialogController != null) {this.customDialogController.open()}

当然如果页面消失,尽量在aboutToDisappear中将customDialogController置空

  // 在自定义组件即将销毁时将dialogController置空aboutToDisappear() {this.customDialogController = null // 将dialogController置空}

三、Overlay浮层

在官方文档中有一段描述
浮层(OverlayManager) 用于将自定义的UI内容展示在页面(Page)之上,在Dialog、Popup、Menu、BindSheet、BindContentCover和Toast等组件之下,展示的范围为当前窗口安全区内。可适用于常驻悬浮等场景。

使用OverlayManager来添加、删除、隐藏、显示节点Component

效果预览
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 1.定义CustomOverlayView组件界面

在CustomOverlayView中,我们定义了加载中,加载失败,加载成功的几种类型,用于展示不同的样式
定义OverlayConfig类为展示的界面配置、OverlayScaleImage缩放的icon

export enum OverlayType {loading,success,fail
}export class OverlayConfig {message: string = ""offset: Position = { x: 0, y: -50 }index: number = 0autoDismiss: boolean = true;duration: number = 3000 // 持续时间onCallback?: (index: number) => voidtype: OverlayType = OverlayType.loadingconstructor(message: string) {this.message = message}
}@Builder
export function builderCustomOverlayView(overlayConfig: OverlayConfig) {CustomOverlayView({olConfig: overlayConfig})
}@ComponentV2
struct OverlayScaleImage {@Param @Require src: PixelMap | ResourceStr | DrawableDescriptor;@Param imgWidth: number = 40;@Local imgScale: number = 0.0;build() {Image(this.src).width(this.imgWidth).aspectRatio(1).scale({ x: this.imgScale, y: this.imgScale }).animation({duration: 300, // 时长iterations: 1, // 设置-1表示动画无限循环}).onAppear(() => {// 组件挂载完毕,修改数值触发动画效果this.imgScale = 1.0})}
}@ComponentV2
export struct CustomOverlayView {@Param olConfig: OverlayConfig = new OverlayConfig("");aboutToAppear(): void {setTimeout(() => {console.log("CustomOverlayView aboutToAppear");if (this.olConfig.onCallback != null) {this.olConfig.onCallback(this.olConfig.index);}}, this.olConfig.duration);}build() {Column() {if (OverlayType.loading == this.olConfig.type) {// messageLoadingProgress().color($r('app.color.success')).width(40).height(40)} else if (OverlayType.success == this.olConfig.type) {// messageOverlayScaleImage({src: $r('app.media.ic_hud_success'),imgWidth: 40})} else if (OverlayType.fail == this.olConfig.type) {// messageOverlayScaleImage({src: $r('app.media.ic_hud_fail'),imgWidth: 30})}Text(this.olConfig.message).fontSize(14).fontColor($r('app.color.white')).margin({top: 10,})}.padding({top: 20,bottom: 20,left: 15,right: 15}).justifyContent(FlexAlign.Center).constraintSize({minWidth: 180,minHeight: 80,}).backgroundColor($r('app.color.overlay_bg_color')).borderRadius(10).offset(this.olConfig.offset)}
}
  • 2.CustomOverlayStorage

由于在OverlayManager来添加、删除、隐藏、显示节点过程中,需要使用index索引参数。这里使用一个类,类中有一个数组记录一下展示的节点Component

@ObservedV2
export class CustomOverlayStorage {@Trace contentArray: ComponentContent<OverlayConfig>[] = []
}
  • 3.自定义MyOverlayManager进行封装OverlayManager

首先确定属性uiContext,创建ComponentContent需要该参数,这个我在index.ets中进行初始化传入。
CustomOverlayStorage存储ComponentContent的数组,确定index
overlayManager用来来添加、删除、隐藏、显示节点

MyOverlayManager代码如下

/// 用于管理Overlay
/// 浮层(OverlayManager) 用于将自定义的UI内容展示在页面(Page)之上,
/// 在Dialog、Popup、Menu、BindSheet、BindContentCover和Toast等组件之下,
/// 展示的范围为当前窗口安全区内。可适用于常驻悬浮等场景。
/// 与OverlayManager相关的属性推荐采用AppStorage来进行应用全局存储,以免切换页面后属性值发生变化从而导致业务错误。
import { AppStorageV2, ComponentContent, OverlayManager, router } from '@kit.ArkUI';
import {builderCustomOverlayView,CustomOverlayStorage,OverlayConfig
} from '../common/components/hud/CustomOverlayView';export class MyOverlayManager {private static currentIndex: number = 0;private uiContext?: UIContextprivate overlayManager?: OverlayManagerprivate overlayStorage: CustomOverlayStorage =AppStorageV2.connect(CustomOverlayStorage, 'overlayStorage', () => new CustomOverlayStorage())!;private static instance: MyOverlayManager;public static getInstance(): MyOverlayManager {if (MyOverlayManager.instance == null) {MyOverlayManager.instance = new MyOverlayManager();}return MyOverlayManager.instance;}initOverlayNode(uiContext: UIContext): void {this.uiContext = uiContext;this.overlayManager = uiContext.getOverlayManager();}addOverlayView(overlayConfig: OverlayConfig): void {if (this.uiContext != null && this.uiContext != undefined) {// 设置索引下标let index = MyOverlayManager.currentIndex++;overlayConfig.index = index;// 创建componentContentlet componentContent = new ComponentContent(this.uiContext!, wrapBuilder<[OverlayConfig]>(builderCustomOverlayView),overlayConfig)this.overlayStorage.contentArray.push(componentContent);if (this.overlayManager != null && this.overlayManager != undefined) {this.overlayManager.addComponentContent(componentContent, index)}}}hideOverlayView(index: number) {if (this.overlayManager != null && this.overlayManager != undefined) {if (index < this.overlayStorage.contentArray.length) {this.overlayManager.hideComponentContent(this.overlayStorage.contentArray[index])}}}showOverlayView(index: number) {if (this.overlayManager != null && this.overlayManager != undefined) {if (index < this.overlayStorage.contentArray.length) {this.overlayManager.showComponentContent(this.overlayStorage.contentArray[index])}}}removeOverlayView(index: number) {if (this.overlayManager != null && this.overlayManager != undefined) {if (index < this.overlayStorage.contentArray.length) {this.overlayManager.removeComponentContent(this.overlayStorage.contentArray[index])}}}removeAllOverlayView() {if (this.overlayManager != null && this.overlayManager != undefined) {this.overlayManager.hideAllComponentContents();for (let index: number = 0; index < this.overlayStorage.contentArray.length; index++) {this.overlayManager.removeComponentContent(this.overlayStorage.contentArray[index])}}}
}
  • 4.index.ets传入uiContext

初始化配置uiContext

aboutToAppear(): void {console.log("aboutToAppear");MyOverlayManager.getInstance().initOverlayNode(this.getUIContext());}
  • 5.调用OverlayManager进行显示加载中、加载成功、加载失败提示

定义type及message

let config = new OverlayConfig(message);config.type = OverlayType.loading;config.onCallback = (index: number)=>{MyOverlayManager.getInstance().removeOverlayView(index)}MyOverlayManager.getInstance().addOverlayView(config);

加载中、加载成功、加载失败的Util

import { MyOverlayManager } from "../../manager/MyOverlayManager";
import { OverlayConfig, OverlayType } from "../components/hud/CustomOverlayView";export class EasyLoadingHud {static showLoading(message: string) {let config = new OverlayConfig(message);config.type = OverlayType.loading;config.onCallback = (index: number)=>{MyOverlayManager.getInstance().removeOverlayView(index)}MyOverlayManager.getInstance().addOverlayView(config);}static showSuccess(message: string) {let config = new OverlayConfig(message);config.type = OverlayType.success;config.onCallback = (index: number)=>{MyOverlayManager.getInstance().removeOverlayView(index)}MyOverlayManager.getInstance().addOverlayView(config);}static showFail(message: string) {let config = new OverlayConfig(message);config.type = OverlayType.fail;config.onCallback = (index: number)=>{MyOverlayManager.getInstance().removeOverlayView(index)}MyOverlayManager.getInstance().addOverlayView(config);}
}
  • 6.页面调用EasyLoadingHud进行显示

可以在页面需要的地方调用EasyLoadingHud进行显示

代码如下

// 加载中
EasyLoadingHud.showLoading("加载中...")
// 加载成功
EasyLoadingHud.showSuccess("加载成功")
// 加载失败
EasyLoadingHud.showFail("加载失败")

四、小结

在开发过程中会遇到提示弹窗、加载中指示器、加载失败的toast等功能,这里是学习HarmonyOS鸿蒙开发的学习记录,如果对你有用,你可以点个赞哦~~。详细的文档还是以官方文档为主。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/104.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于华为ENSP的OSPF状态机、工作过程、配置保姆级别详解(2)

本篇技术博文摘要 &#x1f31f; 基于华为enspOSPF状态机、OSPF工作过程、.OSPF基本配置等保姆级别具体详解步骤&#xff1b;精典图示举例说明、注意点及常见报错问题所对应的解决方法 引言 &#x1f4d8; 在这个快速发展的技术时代&#xff0c;与时俱进是每个IT人的必修课。我…

DeepSeek:性能强劲的开源模型

deepseek 全新系列模型 DeepSeek-V3 首个版本上线并同步开源。登录官网 chat.deepseek.com 即可与最新版 V3 模型对话。 性能对齐海外领军闭源模型​ DeepSeek-V3 为自研 MoE 模型&#xff0c;671B 参数&#xff0c;激活 37B&#xff0c;在 14.8T token 上进行了预训练。 论…

Elastic-Job相关

文档参考视频&#xff1a;09_SpringBoot案例演示_哔哩哔哩_bilibili 一、Elastic-Job介绍 Elastic-Job 是一个轻量级、分布式的任务调度框架&#xff0c;旨在解决分布式环境下的定时任务调度问题。 1.1. Elastic-Job 的核心组件 Elastic-Job 是由多个核心组件构成的&#x…

【Linux】文件 文件描述符fd

&#x1f33b;个人主页&#xff1a;路飞雪吖~ &#x1f320;专栏&#xff1a;Linux 目录 &#x1f33b;个人主页&#xff1a;路飞雪吖~ 一、C文件接口 &#x1f31f;写文件 &#x1f320;小贴士&#xff1a; &#x1f320;stdin && stdout && stderr Linux下…

Java Spring Boot实现基于URL + IP访问频率限制

点击下载《Java Spring Boot实现基于URL IP访问频率限制(源代码)》 1. 引言 在现代 Web 应用中&#xff0c;接口被恶意刷新或暴力请求是一种常见的攻击手段。为了保护系统资源&#xff0c;防止服务器过载或服务不可用&#xff0c;需要对接口的访问频率进行限制。本文将介绍如…

QML states和transitions的使用

一、介绍 1、states Qml states是指在Qml中定义的一组状态&#xff08;States&#xff09;&#xff0c;用于管理UI元素的状态转换和属性变化。每个状态都包含一组属性值的集合&#xff0c;并且可以在不同的状态间进行切换。 通过定义不同的状态&#xff0c;可以在不同的应用场…

SpringCloud

1.认识微服务 随着互联网行业的发展&#xff0c;对服务的要求也越来越高&#xff0c;服务架构也从单体架构逐渐演变为现在流行的微服务架构。这些架构之间有怎样的差别呢&#xff1f; 1.0.学习目标 了解微服务架构的优缺点 1.1.单体架构 单体架构&#xff1a;将业务的所有功…

DSP+Simulink——点亮LED灯(TMSDSP28379D)超详细

实现功能&#xff1a;DSP28379D-LED灯闪烁 :matlab为2019a :环境建立见之前文章 Matlab2019a安装C2000 Processors超详细过程 matlab官网链接&#xff1a; Getting Started with Embedded Coder Support Package for Texas Instruments C2000 Processors Overview of Creat…

java_将数据存入elasticsearch进行高效搜索

使用技术简介&#xff1a; (1) 使用Nginx实现反向代理&#xff0c;使前端可以调用多个微服务 (2) 使用nacos将多个服务管理关联起来 (3) 将数据存入elasticsearch进行高效搜索 (4) 使用消息队列rabbitmq进行消息的传递 (5) 使用 openfeign 进行多个服务之间的api调用 参…

最近在盘gitlab.0.先review了一下docker

# 正文 本猿所在产品的代码是保存到了一个本地gitlab实例上&#xff0c;实例是别的同事搭建的。最近又又又想了解一下&#xff0c;而且已经盘了一些了&#xff0c;所以写写记录一下。因为这个事儿没太多的进度压力&#xff0c;索性写到哪儿算哪儿&#xff0c;只要是新了解到的…

计算机网络(四)网络层

4.1、网络层概述 简介 网络层的主要任务是实现网络互连&#xff0c;进而实现数据包在各网络之间的传输 这些异构型网络N1~N7如果只是需要各自内部通信&#xff0c;他们只要实现各自的物理层和数据链路层即可 但是如果要将这些异构型网络互连起来&#xff0c;形成一个更大的互…

AI人工智能(2):机器学习

1 简介 机器学习&#xff08;Machine Learning&#xff09;是人工智能&#xff08;AI&#xff09;的一个分支&#xff0c;它使计算机系统能够利用数据和算法自动学习和改进其性能。机器学习是让机器通过经验&#xff08;数据&#xff09;来做决策和预测。机器学习已经广泛应用于…

Photon最新版本PUN 2.29 PREE,在无网的局域网下,无法连接自己搭建的本地服务器

1.图1为官方解答 2.就是加上这一段段代码&#xff1a;PhotonNetwork.NetworkingClient.SerializationProtocol SerializationProtocol.GpBinaryV16; 完美解决 unity 商店最新PUN 2 插件 不能连接 &#xff08;环境为&#xff1a;本地局域网 无外网情况 &#xff09; …

android 官网刷机和线刷

nexus、pixel可使用google官网线上刷机的方法。网址&#xff1a;https://flash.android.com/ 本文使用google线上刷机&#xff0c;将Android14 刷为Android12 以下是失败的线刷经历。 准备工作 下载升级包。https://developers.google.com/android/images?hlzh-cn 注意&…

Qt官方下载地址

1. 最新版本 Qt官方最新版本下载地址&#xff1a;https://www.qt.io/download-qt-installer 当前最新版本Qt6.8.* 如下图&#xff1a; 2. 历史版本 如果你要下载历史版本安装工具或者源码编译方式安装&#xff0c;请转至此链接进行下载&#xff1a;https://download.qt.i…

带格式 pdf 翻译

支持 openAI 接口&#xff0c;国内 deepseek 接口兼容 openAI 接口&#xff0c; deepseek api 又非常便宜 https://pdf2zh.com/ https://github.com/Byaidu/PDFMathTranslate

WebRTC 在视频联网平台中的应用:开启实时通信新篇章

在当今这个以数字化为显著特征的时代浪潮之下&#xff0c;实时通信已然稳稳扎根于人们生活与工作的方方面面&#xff0c;成为了其中不可或缺的关键一环。回首日常生活&#xff0c;远程办公场景中的视频会议让分散各地的团队成员能够跨越地理距离的鸿沟&#xff0c;齐聚一堂共商…

《ROS2 机器人开发 从入门道实践》 鱼香ROS2——第6章内容

第6章 建模与仿真-创建自己的机器人 6.1 机器人建模与仿真概述 6.2使用URDF创建机器人 6.2.1 帮机器人创建一个身体 1. 新建文件chapt6/chapt6_ws/src/fishbot_description/urdf/ 2. 新建文件first_robot.urdf <?xml version"1.0"?> <robot name &…

Postman接口测试03|执行接口测试、全局变量和环境变量、接口关联、动态参数、断言

目录 七、Postman 1、安装 2、postman的界面介绍 八、Postman执行接口测试 1、请求页签 3、响应页签 九、Postman的环境变量和全局变量 1、创建环境变量和全局变量可以解决的问题 2、postman中的操作-全局变量 1️⃣手动设置 2️⃣代码设置 3️⃣界面获取 4️⃣代…

【巨实用】Git客户端基本操作

本文主要分享Git的一些基本常规操作&#xff0c;手把手教你如何配置~ ● 一个文件夹中初始化Git git init ● 为了方便以后提交代码需要对git进行配置&#xff08;第一次使用或者需求变更的时候&#xff09;&#xff0c;告诉git未来是谁在提交代码 git config --global user.na…