Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
864 views
in Technique[技术] by (71.8m points)

android - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...