Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MaterialDatePicker shows current date instead of needed

Using MaterialDatePicker I want to show required date and give an opportunity to select another. But when a DatePicker appears it shows current date instead of specified.

I plug the library: implementation 'com.google.android.material:material:1.2.0-alpha06' (or 1.1.0).

Then override AppTheme in styles.xml:

<style name="AppTheme" parent="Theme.MaterialComponents.Light">

And now can show DatePicker.

val now = Calendar.getInstance()
now[Calendar.YEAR] = 2020
now[Calendar.MONTH] = 10
now[Calendar.DAY_OF_MONTH] = 1
val builder = MaterialDatePicker.Builder.datePicker()
builder.setSelection(now.timeInMillis)

val picker = builder.build()
fragmentManager?.let { picker.show(it, MaterialDatePicker::class.java.simpleName) }

This is a result. I want to show 1st November, but it shows 7th May.

enter image description here

UPDATE 1

As written in above link, we can use CalendarConstraints.Builder:

...
val constraintsBuilder = CalendarConstraints.Builder()
constraintsBuilder.setStart(now.timeInMillis)
constraintsBuilder.setEnd(now.timeInMillis)

val builder = MaterialDatePicker.Builder.datePicker()
builder.setCalendarConstraints(constraintsBuilder.build())
builder.setSelection(now.timeInMillis)
...

This will show required date, we can select another day, but we cannot scroll months.

enter image description here

UPDATE 2

I suppose this is a bug of a new Android DatePicker. So I have to select well-known library https://github.com/wdullaer/MaterialDateTimePicker. It selects a specified date right and doesn't require changing an original theme.

enter image description here

like image 887
CoolMind Avatar asked May 07 '20 15:05

CoolMind


1 Answers

You can set the month to which the picker opens with the method constraintsBuilder.setOpenAt(). The default value is the current month if within the bounds otherwise the earliest month within the bounds:

CalendarConstraints.Builder constraintsBuilder = new CalendarConstraints.Builder();

LocalDateTime local = LocalDateTime.of(2020, 11, 1, 0, 0);
long openAt= local.atZone(ZoneId.ofOffset("UTC", ZoneOffset.UTC)).toInstant().toEpochMilli();
//you can also use Calendar.getInstance()...
constraintsBuilder.setOpenAt(openAt);

builder.setCalendarConstraints(constraintsBuilder.build());

You can set a default selection (defaults to no selection) with:

builder.setSelection(....);

enter image description here

like image 56
Gabriele Mariotti Avatar answered Sep 22 '22 14:09

Gabriele Mariotti