鸿蒙(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()
  }
相关推荐
汉堡黄•᷄ࡇ•᷅29 分钟前
鸿蒙开发:案例集合List:ListItem拖拽(交换位置,过渡动画)(性能篇)
华为·harmonyos·鸿蒙·鸿蒙系统
500841 小时前
鸿蒙 Flutter 权限管理进阶:动态权限、权限组、兼容处理与用户引导
flutter·华为·架构·wpf·开源鸿蒙
HONG````1 小时前
鸿蒙应用动态文件读取全指南:从JSON、XML到文本文件的解析实战
华为·harmonyos
C雨后彩虹1 小时前
矩阵扩散问题
java·数据结构·算法·华为·面试
SunkingYang2 小时前
华为Mate 80系列全维度对比:从Mate 70到四版本差异解析
华为·手机·对比·80·mate·70
Mr_Hu4042 小时前
鸿蒙开发学习笔记-生命周期小记
笔记·学习·harmonyos·鸿蒙
汉堡黄2 小时前
鸿蒙开发:案例集合List:ListItem拖拽(交换位置,过渡动画)(性能篇)
harmonyos
500842 小时前
鸿蒙 Flutter 蓝牙与 IoT 开发进阶:BLE 设备连接、数据交互与设备管理
flutter·华为·electron·wpf·开源鸿蒙
kirk_wang3 小时前
Flutter 图表库 fl_chart 鸿蒙端适配实践
flutter·移动开发·跨平台·arkts·鸿蒙
食品一少年4 小时前
开源鸿蒙 PC · Termony 自验证环境搭建与外部 HNP 集成实践(DAY4-10)(2)
华为·harmonyos