I am using MaterialDatePicker
for Android (Kotlin) and need to ensure that the start and end date is no more than 180 days apart. How do I write the constraints for this?
You can define a custom DateValidator
:
public class RangeDateValidator implements CalendarConstraints.DateValidator {
private MaterialDatePicker rangePicker;
private 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:
MaterialDatePicker.Builder<Pair<Long, Long>> builder =
MaterialDatePicker.Builder.dateRangePicker();
CalendarConstraints.Builder constraintsBuilderRange = new CalendarConstraints.Builder();
RangeDateValidator dateValidator = new RangeDateValidator(10);
constraintsBuilderRange.setValidator(dateValidator);
builder.setCalendarConstraints(constraintsBuilderRange.build());
MaterialDatePicker<Pair<Long, Long>> datePicker= builder.build();
dateValidator.setDatePicker(datePicker);
datePicker.show(getSupportFragmentManager(),datePicker.getTag());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With