MaterialDatePicker not working on Android

Carina picture Carina · Sep 5, 2019 · Viewed 8.9k times · Source

I want to change the date picker of my project to the date picker provided by the Material Components for Android, but it is not working.

This is the code I've tried:

MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();

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

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

This is how it looked like:

first image

An this is how it should've looked like:

second image

Can anybody tell me what's missing?

Thanks

Answer

Gabriele Mariotti picture Gabriele Mariotti · Sep 5, 2019

With the Material Components for Android you can use the new MaterialDatePicker.

To work fine, in your app you have to use a Material Components Theme.
In this way you inherit the style and theme for the pickers.

To select a single date just use:

MaterialDatePicker.Builder<Long> builder = MaterialDatePicker.Builder.datePicker();
builder.setTitleText(R.string.your_text);
MaterialDatePicker<Long> picker = builder.build();
picker.show(getSupportFragmentManager(), picker.toString());

To select a range date you can use a DateRange Picker using:

MaterialDatePicker.Builder<Pair<Long, Long>> builder =
                    MaterialDatePicker.Builder.dateRangePicker();
CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();
builder.setCalendarConstraints(constraintsBuilder.build());
MaterialDatePicker<?> picker = builder.build();
picker.show(getSupportFragmentManager(), picker.toString());

enter image description here

Check the colors used in your theme.

These attributes define your style. You don't need to add them, they are provided by default with the Material Components theme.

<!-- Picker styles and themes. -->
<item name="materialCalendarStyle">@style/Widget.MaterialComponents.MaterialCalendar</item>
<item name="materialCalendarFullscreenTheme">@style/ThemeOverlay.MaterialComponents.MaterialCalendar.Fullscreen</item>
<item name="materialCalendarTheme">@style/ThemeOverlay.MaterialComponents.MaterialCalendar</item>

Based on these style, the colors used by the picker are:

HeaderLaoyout     -> background:colorPrimary, textColor:colorOnPrimary
HeaderSelection   -> background:colorPrimary, textColor:colorOnPrimary
ConfirmButtons    -> background:colorPrimary, textColor:colorOnPrimary
Buttons           -> background:colorPrimary, textColor:colorOnSurface
HeaderToggleButton->                          textColor:colorOnPrimary
Day               ->                          text:colorOnSurface  stroke:colorOnSurface
SelectedDay       -> background:colorPrimary, textColor:colorOnPrimary
RangeFillColor    -> background:colorPrimary