HarmonyOS应用开发-基础组件,弹窗原来是这样实现的。

系统自带弹窗

系统提供了告警弹窗、列表选择弹窗、日期/时间选择弹窗、文本滑动选择弹窗。也可以根据需求进行自定义弹窗。

警告弹窗

使用AlertDialog.show来显示警告弹窗:

  • 只有一个按钮的弹窗,使用confirm来进行设置按钮
  • 有两个按钮的弹窗,使用primaryButton、secondaryButton来进行设置按钮

示例代码:

Button('自带弹框(只有确定按钮)')
  .margin({ top: 10 })
  .onClick(() => {
    AlertDialog.show({
      title: '提示',
      message: '请检查您的配置信息是否正确',
      autoCancel: true,
      // 设置弹框在底部
      alignment: DialogAlignment.Bottom,
      // 设置弹框底部向上移动60
      offset: { dx: 0, dy: -60 },
      gridCount: 3,

      confirm: {
        value: '确定',
        action: () => {
          promptAction.showToast({ message: '确定' })
        }
      },

      // 点击遮障层关闭dialog时的回调。
      cancel: () => {
        promptAction.showToast({ message: '取消' })
      }
    })
  })


Button('自带弹框(有确定、取消按钮)')
  .margin({ top: 10 })
  .onClick(() => {
    AlertDialog.show({
      title: '提示',
      message: '确定要删除该信息吗?',
      autoCancel: false,
      alignment: DialogAlignment.Center,
      gridCount: 4,

      primaryButton: {
        value: '确定',
        action: () => {
          promptAction.showToast({ message: '确定' })
        }
      },
      secondaryButton: {
        value: '取消',
        action: () => {
          promptAction.showToast({ message: '取消' })
        }
      },
    })
  })

实现效果:
image.png

image.png

列表选择弹窗

使用ActionSheet来实现列表选择弹窗,设置sheets,构建列表选项,可在每个列表选项中设置监听事件

示例代码:

Button('列表选择弹框')
  .margin({ top: 10 })
  .onClick(() => {
    ActionSheet.show({
      title: '请选择',
      message: '选择你喜欢的水果',
      alignment: DialogAlignment.Bottom,
      offset: { dx: 0, dy: -10 },
  
      confirm: {
        value: 'Confirm button',
        action: () => {
          console.log('Get Alert Dialog handled')
        }
      },
      cancel: () => {
        console.log('actionSheet canceled')
      },

    // 构建列表选项,里边文字样式是否可以修改,待确定
    sheets: [
      {
        title: 'apples',
        action: () => {
          promptAction.showToast({ message: 'apples' })
          console.log('apples')
        }
      },
      {
        title: 'bananas',
        action: () => {
          promptAction.showToast({ message: 'bananas' })

          console.log('bananas')
        }
      },
      {
        title: 'pears',
        action: () => {
          promptAction.showToast({ message: 'pears' })
          console.log('pears')
        }
      }
    ]
  })
})																													

实现效果:
image.png

日期滑动选择器弹窗

使用DatePickerDialog实现日期滑动选择器弹窗,

  • selected指定默认显示的日期
  • lunar设置日期是否显示为农历
  • onAccept中监听事件

�示例代码:

// 定义选择日期为当前日期
selectedDate: Date = new Date()
...


Button('日期选择器')
    .margin({ top: 10 })
    .onClick(() => {
      DatePickerDialog.show({
        start: new Date("2000-1-1"),
        end: new Date("2100-12-31"),
        selected: this.selectedDate,
        // 日期是否显示为农历
        lunar: true,
        onAccept: (value: DatePickerResult) => {
          // 通过Date的setFullYear方法设置按下确定按钮时的日期,这样当弹窗再次弹出时显示选中的是上一次确定的日期
          this.selectedDate.setFullYear(value.year, value.month, value.day)
          console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))

          promptAction.showToast({ message: JSON.stringify(value) })
        },
        onCancel: () => {
          console.info("DatePickerDialog:onCancel()")
        },
        onChange: (value: DatePickerResult) => {
          console.info("DatePickerDialog:onChange()" + JSON.stringify(value))
        }
      })
    })

实现效果:
image.png

时间滑动选择器弹窗

使用TimePickerDialog实现时间滑动选择弹窗

  • useMilitaryTime设置是否24小时制
  • onAccept设置监听事件

示例代码:

// 定义选择时间为当前时间
selectTime: Date = new Date()


Button("时间选择器")
    .margin({ top: 10 })
    .onClick(() => {
      TimePickerDialog.show({
        selected: this.selectTime,
        // 是否需要24小时制
        useMilitaryTime: true,
        onAccept: (value: TimePickerResult) => {
          this.selectTime.setHours(value.hour, value.minute)
          console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))
          promptAction.showToast({ message: JSON.stringify(value) })
        },
        onCancel: () => {
          console.info("TimePickerDialog:onCancel()")
        },
        onChange: (value: TimePickerResult) => {
          console.info("TimePickerDialog:onChange()" + JSON.stringify(value))
        }
      })
    })

实现效果:
image.png

文本滑动选择器弹窗

使用TextPickerDialog实现文本滑动选择器弹窗

  • range,设置文本选择器的选择范围。
  • selected,选中的index
  • onAccept,设置监听事件

