MaterialDatePicker显示当前日期,而不是需要的日期 [英] MaterialDatePicker shows current date instead of needed
问题描述
使用 MaterialDatePicker 我想显示所需的日期并有机会选择另一个.但是,当出现DatePicker时,它将显示当前日期,而不是指定的日期.
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.
我插入了库:implementation 'com.google.android.material:material:1.2.0-alpha06'
(或1.1.0).
I plug the library: implementation 'com.google.android.material:material:1.2.0-alpha06'
(or 1.1.0).
然后在styles.xml
中覆盖AppTheme
:
<style name="AppTheme" parent="Theme.MaterialComponents.Light">
现在可以显示DatePicker.
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) }
这是结果.我想显示11月1日,但是显示5月7日.
This is a result. I want to show 1st November, but it shows 7th May.
更新1
如上面链接中所述,我们可以使用CalendarConstraints.Builder
:
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.
更新2
我想这是一个新的Android DatePicker的错误.因此,我必须选择著名的库 https://github.com/wdullaer/MaterialDateTimePicker .它会选择一个指定的日期,而无需更改原始主题.
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.
推荐答案
您可以使用方法 constraintsBuilder.setOpenAt()
设置选择器打开的月份.
如果在界限内,则默认值为当前月份,否则在界限内为最早的月份:
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(....);
这篇关于MaterialDatePicker显示当前日期,而不是需要的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!