给未来的读者!
实际上,使用新的android 材料设计组件可以使用MaterialDatePicker
. 超出允许范围的日期是不可选择的。
脚步
1. 将材料依赖添加到模块的 gradle 文件中
implementation 'com.google.android.material:material:1.1.0-beta01'
2.更改应用主题以继承材料主题的版本。
前任:
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
3. 使用以下代码启动对话框。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setupRangePickerDialog()
}
private fun setupRangePickerDialog() {
val builderRange = MaterialDatePicker.Builder.dateRangePicker()
builderRange.setCalendarConstraints(limitRange().build())
val pickerRange = builderRange.build()
pickerRange.show(supportFragmentManager, pickerRange.toString())
}
/*
Limit selectable range to Oct 17 - Nov 20 2019
*/
private fun limitRange(): CalendarConstraints.Builder {
val constraintsBuilderRange = CalendarConstraints.Builder()
val calendarStart: Calendar = GregorianCalendar.getInstance()
val calendarEnd: Calendar = GregorianCalendar.getInstance()
val year = 2019
calendarStart.set(year, 10, 17)
calendarEnd.set(year, 11, 20)
val minDate = calendarStart.timeInMillis
val maxDate = calendarEnd.timeInMillis
constraintsBuilderRange.setStart(minDate)
constraintsBuilderRange.setEnd(maxDate)
constraintsBuilderRange.setValidator(RangeValidator(minDate, maxDate))
return constraintsBuilderRange
}
}
class RangeValidator(private val minDate:Long, private val maxDate:Long) : CalendarConstraints.DateValidator{
constructor(parcel: Parcel) : this(
parcel.readLong(),
parcel.readLong()
)
override fun writeToParcel(dest: Parcel?, flags: Int) {
TODO("not implemented")
}
override fun describeContents(): Int {
TODO("not implemented")
}
override fun isValid(date: Long): Boolean {
return !(minDate > date || maxDate < date)
}
companion object CREATOR : Parcelable.Creator<RangeValidator> {
override fun createFromParcel(parcel: Parcel): RangeValidator {
return RangeValidator(parcel)
}
override fun newArray(size: Int): Array<RangeValidator?> {
return arrayOfNulls(size)
}
}
}