Search code examples
javaandroidandroid-custom-viewandroid-calendarandroid-datepicker

Android custom calendar / date picker


This is what the new default DatePickerDialog widget looks like as it appears from Android 5.0 onward:

enter image description here

This is not much liked by my project managers. What they want is the "old style" Holo date picker as it used to be before Marshmallow & Lollipop. Something like this:

enter image description here

I have two options before me:

  • Use an existing calendar widget developed by somebody else that has the same look and feel as above.
  • Create my own calendar widget with complete calendar functionality.

If I am to create my own widget, then creating the UI is simple enough. My question is, how do I write the business logic for such a calendar, i.e. how do I back it with real data ? How do I account for leap years, and the number of days in different months ? Most importantly, I need the three NumberPickers to be in sync when it comes to the min and max range. It should NOT be possible to scroll beyond the min and max limits. This is the problem I haven't been able to solve.

Here's what I've done so far:

  • I've used the NumberPicker widget inside a DialogFragment, and I've used setMinValue() and setMaxValue() to set the range of each NumberPicker.
  • When a year changes (say from 2011 to 2012), I calculate the number of days in the current month by using

       cal = new GregorianCalendar(y, m, d);
       daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    

    as described here.

  • When a user scrolls from December to January or January to December, I programmatically scroll the year picker to increment or decrement respectively as described here.
  • The pickers for day, month and year are prevented from scrolling beyond their minimum and maximum values by using setWrapSelectorWheel().

So my question is, is there a pre-existing widget such as this one that I can use ? Alternatively, is there a way to back the NumberPickers with real calendar data, and have them scroll in sync within the min and max date range ? Please guide me. All answers will be appreciated.

EDIT:

While the given answer works, it is worth noting that there is an even better way: wrapping a DatePicker in a DialogFragment.


Solution

  • You can use the API Date Picker and tell it to use the Holo Design using this constructor: DatePickerDialog (Context, int, DatePickerDialog.OnDateSetListener, int, int, int)

    See the comments on this question: DatePicker crash in samsung with android 5.0

    You may have to tweak the theme a bit.

    Here is how we use this in action: https://github.com/dmfs/opentasks/blob/master/src/org/dmfs/tasks/widget/TimeFieldEditor.java#L437