Search code examples
androidkotlinandroid-datepickermaterial-components-android

MaterialDatePicker Select Date between 2 dates only


How to add a constraint to MaterialDatePicker to force user to select a date between only 2 dates?

val constraintBuilder = CalendarConstraints.Builder()
    val materialRangeBuilder = MaterialDatePicker.Builder.datePicker()
    materialRangeBuilder.setTitleText("Book Date")
    materialRangeBuilder.setCalendarConstraints(constraintBuilder.build())

    val materialRangePicker = materialRangeBuilder.build()

    materialRangePicker.addOnPositiveButtonClickListener {
        Timber.d("$it")
    }

    materialRangePicker.show(supportFragmentManager, "DATE_RANGE_PICKER")

Solution

  • You can use a DateValidator to restrict the selections.
    In particular you can use the built-in validators:

    • DateValidatorPointForward that enables dates from a given point forward
    • DateValidatorPointBackward that enables only dates before a given point.

    Something like:

    MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();
    
    CalendarConstraints.Builder constraintsBuilderRange = new CalendarConstraints.Builder();
    
    //....define min and max for example with LocalDateTime and ZonedDateTime or Calendar
    
    CalendarConstraints.DateValidator dateValidatorMin = DateValidatorPointForward.from(min.getTimeInMillis());
    CalendarConstraints.DateValidator dateValidatorMax = DateValidatorPointBackward.before(max.getTimeInMillis());
    
    ArrayList<CalendarConstraints.DateValidator> listValidators =
                new ArrayList<CalendarConstraints.DateValidator>();
    listValidators.add(dateValidatorMin);
    listValidators.add(dateValidatorMax);
    CalendarConstraints.DateValidator validators = CompositeDateValidator.allOf(listValidators);
    constraintsBuilderRange.setValidator(validators);
    
    builder.setCalendarConstraints(constraintsBuilderRange.build());
    
    MaterialDatePicker<Long> picker = builder.build();
    picker.show(getSupportFragmentManager(), picker.toString());
    

    enter image description here