0

我已经为日期范围选择实现了这一点。

如何限制日期范围的限制。我希望用户从所选的开始日期最多选择 7 天。

在此处输入图像描述

在下面添加我的代码,

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

1 回答 1

1

该库提供的所有内置验证器都是静态的。
它并不完美,但您可以定义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)

在此处输入图像描述

于 2021-04-07T15:59:30.490 回答