2015-07-10 45 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 */ 
        } 
相關問題