[FIXED] MaterialDatePicker get selected dates

Issue

I’m calling a MaterialDatePicker like this in Android:

MaterialDatePicker.Builder<Pair<Long, Long>> builder = MaterialDatePicker.Builder.dateRangePicker();

CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
builder.setCalendarConstraints(constraintsBuilder.build());

int dialogTheme = resolveOrThrow(getContext(), R.attr.materialCalendarTheme);
builder.setTheme(dialogTheme);

MaterialDatePicker<?> picker = builder.build();

picker.show(getFragmentManager(), picker.toString());

the library is:

dependencies {
    implementation 'com.google.android.material:material:1.2.0-alpha01'
}

How can I get the selected date of this calendar? I can’t find any listener like onDateSet or OnDateSetListener

Solution

Just use the addOnPositiveButtonClickListener listener called when the user confirms a valid selection:

For a single date picker:

picker.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Long>() {
      @Override public void onPositiveButtonClick(Long selection) {
        // Do something...
        //Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        //calendar.setTimeInMillis(selection);   

      }
    });

For a range date picker:

MaterialDatePicker<Pair<Long, Long>> pickerRange = builderRange.build();
pickerRange.show(....);

pickerRange.addOnPositiveButtonClickListener(new MaterialPickerOnPositiveButtonClickListener<Pair<Long, Long>>() {
  @Override public void onPositiveButtonClick(Pair<Long,Long> selection) {
       Long startDate = selection.first;
       Long endDate = selection.second;
       //Do something...
  }
});

Answered By – Gabriele Mariotti

Answer Checked By – David Marino (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published