MaterialDatePicker shows current date instead of needed

匆匆过客 提交于 2020-07-14 09:46:30

问题


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.

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.

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.


回答1:


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



来源:https://stackoverflow.com/questions/61661948/materialdatepicker-shows-current-date-instead-of-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!