鸿蒙(HarmonyOS)自定义Dialog实现时间选择控件

一、操作环境

操作系统: Windows 11 专业版、IDE:DevEco Studio 3.1.1 Release、SDK:HarmonyOS 3.1.0(API 9)

二、效果图

三、代码

复制代码
SelectedDateDialog.ets文件
TypeScript 复制代码
/**
 * 时间选择
 */
@CustomDialog
export struct SelectedDateDialog {
  @State selectedDate: Date = new Date()
  private callback: (value: DatePickerResult) => void
  @State value: DatePickerResult = {
    year: new Date().getFullYear(),
    month: new Date().getMonth(),
    day: parseInt(new Date().getDate().toString().padStart(2, '0')) }
  controller: CustomDialogController//自定义dialog必须声明

  aboutToAppear() {
    console.log("时间选择Loading展示》》》》》")
  }

  build() {
    Column() {
      DatePicker({
        start: new Date('2014-1-1'), //起始时间
        end: new Date('2030-1-1'), //结束时间
        selected: this.selectedDate, //默认所选时间
      })
        .margin({ top: 20 })
        .lunar(false) //日期是否显示农历。 - true:展示农历。 - false:不展示农历。 默认值:false
        .onChange(value => {
          console.log("轮换结果:" + value)
          this.value = value
        })

      Blank()

      Button('确定').borderRadius('3').width('30%')
        .margin({ bottom: 20 })
        .onClick((event: ClickEvent) => {
          console.log("时间:" + this.value.year + this.value.month + this.value.day)
          this.callback?.(this.value)
          this.controller.close()
        })
    }
    .width('100%')
    .height('50%')
  }
}

在page中的调用方式:

TypeScript 复制代码
selectTimeDialog: CustomDialogController = new CustomDialogController({
    builder: SelectedDateDialog({ callback: (value) => {
      console.log("选择结果:" + value.year)
      this.changeTime = value.year + "-" + (value.month + 1) + "-" + value.day//月份从0开始,故需+1
    } }),
    cancel: this.closeDialog, //点击空白区域回调
    autoCancel: true,
    alignment: DialogAlignment.Bottom,
    offset: { dx: 0, dy: -20 },
    gridCount: 4,
    customStyle: false
  })

  closeDialog() {
    console.info('Click the callback in the blank area')
    this.selectTimeDialog.close()
  }

  openDialog() {
    //点击事件中直接调用
    this.selectTimeDialog.open()
  }
相关推荐
fruge19 小时前
提升 HarmonyOS 开发效率:DevEco Studio 6.0 热更新调试模式全指南
华为·harmonyos
2501_9197490319 小时前
鸿蒙:使用Image组件展示相册图片或rawfile图片
华为·harmonyos
2501_9197490319 小时前
鸿蒙:PersistenceV2页面间持久化存储数据
华为·harmonyos
yenggd21 小时前
QoS之拥塞管理两种配置方法
网络·华为
一尘之中1 天前
操作系统内核架构深度解析:从单内核、微内核到鸿蒙分布式设计
架构·harmonyos·ai写作
咕噜企业签名分发-淼淼1 天前
App防止恶意截屏功能的方法:iOS、Android和鸿蒙系统的实现方案
android·ios·harmonyos
安卓开发者1 天前
鸿蒙NEXT NearLink Kit入门指南:重新定义短距无线通信
华为·harmonyos
科技风向标1 天前
2025 随身 WiFi 行业报告:格行 WiFi6 技术下放百元市场,中兴华为机型竞争力分析;五款机型芯片方案 / 网速 / 质保深度横评
网络·科技·物联网·华为·随身wifi·格行
想不明白的过度思考者2 天前
鸿蒙系统:不止于“手机OS”的全场景智能操作系统
华为·智能手机·harmonyos
IT WorryFree2 天前
华为光模块命名规则
华为