为 materialDatePicker 设置 180 天的日历约束

set calendar constraints of 180 days for materialDatePicker

我正在为 Android (Kotlin) 使用 MaterialDatePicker,并且需要确保开始日期和结束日期相隔不超过 180 天。我该如何编写约束条件?

您可以定义自定义 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;
    }

然后:

    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());