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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…