HarmonyOS 怎么实现类似SnackBar的效果?

全局弹出顶层的View(可以自定义)并且不遮挡底层的UI操作交互

阅读 473
1 个回答

可以使用promptAction组件能力,promptAction.openCustomDialog()。同时设置promptAction.openCustomDialog({isModal: false})来取消浮窗蒙层,进行与浮窗外事件交互。

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-promptaction-V5\#showdialogoptions

import promptAction from '@ohos.promptAction'
let customDialogId: number = 0

@Builder
function customDialogBuilder() {
  Column() {
    Text('Custom dialog Message').fontSize(10)
    Row() {
      Button("确认").onClick(() => {
        promptAction.closeCustomDialog(customDialogId)
      })
      Blank().width(50)
      Button("取消").onClick(() => {
        promptAction.closeCustomDialog(customDialogId)
      })
    }
  }
}

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

  @Builder
  customDialogComponent() {
    customDialogBuilder()
  }

  build() {
    Row() {
      Column() {
        Button('xxxx').onClick(()=>{
          console.log('xxx')
        })
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            promptAction.openCustomDialog({
              builder: () => {
                this.customDialogComponent()
              },
              showInSubWindow: false,
              offset: { dx: 5, dy: 5 },
              backgroundColor: 0xd9ffffff,
              cornerRadius: 20,
              width: '80%',
              height: 200,
              isModal:false,
              borderWidth: 1,
              borderStyle: BorderStyle.Dashed, //使用borderStyle属性,需要和borderWidth属性一起使用
              borderColor: Color.Blue, //使用borderColor属性,需要和borderWidth属性一起使用
              shadow: ({
                radius: 20,
                color: Color.Grey,
                offsetX: 50,
                offsetY: 0
              }),
            }).then((dialogId: number) => {
              customDialogId = dialogId
            })
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进