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

一、操作环境

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

二、效果图

三、代码

SelectedDateDialog.ets文件
/**
 * 时间选择
 */
@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中的调用方式:

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()
  }

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值