I have implemented this for date range selection.
How do I restrict the limit of the date range. I want the user to select max of seven days from the start date selected.
Adding my code below,
private fun showDateRangePicker() {
val constraintsBuilder = CalendarConstraints.Builder()
val validators: ArrayList<CalendarConstraints.DateValidator> = ArrayList()
validators.add(DateValidatorPointBackward.before(MaterialDatePicker.todayInUtcMilliseconds()))
validators.add(DateValidatorWeekdays())
constraintsBuilder.setValidator(CompositeDateValidator.allOf(validators))
val dateRangePicker =
MaterialDatePicker.Builder.dateRangePicker()
.setTitleText("Select dates")
.setTheme(R.style.MaterialCalendarTheme)
.setSelection(Pair(MaterialDatePicker.todayInUtcMilliseconds(), MaterialDatePicker.todayInUtcMilliseconds()))
.setCalendarConstraints(constraintsBuilder.build())
.build()
dateRangePicker.show(supportFragmentManager, dateRangePicker.toString())
}
All the built-in validators provided by the library are static.
It is not perfect but you can define a custom Validator
like:
public class RangeDateValidator implements CalendarConstraints.DateValidator {
private MaterialDatePicker rangePicker;
final int numberOfDays;
public RangeDateValidator (int numberOfDays){
this.numberOfDays = numberOfDays;
}
public void setDatePicker(MaterialDatePicker rangePicker) {
this.rangePicker = rangePicker;
}
@Override
public boolean isValid(long date) {
Pair<Long, Long> selection =(Pair<Long, Long>) rangePicker . getSelection ();
if (selection != null) {
Long startDate = selection . first;
if (startDate != null) {
long days =(numberOfDays - 1) * TimeUnit.DAYS.toMillis(1);;
if (date > startDate + days)
return false;
if (date < startDate)
return false;
}
}
return true;
}
}
and then:
val dateRangePickerBuilder =
MaterialDatePicker.Builder.dateRangePicker()
val constraintsBuilderRange = CalendarConstraints.Builder()
val dateValidator = RangeDateValidator(7) //number of days
constraintsBuilderRange.setValidator(dateValidator)
dateRangePickerBuilder.setCalendarConstraints(constraintsBuilderRange.build())
val datePicker = dateRangePickerBuilder.build()
dateValidator.setDatePicker(datePicker)
datePicker.show(supportFragmentManager, datePicker.tag)