【关键字】
promptAction / openCustomDialog / 全局 / 弹窗
【问题描述】
promptAction.openCustomDialog 应该如何弹出全局自定义弹窗?
【解决方案】
promptAction.openCustomDialog 全局弹窗参考代码如下:
一、新建3个工具类
1、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);
}
}
2、DialogUtils.ets
import { promptAction } from '@kit.ArkUI'
import { GlobalContext } from './GlobalContext'
@Builder
export function customDialogBuilder(content: String) {
Column() {
Text(`Tip: ${content} `).fontSize(20).height("30%")
Text('失败原因:失败原因失败原因失败原因失败原因失败原因失败原因失败原因!').fontSize(16).height("30%")
Row() {
Button("确认").onClick(() => {
promptAction.closeCustomDialog(getCustomDialogId())
})
Blank().width(50)
Button("取消").onClick(() => {
promptAction.closeCustomDialog(getCustomDialogId())
})
}
.margin({ top: 30 })
}.height(200).padding(5)
}
function getCustomDialogId() {
// 取customDialogId
let customDialogId = GlobalContext.getContext().getObject('customDialogId') as number
return customDialogId;
}
3、HttpUtil.ets
import { GlobalContext } from './GlobalContext';
import { promptAction } from '@kit.ArkUI';
import { customDialogBuilder } from './DialogUtils';
export function testPromptDialog() {
// 方法调用后使用弹窗
// 使用GlobalContext中UIContext
const that = GlobalContext.getContext().getObject('UIContext') as UIContext;
if (that) {
promptAction.openCustomDialog({
builder: customDialogBuilder.bind(that, "网络请求失败!")
}).then((dialogId: number) => {
GlobalContext.getContext().setObject('customDialogId', dialogId)
})
}
}
二、页面测试弹窗效果
1、Index.ets
import { GlobalContext } from '../utils/GlobalContext'
import { router } from '@kit.ArkUI'
@Entry
@Component
struct Index {
aboutToAppear(): void {
// 存入UIContext与customDialogId
GlobalContext.getContext().setObject('UIContext', this)
GlobalContext.getContext().setObject('customDialogId', 0)
}
build() {
Row() {
Column() {
Button("跳转其他页面")
.onClick(() => {
router.pushUrl({ url: "pages/Page2" })
})
}
.width('100%')
}
.height('100%')
}
}
2、Page2.ets
import { testPromptDialog } from '../utils/HttpUtil';
@Entry
@Component
struct Page2 {
@State message: string = 'Hello World';
build() {
Row() {
Column() {
Button("promptAction弹窗")
.onClick(() => {
testPromptDialog()
})
}
.width('100%')
}
.height('100%')
}
}