setMinDate(…) for DatePicker doesn't work when invoked a second time

丶灬走出姿态 提交于 2019-11-30 22:07:06

问题


I'm in a particular situation in which I have to alter the min and max date of DatePicker according to the selected element of a Spinner. Here's the chunk of code I'm using to switch min and max date.

private void switchCalculationMethod(int method) {
    calculationMethod = method;
    switch (method) {
        case METHOD_1:
            datePicker.setMinDate(new LocalDate().minusWeeks(42).getMillis());
            datePicker.setMaxDate(new LocalDate().plusDays(1).getMillis() - 1);
            break;
        case METHOD_2:
            datePicker.setMinDate(new LocalDate().minusWeeks(2).getMillis()); // This don't work!!
            datePicker.setMaxDate(new LocalDate().plusWeeks(40).getMillis()); // This works!!!
            break;
    }
    datePicker.init(today.getYear(), today.getMonthOfYear() - 1,
            today.getDayOfMonth(), this);
}

So, the DatePicker would get set up correctly the first time, problem occurs when I attempt to change the min date again (changing max date works). It would remain at the value I had set first. I'm thinking this is a bug. Am I doing something wrong here? Is there a workaround for this?.

PS : I'm using Joda time api.


回答1:


This happens because method setMinDate() has check

 if (mTempDate.get(Calendar.YEAR) == mMinDate.get(Calendar.YEAR)
                && mTempDate.get(Calendar.DAY_OF_YEAR) != mMinDate.get(Calendar.DAY_OF_YEAR){
            return;
 }

Simple workaround is to set min date with different year at first, for example

mPicker.setMinDate(0);

mPicker.setMinDate(new LocalDate().minusWeeks(2)
                                .toDateTimeAtStartOfDay().getMillis());

It works for me.




回答2:


As said above, you can bypass the check by calling those before actually changing the value:

setMinDate(0);
setMaxDate(Long.MAX_VALUE);

If you want to reset the minimum or maximum value to its default, you can use the following values:

setMinDate(-2208902400000L);  // Jan 1, 1900
setMaxDate(4102531200000L);  // Jan 1, 2100



回答3:


first update setMinDate to 0 after then setMinDate according to you dateobject

mPicker.setMinDate(0);

mPicker.setMinDate(datepickerObject.getTimeInMillis());




回答4:


mPicker.setMinDate(0);

doesn't work for me.

Try to reinitialize the picker.

mPicker = new DatePickerDialog(..)


来源:https://stackoverflow.com/questions/19616575/setmindate-for-datepicker-doesnt-work-when-invoked-a-second-time

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