As the accepted answers here rely on the custom implementation of com.wdullaer, I would like to propose another solution that I have just implemente using the standard MaterialDatePicker and a custom DateValidator:
// Create a custom date validator to only enable dates that are in the list
val customDateValidator = object: CalendarConstraints.DateValidator {
override fun describeContents(): Int { return 0 }
override fun writeToParcel(dest: Parcel?, flags: Int) { }
override fun isValid(date: Long): Boolean {
listOfPossibleDatesAsLong.forEach {
val itemDateTime = Calendar.getInstance()
itemDateTime.timeInMillis = it
val dateDateTime = Calendar.getInstance()
dateDateTime.timeInMillis = date
if(itemDateTime.get(Calendar.YEAR) == dateDateTime.get(Calendar.YEAR)
&& itemDateTime.get(Calendar.MONTH) == dateDateTime.get(Calendar.MONTH)
&& itemDateTime.get(Calendar.DAY_OF_MONTH) == dateDateTime.get(Calendar.DAY_OF_MONTH))
return true
}
return false
}
}
Additionally to other constraints in the CalendarConstraints, just set the customDateValidator now, this can also be used together with setStart(...) and setEnd(...)
// Build constraints.
val constraintsBuilder =
CalendarConstraints.Builder().apply {
// other constraints
setValidator(customDateValidator)
}
}
Then define the datePicker and show it
val datePicker =
MaterialDatePicker.Builder.datePicker()
.setTitleText("Select date")
.setSelection(MaterialDatePicker.todayInUtcMilliseconds())
.setCalendarConstraints(constraintsBuilder.build())
.build()
datePicker.addOnPositiveButtonClickListener {
// Respond to positive button click...
}
datePicker.show(parentFragmentManager, "tag")
I need to admit that I haven't understood if describeContents and writeToParcel not being implemented properly would have a negative impact on anything, maybe this could be discussed here. However, for my purposes this works perfectly.