Toast弹窗使用常见场景如下:
场景一:如何使用Toast弹窗并设置其显示层级最高?
场景二:如何自定义Toast弹窗的阴影效果?
场景三:如何自定义Toast弹窗显示时间?
场景四:设置Toast的背板颜色backgroundColor为指定颜色后,发现显示颜色不符合预期。
示例代码如下:
import { PromptAction, promptAction } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
export struct Index {
private uiContext: UIContext = this.getUIContext();
private promptAction: PromptAction = this.uiContext.getPromptAction();
build() {
Column({ space: 20 }) {
Button('场景一')
.fontSize(20)
.onClick(() => {
try {
this.promptAction.showToast({
message: 'I am TOP_MOST toast',
duration: 2000,
showMode: promptAction.ToastShowMode.TOP_MOST,
});
} catch (error) {
let message = (error as BusinessError).message;
let code = (error as BusinessError).code;
console.error(`scene1:showToast args error code is ${code}, message is ${message}`);
}
})
Button('场景二')
.fontSize(20)
.onClick(() => {
try {
this.promptAction.showToast({
message: 'I am shadow toast',
duration: 2000,
shadow: ShadowStyle.OUTER_FLOATING_MD,
});
} catch (error) {
let message = (error as BusinessError).message;
let code = (error as BusinessError).code;
console.error(`scene2:showToast args error code is ${code}, message is ${message}`);
}
})
Button('场景三')
.fontSize(20)
.onClick(() => {
try {
this.promptAction.showToast({
message: 'I am duration toast',
duration: 3000,
});
} catch (error) {
let message = (error as BusinessError).message;
let code = (error as BusinessError).code;
console.error(`scene3:showToast args error code is ${code}, message is ${message}`);
}
})
Button('场景四')
.fontSize(20)
.onClick(() => {
try {
this.promptAction.showToast({
message: 'I am color toast',
duration: 3000,
backgroundColor: Color.Gray,
backgroundBlurStyle:BlurStyle.NONE,
});
} catch (error) {
let message = (error as BusinessError).message;
let code = (error as BusinessError).code;
console.error(`scene4:showToast args error code is ${code}, message is ${message}`);
}
})
}
.height('100%')
.width('100%')
.justifyContent(FlexAlign.Center)
}
} Q:Toast弹窗无法显示的可能原因及排查方向有哪些?
A:主要排查方向包括:
Q:如何设置Toast弹窗的样式,包括圆角、宽高、字体大小、图片等?
A:Toast弹窗是一种固定样式的提示框,不支持自定义Toast弹窗的样式,可以使用自定义弹窗实现,参考通过自定义弹窗实现自定义样式的Toast。
Q:如何实现全局的Toast函数,并且可以显示和隐藏?
A:可以参考自定义一个全局调用的Toast函数组件。
Q:使用Toast弹窗时报错Error: Internal error. UI execution context not found.如何解决?
A:根据报错信息,初步推断是在调用promptAction.showToast接口时,识别到场景下UI实例缺失主动抛出的。请尝试绑定UI实例来调用接口,同时进行合理的try catch异常捕捉。