我已经为我的 DatePicker
View 设置了一个 minDate()
。
现在的问题是我仍然可以从指定的最短日期之前的日期中进行选择。
我的java:
long thirtyDaysInMilliseconds = 2592000000l;
datePicker.setMinDate(System.currentTimeMillis() - thirtyDaysInMilliseconds); // Setting the minimum date
我的 XML:
<DatePicker
android:id="@+id/date_picker_id"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_below="@id/header_id"
/>
还有一张图片来演示:
看到我仍然可以选择不在我指定的 minDate()
范围内的 1(而且 1 - 9 不在范围内,10 - 13 在范围内)。旁边的圆圈表明它是可选的。我不想点击那些。我也可以从那些“未选择的日期”中检索信息
这是为什么?我该如何解决它?
最佳答案
我的 DatePicker 也有同样的问题,它显示为对话框 fragment 。
我注意到这只发生在 Lollipop 上
我的解决方案并不完美,但有助于防止超出范围的日期破坏代码,但仍然可以选择:(
因此,请在日期选择器上设置最短日期和最长日期。
if (mMinDate != null) {
datePickerDialog.getDatePicker().setMinDate(mMinDate.getTime());
}
if (mMaxDate != null) {
datePickerDialog.getDatePicker().setMaxDate(mMaxDate.getTime());
}
然后在您从选择器中提取当前日期的代码中(在我的例子中,它是带有“确定”按钮的对话框)执行此检查
//Just getting the current date from the date picker
int day = ((DatePickerDialog) dialog).getDatePicker().getDayOfMonth();
int month = ((DatePickerDialog) dialog).getDatePicker().getMonth();
int year = ((DatePickerDialog) dialog).getDatePicker().getYear();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
Date date = calendar.getTime(); //This is what we use to compare with.
/** Only do this check on lollipop because the native picker has a bug where the min and max dates are ignored */
if (Build.VERSION.SDK_INT >= 21) {
boolean isDateValid = true; //Start as OK but as we go through our checks this may become false
if(mMinDate != null){
//Check if date is earlier than min
if(date.before(mMinDate)){
isDateValid = false;
}
}
if(mMaxDate != null){
//Check if date is later than max
if(date.after(mMaxDate)){
isDateValid = false;
}
}
if(isDateValid){ //if true we can use date, if false do nothing but you can add some else code
/** ALL GOOD DATE APPLY CODE GOES HERE */
}
}else{ //We are not on lollipop so no need for this check
/** ALL GOOD DATE APPLY CODE GOES HERE */
}
关于java - DatePicker MinDate 可选择 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31338258/