9

I have a activity that is popping up a android.app.DatePickerDialog.

DatePickerDialog dialog =  new DatePickerDialog(this, startDateSetListener, start_cal.get(Calendar.YEAR), start_cal.get(Calendar.MONTH), start_cal.get(Calendar.DATE));

I want to get at the DatePicker View from the DatePickerDialog so that I can set the min and max dates. The API reference says that there is a method getDatePicker and that has been there since API 1 but it is invalid, my ide doesn't like it.

DatePicker picker = dialog.getDatePicker();

"The method getDatePicker() is undefined for the type DatePickerDialog"

Any one know what API was the method created in or how I can get to the DatePicker to edit min/max dates?

I am using API 7, Platform 2.1.

stacybro
  • 115
  • 1
  • 5

2 Answers2

23

Despite that getter method only being available in Honeycomb and above (as dmon correctly pointed out), you can still fairly easily get access to the DatePicker object encapsulated by the DatePickerDialog using reflection. It'll look something like this:

DatePickerDialog dialog = ... // create dialog
Field mDatePickerField = dialog.getClass().getDeclaredField("mDatePicker");
mDatePickerField.setAccessible(true);
DatePicker mDatePickerInstance = (DatePicker) mDatePickerField.get(dialog);

From this point on, you have a reference to the internal DatePicker object and you should be able to change it to your own liking. Please do beware of any obvious typos, as I entered this directly into the browser.

MH.
  • 45,303
  • 10
  • 103
  • 116
  • 3
    Good answer. Unfortunately the get and set max on date picker are API 11 also... – stacybro May 09 '12 at 14:04
  • Bummer, I hadn't looked at those yet. Unfortunately, while browsing through the source of `DatePicker` for 2.1-update1, the min/max date logic is completely absent. I suppose you could create your own extension of `DatePicker` to deal with that, and inject it into the `DatePickerDialog` (or use a custom dialog), but it seems like an awful lot of work for something quite minor. – MH. May 09 '12 at 19:31
4

You misread, it's only available since API 11:

"public DatePicker getDatePicker () Since: API Level 11". Look closely.

dmon
  • 30,048
  • 8
  • 87
  • 96