鸿蒙(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()
  }
相关推荐
逢生博客9 小时前
Mac 搭建仓颉语言开发环境(Cangjie SDK)
macos·华为·鸿蒙
青柠_项目管理9 小时前
PMP证书持有者,在华为、腾讯一般能拿多少薪资?
华为·pmp
小强在此12 小时前
【基于开源鸿蒙(OpenHarmony)的智慧农业综合应用系统】
华为·开源·团队开发·智慧农业·harmonyos·开源鸿蒙
Reuuse14 小时前
【HCIA-Datacom】华为VRP系统
服务器·网络·华为
PlumCarefree16 小时前
基于鸿蒙API10的RTSP播放器(四:沉浸式播放窗口)
华为·harmonyos
中关村科金19 小时前
中关村科金推出得助音视频鸿蒙SDK,助力金融业务系统鸿蒙化提速
华为·音视频·harmonyos
繁依Fanyi20 小时前
828 华为云征文|华为 Flexus 云服务器部署 RustDesk Server,打造自己的远程桌面服务器
运维·服务器·开发语言·人工智能·pytorch·华为·华为云
小强在此1 天前
基于OpenHarmony(开源鸿蒙)的智慧医疗综合应用系统
华为·开源·团队开发·健康医疗·harmonyos·开源鸿蒙
奔跑的露西ly1 天前
【鸿蒙 HarmonyOS NEXT】popup弹窗
华为·harmonyos