In this post, we’re going to see how to provide a nice Android UI control for selecting the date using DatePickerDialog.
The dialog looks as follows:
It may be opened e.g. when clicking on a button in the app, as I used it in MoneyBack.
First of all, we will implement the dialog to be displayed within DialogFragment. Doing that our dialog will be able to be displayed as independent piece of UI on the top of any Activity.
The second requirement is to implement IOnDateSetListener interface (coming from Java/Android), which provides a callback on date selection action done by the user.
The DatePickerFragment meeting those two requirements may look as follows:
There are few crucial parts in above-listed class:
Line 1: as said before, the class derives from DialogFragment and implements IOnDateSetListener interface
Line 3: here we have public static readonly string TAG variable defined – it is used as a unique identifier of the Fragment; in some cases, Fragments can be displayed without any UI – in such case the only possibility to identify and get the Fragment is by using findFragmentByTag() method
Lines 5-10: define _dateSelectedHandler delegate which may be provided to the constructor of our DatePickerFragment with the method to be called-back when user selects a date
Lines 12-20: inheriting from DialogFragment allows us to override its lifecycle methods – one of them is Dialog OnCreateDialog(Bundle savedInstanceState), in which we actually create the Dialog-inheriting class – in our case – DatePickerDialog – with initially selected date (set to current date in the provided example)
Lines 22-26: implementing IOnDateSetListener interface requires to implement OnDateSet method, which is called when the user selects the date and clicks “OK” button;
NOTE: one of this method’s arguments is monthOfYear integer value, which contains month number expressed as values 0-11 (NOT 1-12) for compatibility with java.util.Calendar.MONTH
In MoneyBack application I’ve used DatePickerFragment on creating/modifying an event, when user needs to select its date:
As soon as the button is clicked, the following code executes:
As you can see, to DatePickerFragment‘s constructor I’m providing the delegate with a method to be called when the date is selected by the user (setting _selectedDate property with selected time and putting the date in short format as button’s Text).
In order to display a dialog, Show method is called, taking current FragmentManager and already mentioned per-Fragment-unique tag string, defined statically in DatePickerFragment class.
Today’s short post presented how to easily create a DialogFragment showing DatePickerDialog for date selection, which allows to provide any method to be called-back when the date is selected by the user.
I hope you’ll find it useful 😉