2011-02-09 32 views
7

Tôi đang sử dụng DatePicket trong hoạt động của mình,Android DatePicker Date Limiting

Tôi muốn giới hạn ngày được người dùng chọn cho đến ngày hôm nay.

Họ không thể chọn ngày lớn hơn ngày thường.

cảm ơn bạn.

Trả lời

7

có bạn có thể làm điều đó rất easely xác nhận đây là dụ:

if(dateObj1.before(dateObj2) || dateObj1.equals(dateObj2)){ 
//the program runs normally 
} 
else{ 
       new AlertDialog.Builder(PM_Edit.this) 

       .setTitle("Wrong Data Input!") 

       .setMessage("The end Date must be Before the start Date, please insert new Date values") 

       .setNeutralButton("Ok", 

       new DialogInterface.OnClickListener() { 

       public void onClick(DialogInterface dialog, 

       int which) { 

       } 

       }).show(); 
      } 

Tín dụng cho: http://www.brighthub.com/mobile/google-android/articles/41545.aspx

3

Tôi chưa làm việc với DatePicker nhưng tài liệu không hiển thị bất kỳ phương pháp nào có thể hạn chế ngày tối đa Picker hiển thị, bạn vẫn có thể kiểm tra ngày trả về và có thể thông báo cho người dùng về tiêu chí xác thực.

+0

anh chàng sao tôi cố gắng để làm xác nhận bằng tay. –

0

Tôi đồng ý với Sheikh.

Có thể xem xét thực hiện xác thực vào ngày đã nhập và nếu không hợp lệ, hãy thông báo cho người dùng và khởi chạy lại DatePicker.

Ngoài ra, có thể là tiện ích con tùy chỉnh, nhưng tôi chưa thấy cách mặc định để thực hiện việc này.

5
DatePicker datePicker = (DatePicker)findViewById(R.id.new_date_picker); 


datePicker.init(year, month, day, new OnDateChangedListener() { 

    @Override 
    public void onDateChanged(DatePicker view, int year, int monthOfYear,int dayOfMonth) { 

     if(isDateAfter(view)){ 
      Calendar mCalendar = Calendar.getInstance(); 
      view.init(mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH), this); 
     } 
    } 


    private boolean isDateAfter(DatePicker tempView) { 
     Calendar mCalendar = Calendar.getInstance(); 
     Calendar tempCalendar = Calendar.getInstance(); 
     tempCalendar.set(tempView.getYear(), tempView.getMonth(), tempView.getDayOfMonth(), 0, 0, 0); 
     if(tempCalendar.after(mCalendar)) 
      return true; 
     else 
      return false; 
    } 
});