DatePicker MinDate是可选的 - Android

时间:2015-07-10 10:15:26

标签: java android android-datepicker

我在minDate()视图中设置了DatePicker。 现在的问题是我仍然可以选择我指定的最短日期之前的日期。

我的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" 

    />

要展示的图片:

enter image description here

请参阅我仍然可以选择不是我指定的minDate()范围的1(同样1 - 9不在范围内,10 - 13在范围内)。除此之外的圆圈显示它可选。我希望无法点击那些。此外,我可以从那些“未选择的日期”中检索信息 为什么这样,我该如何解决?

1 个答案:

答案 0 :(得分:2)

我的DatePicker出现了同样的问题,显示为对话框片段。

我注意到这只发生在棒棒糖上

我的解决方案并不完美,但有助于防止日期超出破坏代码的范围,但仍然可以选择:(

因此,请在日期选择器上设置最小日期和最长日期。

    if (mMinDate != null) {
        datePickerDialog.getDatePicker().setMinDate(mMinDate.getTime());
    }

    if (mMaxDate != null) {
        datePickerDialog.getDatePicker().setMaxDate(mMaxDate.getTime());
    }

然后在您的代码中,您从选择器中提取当前日期(在我的情况下,它是带有OK按钮的对话框)执行此检查

//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 */
                    }
相关问题