场景一:创建并显示全局自定义弹窗
方案
可以使用openCustomDialog接口, 创建并弹出dialogContent对应的自定义弹窗,使用Promise异步回调。
创建Params类方便开发者进行传参的,开发者可以在@Builder里自定义组件的内容,宽度跟随子节点自适应,圆角为0,弹窗背景色为透明色;
let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message))
上述代码中uiContext代表上下文,wrapBuilder(buildText)代表自定义节点,new Params(this.message)代表传参。
核心代码
import { BusinessError } from '@ohos.base';
import { ComponentContent } from "@ohos.arkui.node";
class Params {
text: string = ""
constructor(text: string) {
this.text = text;
}
}//传参
@Builder
function buildText(params: Params) {
Row(){
Column() {
Text(params.text)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.margin({bottom: 36})
}.backgroundColor('#FFF0F0F0')
}
.height("100%")
} //自定义组件的内容
@Entry
@Component
struct Index {
@State message: string = "显示TOAST"
build() {
Row() {
Column() {
Button("click me")
.onClick(() => {
let uiContext = this.getUIContext();
let promptAction = uiContext.getPromptAction();
let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));//上下文、自定义节点、传参
try {
promptAction.openCustomDialog(contentNode);
} catch (error) {
let message = (error as BusinessError).message;
let code = (error as BusinessError).code;
console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
};
})
}
.width('100%')
.height('100%')
}
.height('100%')
}
}
import { BusinessError } from '@ohos.base';
import { ComponentContent } from "@ohos.arkui.node";
class Params {
text: string = ""
constructor(text: string) {
this.text = text;
}
}//传参
@Builder
function buildText(params: Params) {
Row(){
Column() {
Text(params.text)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.margin({bottom: 36})
}.backgroundColor('#FFF0F0F0')
}
.height("100%")
} //自定义组件的内容
@Entry
@Component
struct Index {
@State message: string = "显示TOAST"
build() {
Row() {
Column() {
Button("click me")
.onClick(() => {
let uiContext = this.getUIContext();
let promptAction = uiContext.getPromptAction();
let contentNode = new ComponentContent(uiContext, wrapBuilder(buildText), new Params(this.message));//上下文、自定义节点、传参
try {
promptAction.openCustomDialog(contentNode);
} catch (error) {
let message = (error as BusinessError).message;
let code = (error as BusinessError).code;
console.error(`OpenCustomDialog args error code is ${code}, message is ${message}`);
};
})
}
.width('100%')
.height('100%')
}
.height('100%')
}
}
场景二:全局弹窗拦截返回并监听返回事件
方案
onWillDismiss Callback,当用户执行点击遮障层关闭、左滑/右滑、三键back、键盘ESC关闭交互操作时,如果注册该回调函数,则不会立刻关闭弹窗。在回调函数中可以通过reason得到阻拦关闭弹窗的操作类型,从而根据原因选择是否能关闭弹窗。
名称 | 描述 |
---|---|
PRESS_BACK | 点击三键back、左滑/右滑、键盘ESC。 |
TOUCH_OUTSIDE | 点击遮障层时。 |
CLOSE_BUTTON | 点击关闭 |