代码示例:


// 选中的
select: number = 2
// range,设置文本选择器的选择范围。
fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5']
  

Button("TextPickerDialog")
  .margin({ top: 10 })
  .onClick(() => {
    TextPickerDialog.show({
      // 设置文本选择器的选择范围。
      range: this.fruits,
      // 选中的
      selected: this.select,
      // 设置选择器中选项的高度。
      // defaultPickerItemHeight: 50,
      onAccept: (value: TextPickerResult) => {
        // 设置select为按下确定按钮时候的选中项index,这样当弹窗再次弹出时显示选中的是上一次确定的选项
        this.select = value.index
        console.info("TextPickerDialog:onAccept()" + JSON.stringify(value))

        promptAction.showToast({ message: JSON.stringify(value) })
      },
      onCancel: () => {
        console.info("TextPickerDialog:onCancel()")
      },
      onChange: (value: TextPickerResult) => {
        console.info("TextPickerDialog:onChange()" + JSON.stringify(value))
      }
    })
  })

实现效果:
image.png

自定义弹窗

自定义MyCustomDialog实现自定义弹框

  • 在MyCustomDialog上设置@CustomDialog
  • 在MyCustomDialog中设置弹窗中要显示的内容,设置Button事件
  • 在MyCustomDialog中设置变量CustomDialogController
  • 在页面中使用MyCustomDialog,设置CustomDialogController
import promptAction from '@ohos.promptAction';

@CustomDialog
struct MyCustomDialog {
  controller: CustomDialogController
  cancel: () => void
  confirm: () => void
  title: string = 'title'
  message: string = 'message'

  build() {
    Column() {
      Text(this.title)
        .fontSize(20)
        .width("90%")
        .margin({ top: 10 })

      Text(this.message)
        .fontSize(16)
        .width("90%")
        .margin({ top: 10, bottom: 10 })

      Divider().opacity(0.6).margin({ left: 5, right: 5 })

      Flex({ justifyContent: FlexAlign.SpaceAround }) {
        Row() {
          Button('取消')
            .backgroundColor(0xffffff).fontColor(Color.Black)
            .width('50%')
            .onClick(() => {
              this.controller.close()
              this.cancel()
            })


          Divider().vertical(true).height(22).opacity(0.6).margin({ left: 5, right: 5 })


          Button('确定')
            .width('50%')
            .backgroundColor(0xffffff).fontColor(Color.Black)
            .onClick(() => {
              this.controller.close();
              this.confirm()
            })
        }
      }.margin({ top: 5, bottom: 5 })
    }
  }
}


@Entry
@Component
struct MyDialogPage {
  
  dialogController: CustomDialogController = new CustomDialogController({
    builder: MyCustomDialog({
      cancel: this.onCancel,
      confirm: this.onAccept,
      title: '提示',
      message: 'hello world,wmding'
    }),
    // 可设置dialog的对齐方式,设定显示在底部或中间等,默认为底部显示
    alignment: DialogAlignment.Center,
    // 点击遮障层退出时的回调
    cancel: this.onExistApp,
    autoCancel: true,
  })

  // 在自定义组件即将析构销毁时将dialogController置空
  aboutToDisappear() {
    this.dialogController = undefined // 将dialogController置空
  }

  onExistApp() {
    promptAction.showToast({ message: '取消' })
  }

  onCancel() {
    promptAction.showToast({ message: '取消' })
  }

  onAccept() {
    promptAction.showToast({ message: '确定' })
  }

  build() {
    Column() {
      Button('弹框').onClick(() => {
        if (this.dialogController != undefined) {
          this.dialogController.open()
        }
      })
    }.width('100%')
  }
}

实现效果:
image.png

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-03-13 09:48:06       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-13 09:48:06       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-13 09:48:06       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-13 09:48:06       20 阅读

热门阅读

  1. 力扣每日练习3.12

    2024-03-13 09:48:06       18 阅读
  2. JVM垃圾收集器之CMS垃圾收集器和G1垃圾收集器

    2024-03-13 09:48:06       23 阅读
  3. git 工具常用命令

    2024-03-13 09:48:06       20 阅读
  4. 【Linux的shell原理 与 Linux权限】

    2024-03-13 09:48:06       18 阅读
  5. Git高级玩法:Rebase、Cherry-pick与Stash实战解析

    2024-03-13 09:48:06       18 阅读
  6. flask框架-03

    2024-03-13 09:48:06       17 阅读
  7. 使用Python检测贝叶斯网络的因果关系检测

    2024-03-13 09:48:06       17 阅读
  8. C++/CLI学习笔记3(快速打通c++与c#相互调用的桥梁)

    2024-03-13 09:48:06       16 阅读
  9. 【MySQL】范式

    2024-03-13 09:48:06       20 阅读
  10. SeaTunnel 2.3.4 Cluster in K8S

    2024-03-13 09:48:06       19 阅读
  11. Centos搭建Nacos集群

    2024-03-13 09:48:06       25 阅读
  12. 【力扣347前k个高频元素】

    2024-03-13 09:48:06       17 阅读
  13. jenkins

    2024-03-13 09:48:06       17 阅读