2015-07-10 48 views
2

我已经设置了一个​​到我的DatePicker视图。 现在的问题是,我仍然可以选择我分配的最短日期之前的日期。DatePicker MinDate可选 - Android

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

见我仍然可以选择1这是不我分配的​​的范围(还有1 - 9不在范围内10 - 13在范围内)。除此之外的圆圈显示它可以选择。我想不能点击这些。此外,这是为什么我可以检索那些“未选择的日期 信息,我该如何解决这个问题?

回答

2

我有我的DatePicker所显示的对话框片段同样的问题。

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

我的解决方案并不完美,但将有助于防止超出范围从断码的日期,但仍然会选择:(

所以设定分钟日期和日期选择器最大日期。

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