鸿蒙使用@CustomDialog自定义弹窗

253 阅读1分钟

有很多的时候,我们需要弹窗来实现我们的业务,比如说各种提示等待,这个时候鸿蒙的自定义弹窗就能省很多的事情了

在外部自定义弹窗

@Preview
@CustomDialog
@Component
export default  struct Confirm {
  // 必不可少的属性 用来控制这个结构的显示和隐藏的
  controller: CustomDialogController
  message: string = "确定要退出登录吗?"
  buttonList: ConfirmButton[] = [{
    text: '确定',
    fontSize: 14,
    fontColor: $r('app.color.text_secondary')
  }]
  build() {
    Row() {
      Column() {
        Row() {
          Text(this.message)
            .fontSize(16)
            .fontColor($r('app.color.text_primary'))
        }
        .width('100%')
        .height(88)
        .justifyContent(FlexAlign.Center)
        .border({
          color: $r('app.color.background_divider'),
          width: {
            bottom: 0.5
          }
        })
        Row() {
          ForEach(this.buttonList, (item: ConfirmButton, index: number) => {
            Text(item.text)
              .fontSize(item.fontSize || 16)
              .textAlign(TextAlign.Center)
              .fontColor(item.fontColor || $r('app.color.text_secondary'))
              .layoutWeight(1)
              .border({
                color: $r('app.color.background_divider'),
                width: {
                  right: this.buttonList.length > 1 && index !== this.buttonList.length - 1
                    ? 0.5: 0
                }
              })
              .height('100%')
              .onClick(async () => {
                if(item.action) {
                  await item.action()
                }
                this.controller.close()
              })
          })
        }
        .height(49)
        .width('100%')
      }
    }
    .width(278)
    .borderRadius(12)
    .backgroundColor($r('app.color.white'))
  }
}



class ConfirmButton {
  fontColor?: ResourceStr = ''
  fontSize?: number = 16
  text: string = ""
  action?: () => void = () => {}
}

主页面使用

首先要new一个CustomDialogController对象出来,在里面的builder里面添加外部自定义的Conform。

confirm: CustomDialogController = new CustomDialogController({
  builder: Confirm({
    message: '确定要退出登录吗?',
    buttonList: [{
      text: '取消'
    },{
      text: '确定',
      fontColor: $r('app.color.primary'),
      action: () => {
        this.logout()
      }
    }]
  }),
  customStyle: true,
  alignment: DialogAlignment.Center,
  autoCancel: false
})

最后在需要使用的地方使用控制器open就可以了

.onClick(()=>{
  this.confirm.open()
})

自定义的外部定义的弹窗里面已经有了close,我们无需再主窗口调用close

this.controller.close()

image.png