文档开发者中心
我的
|

ArkUI (方舟UI框架)

HarmonyOS 5

异步操作中不显示设置了显示于应用之上的toast

已解决

1. 自定义了toast,设置了showMode: promptAction.ToastShowMode.TOP_MOST属性,使toast可以显示于应用之上;
2. 在异步操作中,调用toast,无法显示,去除showMode: promptAction.ToastShowMode.TOP_MOST可以正常显示。

收起
自动换行
深色代码主题
复制
// Index.ets
import { showToast } from './ComponentUtil';
import { bundleManager } from '@kit.AbilityKit'

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            this.getVersionInfo()
          })
      }
      .width('100%')
    }
    .height('100%')
  }

  private async getVersionInfo() {
    bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
      .then((bundleInfo) => {
       showToast(bundleInfo.versionName)
      }).catch((error: string) => {
      console.error("获取版本号异常:" + error)
    })
  }
}
收起
自动换行
深色代码主题
复制
// ComponentUtil.ets
import promptAction from '@ohos.promptAction';

/**
 * duration 显示时间3S
 * @param msg
 */
export function showToast(msg: string | Resource) {
  promptAction.showToast({
    message: msg,
    duration: 3000,
    bottom:"center",
    showMode: promptAction.ToastShowMode.TOP_MOST
  });
}

class ComponentUtil {
  getStringByResourceStr(context: Context, resourceStr: Resource) {
    return context.resourceManager.getStringSync(resourceStr).toString()
  }
}

let componentUti: ComponentUtil = new ComponentUtil()
export default componentUti as ComponentUtil
点赞
1
收藏
回复
1
分享
举报
浏览276 发布于2024-09-24 08:46广东
全部评论
最多点赞
最新发布
最早发布
|
采纳答复

promptAction模块功能依赖UI的执行上下文,不可在UI上下文不明确的地方使用。从API version 10开始,可以通过使用UIContext中的getPromptAction方法获取当前UI上下文关联的PromptAction对象。详细情况请查看:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-promptaction-V5#showtoastoptions 。针对此情况可更改代码:

收起
自动换行
深色代码主题
复制
//  index.ets
  private getVersionInfo() {
    bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
      .then((bundleInfo) => {
        let promptActionData = this.getUIContext().getPromptAction();
       showToast(promptActionData,bundleInfo.versionName)
      }).catch((error: string) => {
      console.error("获取版本号异常:" + error)
    })
  }
//ComponentUtil.ets
import promptAction from '@ohos.promptAction';
import { PromptAction } from '@kit.ArkUI';
/**

duration 显示时间3S
@param msg

 */
export function showToast(promptActionData: PromptAction,msg: string | Resource) {
  promptActionData.showToast({
    message: msg,
    duration: 3000,
    bottom:"center",
    showMode: promptAction.ToastShowMode.TOP_MOST
  });
}
展开全部
1楼回复于2024-09-24 12:17 来自广东
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要提问题

了解社区公约,与您携手共创和谐专业的开发者社区。