Android code snippet - Custom datepicker dialog

from category Android

Introduction

The following article provides a quick introduction on using a custom dialog, especially a datepicker dialog in Android. The example provides a possible solution to exlude specific days from users selection, e.g. you can prevent the user to choose a date of a sunday.

Prerequisites

You need basic experience in Android development and you should be able to create a sample app project where you can paste and test the provided code. I recommend to use Android Studio though its still in an early stage but it works like a charm for me already.

Hands on

Define a layout for your custom dialog e.g. datepicker

Define custom layout with all UI elements, that you want to be included in your custom dialog. The following example provides a layout for a datepicker as shown in the screenshots above.

Create a datepicker dialog based on a custom layout

The following code builds a dialog based on the above defined layout and shows it. Further more the example contains the functionality to prevent the user from choosing a date before the 12.12.2010 or to choose a date on weekday sunday. This can be customized for any other desired use case.

@Priya: If you still have problems regarding the quoted line please post the error stack trace

comment written by
[Priya]
on
2014-03-08 10:46

Thanks for your code.. was searching since many days to display date picker on fragment.. using your code solved my problem...

comment written by
[Priya]
on
2014-03-08 10:27

Thanks for this example..
how to implement it on Fragment...
getting error at
Date choosenDateFromUI = formatter .parse(datePickerShowDialogButton.getText().toString());

comment written by
[alex]
on
2014-01-21 10:06

@nodate: I don't think this is possible with the standard control, you have to create your own custom control for this purpose.
@javaDroid: "datePickerButton" was wrong, i corrected it, thanks for the feedback!

comment written by
[nodate]
on
2013-12-29 20:47

This is working well, but how to hide day selection in this example? I need only month and year selections.

comment written by
[javaDroid]
on
2013-11-21 08:11

thanks . It was very usefull. but i didnt understand what "datePickerButton" is . could you tell what is this where was it initiated ?