How to disable past dates in MaterialDatePicker?

十年热恋 提交于 2020-07-03 10:20:55

问题


 //Material Date Picker
private val calendar = Calendar.getInstance()
private val constraintsBuilder = CalendarConstraints.Builder().setStart(calendar.timeInMillis)
private val builder = MaterialDatePicker.Builder.datePicker()
private val picker = builder
    .setSelection(calendar.timeInMillis)
    .setInputMode(MaterialDatePicker.INPUT_MODE_CALENDAR)
    .setCalendarConstraints(constraintsBuilder.build())
    .build()

I am using above code to open calendar setSelection method select current date and setStart only works for current month So i am unable to select previous month dates but i can still select past dates of current month.

If any can help me out. Please let me know. Thanks.


回答1:


You can build your own DateValidator or you can just use the DateValidatorPointForward provided by the library.

Something like:

//Returns a DateValidator which enables days from {@code point}, in 
//UTC milliseconds, forward
CalendarConstraints.DateValidator dateValidator = DateValidatorPointForward.from(yourDate);
constraintsBuilder.setValidator(dateValidator);




回答2:


You need to create your own DateValidator for this. A date being enabled/disabled depends on whether DateValidator.isValid() returns true or false

@Parcelize
class FutureDateValidator : CalendarConstraints.DateValidator {
    override fun isValid(date: Long): Boolean {
        return date > System.currentTimeMillis()
    }
}

And then use this validator as:

CalendarConstraints.Builder()
    .setValidator(FutureDateValidator())
    .build()


来源:https://stackoverflow.com/questions/61388666/how-to-disable-past-dates-in-materialdatepicker

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