在 Material 日期范围选择器 Android 中最多选择 7 天

Limit to max 7 days selection in Material date range picker Android

我已经为 selection 的日期范围实施了 this

如何限制日期范围的限制。我希望用户 select 从开始日期起最多 7 天 selected.

在下面添加我的代码,

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

库提供的所有内置验证器都是静态的。
它并不完美,但您可以定义自定义 Validator,例如:

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;
    }
}

然后:

    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)