0

How to restrict date picker from accepting current and future dates in android i am using google api...any idea..?

1 Answers1

3
  1. Since API level 11 there is a method for that:

    DatePicker.setMaxDate(long maxDate)
    
  2. If it has to work in previous versions, use this method:

    public void init(int year, int monthOfYear, int dayOfMonth, DatePicker.OnDateChangedListener onDateChangedListener)
    

You could pass your own OnDateChangedListener which "resets" invalid dates to the newest valid one:

DatePicker picker = ...
int year = ...
int monthOfYear = ...
int dayOfMonth = ...
picker.init(year, monthOfYear, dayOfMonth, new DatePicker.OnDateChangedListener() {

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        // check if current date is OK
        boolean dateOk = ...
        if (!dateOk) {
            // correct the date, but be sure the corrected date is OK
            // => otherwise you might get endless recursion
            year = ...
            monthOfYear = ...
            dayOfMonth = ...
            // update the date widget with the corrected date values
            view.updateDate(year, monthOfYear, dayOfMonth);
        }
    }
});
Markus Wörz
  • 736
  • 5
  • 4
  • I have a similar problem: I want to display a Dialog when the date is in the past. The problem is that the Dialog gets called two times : first, when the user enters a past date and second, when view.updateDate is invoked. I guess it triggers the call to the listener one more time since we are "changing" the date with this call. How can we get rid of this ? can we temporarily "clear" the listeners ? – kaffein Jun 22 '12 at 16:10