Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set calendar constraints of 180 days for materialDatePicker

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?

like image 323
ish herr Avatar asked Jul 30 '20 07:07

ish herr


1 Answers

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

enter image description here

like image 127
Gabriele Mariotti Avatar answered Oct 16 '22 19:10

Gabriele Mariotti