简单的封装下Material组件里的日期选择器和时间选择器的使用方法
效果
代码
需要添加Material组件库的依赖(不过后面新版本Android Studio创建的新项目都会有此依赖了…)
implementation 'com.google.android.material:material:1.4.0'
private fun showTimeDialog(startDate: Date? = null) {
val builder = MaterialTimePicker.Builder()
//设置时间格式为24小时制
builder.setTimeFormat(TimeFormat.CLOCK_24H)
startDate?.let {
builder.setHour(it.hours)
builder.setMinute(it.minutes)
}
val timePicker = builder.build()
timePicker.apply {
// 设置事件监听器(当用户选择日期时触发)
addOnPositiveButtonClickListener {
val hour = timePicker.hour
val mintue = timePicker.minute
val hourStr = if (hour>9) hour.toString() else "0$hour"
val mintueStr = if (mintue>9) hour.toString() else "0$mintue"
val timeStrText = "$hourStr:$mintueStr"
//todo 选择时间后的操作
}
}
timePicker.show(supportFragmentManager, "DATE_PICKER_TAG")
}
private fun showDateDialog(startDate: Date? = null) {
// 创建 Material 日历选择器实例
val builder = MaterialDatePicker.Builder.datePicker()
//设置默认选择数据
startDate?.let {
builder.setSelection(it.time)
}
// 构建 Material 日历选择器
val materialDatePicker = builder.build()
materialDatePicker.apply {
// 设置事件监听器(当用户选择日期时触发)
addOnPositiveButtonClickListener {
val date = Date(it)
//todo 选择时间后的操作
}
}
materialDatePicker.show(supportFragmentManager, "DATE_PICKER_TAG")
}
评论区