I am trying to set the min and max date of the date picker in Android to before API level 11. I used the following code:
mDatePickerField = startDatePickerDialog.getClass().getDeclaredField("mDatePicker");
mDatePickerField.setAccessible(true);
DatePicker startDatePickerInstance =(DatePicker)mDatePickerField.get(startDatePickerDialog);
startDatePickerInstance.init(mYearMin, mMonthMin, mDayMin, new DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker datePicker, int i, int i1, int i2) {
Date maxDate = new Date(mYearMax, mMonthMax, mDayMax, 0, 0, 0);
Date selectedDate = new Date(i, i1, i2, 0, 0, 0);
if (selectedDate.after(maxDate)) {
datePicker.updateDate(mYearMax, mMonthMax, mDayMax);
}
}
}
However, the updateDate
method fires onDateChanged
again and the date picker is not updated.
Can anyone help to solve the problem?
Edit your DatePicker.java adding the following 3 code excerpts.
Declare the variables used for limiting the minimum and maximum date.
After the constructors, your have to override onDateChanged method.
And now, create setter methods for the minimum and maximum dates.
Second part, in the activity you call the DatePicker dialog, you need to set the minimum and maximum desired dates. The code below sets the current date as minimum and two years in the future as the maximum date.
}
note: you need pass the listener custom datepickerdialog to update the date after select in datepicker dialog
Just Use Value(Min & Max) Comes From Calender to set DatePiker.MaxDate & DatePiker.MinDate try some thing like :
You can set range with init datePicker method. Example with min value :
Based on @yostyle's answer, I've made a method which sets the minimum and maximum date for an DatePicker. My DatePicker was used inside an AlertDialog because I needed some extra customizations, but this method can be used directly on any DatePickerDialog or for any custom DatePicker's:
Keep in mind that this method should be called after DatePicker was initialized, like this:
You can't. The way I dealt with this was by using an if statement for the DatePicker:
I ended up doing nothing for the TimePicker.
What's the good news?
SimonVT has backported both the DatePicker and TimePicker, so that you can enjoy the latest functionality on earlier API levels: