HarmonyOS 鸿蒙Next中如何实现全局公用Loading弹框
HarmonyOS 鸿蒙Next中如何实现全局公用Loading弹框 如何实现全局公用Loading弹框
2、新建GlobalContext.ets工具类
export class GlobalContext {
private constructor() {}
private static instance: GlobalContext;
private _objects = new Map<string, Object>();
public static getContext(): GlobalContext {
if (!GlobalContext.instance) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
getObject(value: string): Object | undefined {
return this._objects.get(value);
}
setObject(key: string, objectClass: Object): void {
this._objects.set(key, objectClass);
}
}
3、新建DialogUtils.ets工具类
import { promptAction } from '@kit.ArkUI'
import { GlobalContext } from './GlobalContext'
let customDialogId: number = 0
//关闭弹窗写法:promptAction.closeCustomDialog(customDialogId)
@Builder
export function customDialogBuilder(content: string) {
Column() {
LoadingProgress()
.color(Color.Blue)
.width(80).height(80)
Text(content)
.fontSize(16)
.fontColor(Color.Blue)
}
.height(200).padding(5)
.justifyContent(FlexAlign.Center)
}
export function testPromptDialog() {
const that = GlobalContext.getContext().getObject('UIContext') as UIContext;
if (that) {
promptAction.openCustomDialog({
builder: customDialogBuilder.bind(that, "努力加载中..")
}).then((dialogId: number) => {
customDialogId = dialogId;
})
}
}
更多关于HarmonyOS 鸿蒙Next中如何实现全局公用Loading弹框的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS(鸿蒙Next)中,实现全局公用Loading弹框可以通过以下步骤完成:
-
自定义Loading组件:首先,创建一个自定义的Loading组件。可以使用
CommonDialog
或CustomDialog
来设计弹框的UI,包含加载动画和提示文本。 -
全局状态管理:使用
AbilityContext
或AppStorage
来管理Loading的显示与隐藏状态。通过全局状态管理,可以在应用的任何地方控制Loading弹框的显示。 -
封装全局方法:封装一个全局方法,用于显示和隐藏Loading弹框。这个方法可以放在一个全局工具类中,方便在应用的任何地方调用。
-
调用全局方法:在需要显示Loading弹框的地方,调用封装好的全局方法即可显示或隐藏Loading弹框。
示例代码:
// 自定义Loading组件
@CustomDialog
struct LoadingDialog {
@State message: string = '加载中...'
build() {
Column() {
ProgressBar()
Text(this.message)
}
}
}
// 全局工具类
class LoadingUtils {
static showLoading(message: string = '加载中...') {
// 显示Loading弹框
}
static hideLoading() {
// 隐藏Loading弹框
}
}
// 在需要的地方调用
LoadingUtils.showLoading('正在加载数据...')
// 数据加载完成后
LoadingUtils.hideLoading()
通过以上步骤,可以在HarmonyOS中实现全局公用的Loading弹框。
在HarmonyOS Next中实现全局公用Loading弹框,可以通过自定义Component
并结合@State
状态管理来实现。首先,创建一个LoadingComponent
,使用@State
控制显示状态。然后,通过@Provide
和@Consume
在全局范围内共享该组件。最后,在需要的地方调用showLoading
和hideLoading
方法控制弹框的显示与隐藏。示例代码如下:
@Entry
@Component
struct Index {
@State private showLoading: boolean = false;
build() {
Column() {
Button('Show Loading').onClick(() => {
this.showLoading = true;
})
Button('Hide Loading').onClick(() => {
this.showLoading = false;
})
if (this.showLoading) {
LoadingComponent()
}
}
}
}
@Component
struct LoadingComponent {
build() {
Text('Loading...').fontSize(20)
}
}
通过这种方式,可以在应用的不同页面中轻松控制Loading弹框的显示与隐藏。