You are on page 1of 24

Android DatePicker

Recently I wrote a tutorial on android notifications and there we touched dialog


notifications. Androids date picker is a type of dialog. This tutorial is to explain how
to create a date picker dialog in android. This dialog will disable the background
activityuntil the user select the date and click done tab of the dialog shown.
!ollowing are the steps to create date picker"
#. $reating new pro%ect.
&. Designing the layout with datepicker icon.
'. (enerate code to display datepicker dialog.
#. $reating a new pro%ect.
)e have already seen this step *ultiple ti*es. Refer (et +ser Input in
Android tutorial to recollect those steps.
&. Designing the layout with datepicker icon.
,pen the x*l file for layout design fro* the path
workspace-(et+serInput-res-layout-activity.*ain.x*l.
/elect the (raphic layout tab.
Drag and drop the 0ditText fro* for* widgets and set properties of the right
panel.
)hile selecting the 0ditText1 choose the one appropriate for the date type. There are
several types of 0ditText for various input that are supposed to be entered by the
user. $ode will be like this1
20ditText
android"id3456id-editText#4
android"layout.width34wrap.content4
android"layout.height34wrap.content4
android"layout.alignParent7eft34true4
android"layout.alignParentTop34true4
android"layout.*argin7eft34&8dp4
android"layout.*arginTop349:dp4
android"e*s34#84
android"inputType34date4 ;
2re<uest!ocus -;
Drag and drop the I*age=utton field fro* the i*ages and *edia *enu.
)hen we try to place this i*agebutton1 the icon has to be selected to display for
i*agebutton. !or that we should save a datepicker icon into res.drawable folder.
And then1 we need to set properties nedded like on$lick1 Padding and so on. After
co*pleteting this step1 the code will look like as follows1
2I*age=utton
android"id3456id-i*age=utton#4
android"layout.width34wrap.content4
android"layout.height34wrap.content4
android"layout.align=otto*3456id-editText#4
android"layout.toRight,f3456id-editText#4
android"contentDescription345string-selectdate4
android"cropToPadding34true4
android"on$lick34selectDate4
android"src345drawable-ic.datepicker4 -;
!inally layout code will be like1
actvity.*ain.x*l
2Relative7ayout x*lns"android34http"--sche*as.android.co*-apk-res-android4
x*lns"tools34http"--sche*as.android.co*-tools4
android"layout.width34*atch.parent4
android"layout.height34*atch.parent4
android"on$lick34selectDate4 ;
20ditText
android"id3456id-editText#4
android"layout.width34wrap.content4
android"layout.height34wrap.content4
android"layout.alignParent7eft34true4
android"layout.alignParentTop34true4
android"layout.*argin7eft34&8dp4
android"layout.*arginTop349:dp4
android"e*s34#84
android"inputType34date4 ;
2re<uest!ocus -;
2-0ditText;
2I*age=utton
android"id3456id-i*age=utton#4
android"layout.width34wrap.content4
android"layout.height34wrap.content4
android"layout.align=otto*3456id-editText#4
android"layout.toRight,f3456id-editText#4
android"contentDescription345string-selectdate4
android"cropToPadding34true4
android"on$lick34selectDate4android"src345drawable-ic.datepicker4
-;2-Relative7ayout;
'. (enerate code to display date picker dialog
I*port the needed classes and then create the instance of !rag*entActivity.
+sually instance will be created for Activity class. =ut in this this application it is
created for !rag*entActivity. This helps our activity to create a frag*ent as a
popup on top of the layout.
$reating subclass which extends Dialog!rag*ent class and i*ple*ents
DatePickerDialog.,nDate/et7istener *ethod. This subclass includes *ethod to
display the datepicker frag*ent to the user. It also has the *ethod to handle the
event on setting the date.
5,verridepublic
Dialog on$reateDialog>=undle savedInstance/tate?
@
final $alendar calendar 3 $alendar.getInstance>?A
int yy 3 calendar.get>$alendar.B0AR?A
int ** 3 calendar.get>$alendar.C,DTE?A
int dd 3 calendar.get>$alendar.DAB.,!.C,DTE?A
return new DatePickerDialog>getActivity>?1 this1 yy1 **1 dd?AF
public void onDate/et>DatePicker view1 int yy1 int **1 int dd?
@populate/etDate>yy1 **6#1 dd?AF
The on$reateDialog>? *ethod creates a calendar ob%ect. +sing this ob%ect the
current day1 *onth and year that will be retrieved. This current instance will return
to the activity to display the date picker with the current date by default.
onDate/et>? *ethod calls the populate/etDate>? with the selected date para*eters.
This *ethod will update the 0ditText field with the following code.
public void populate/etDate>int year1 int *onth1 int day? @*0dit 3
>0ditText?findGiew=yId>R.id.editText#?A*0dit.setText>*onth64-46day64-46year?AF
The entire code is as shown below.
CainActivity.%ava
package co*.%avapapers.andoiddatepickerAi*port
co*.%avapapers.andoiddatepicker.RAi*port android.os.=undleAi*port
android.view.GiewAi*port android.widget.0ditTextAi*port
android.widget.DatePickerAi*port
android.support.vH.app.!rag*entActivityAi*port android.app.DialogA
i*port android.app.DatePickerDialogA
i*port android.support.vH.app.Dialog!rag*entA
i*port %ava.util.$alendarA
public class CainActivity extends !rag*entActivity @
0ditText *0ditA
5,verride
public void on$reate>=undle savedInstance/tate? @
super.on$reate>savedInstance/tate?A
set$ontentGiew>R.layout.activity.*ain?A
F
public void selectDate>Giew view? @
Dialog!rag*ent new!rag*ent 3 new /electDate!rag*ent>?A
new!rag*ent.show>get/upport!rag*entCanager>?1 4DatePicker4?A
F
public void populate/etDate>int year1 int *onth1 int day? @
*0dit 3 >0ditText?findGiew=yId>R.id.editText#?A
*0dit.setText>*onth64-46day64-46year?A
F
public class /electDate!rag*ent extends Dialog!rag*ent i*ple*ents
DatePickerDialog.,nDate/et7istener @
5,verride
public Dialog on$reateDialog>=undle savedInstance/tate? @
final $alendar calendar 3 $alendar.getInstance>?A
int yy 3 calendar.get>$alendar.B0AR?A
int ** 3 calendar.get>$alendar.C,DTE?A
int dd 3 calendar.get>$alendar.DAB.,!.C,DTE?A
return new DatePickerDialog>getActivity>?1 this1 yy1 **1 dd?A
F
public void onDate/et>DatePicker view1 int yy1 int **1 int dd? @
populate/etDate>yy1 **6#1 dd?A
F
F
F
Date Picker ,utput
Date Picker Dialog and Ti*e Picker Dialog in Android use to select a date and ti*e1
as it will bepopup when you needed. )hile Ti*e Picker and Date Picker widget
occupy *ore space on screen. Dialogs are best way to solve this issue.
Dialog box used to show so*e infor*ation or pro*pt user to do so*e kind of
action. In Android1 we have *any different dialog types. 0ach has special function
that *ost users should be so*ewhat fa*iliar with it. In Pulse I we will discuss below
dialog box in depth.
#. Dialog
&. Alert Dialog
'. Progress Dialog
H. Date Picker Dialog
9. Ti*e Picker Dialog

In this tutorial1 we will learn how to show Date Picker Dialog box and Ti*e Picker
Dialog =ox in Android Application. In this Application we will have si*ple screen
where we will have two text box >one for date and one for ti*e? and two buttons
>one for launching date picker and one for launching ti*e picker?. )hen user click
on button it will display respective dialog. )hen userselect date or ti*e1 it will be
visible on text box.
Date Picker Dialog
7ets first see how to launch Date Picker Dialog. )e will use DatePickerDialog class1
we will use 9 argu*ent constructor1 listed below"
#. $ontext 1 it will be application context
&. $allback function1 used when user select date
'. int for Bear1 which will be visible as selected Bear on calendar
H. int for Conth1 which will be visible as selected *onth on Date Picker Dialog
9. int for Day1 which will be visible as selected day on Date Picker Dialog.
8#
8&
8'
8H
89
8:
8I
8J
8K
#8
##
#&
#'
#H
#9
#:
#I
final $alendar c 3 $alendar.getInstance>?A
*Bear 3 c.get>$alendar.B0AR?A
*Conth 3 c.get>$alendar.C,DTE?A
*Day 3 c.get>$alendar.DAB.,!.C,DTE?A

DatePickerDialog dpd 3 new DatePickerDialog>this1
new DatePickerDialog.,nDate/et7istener>? @

5,verride
public void onDate/et>DatePicker view1 int year1
int *onth,fBear1 int day,fConth? @
txtDate.setText>day,fConth 6 4L4
6 >*onth,fBear 6 #? 6 4L4 6 year?A

F
F1 *Bear1 *Conth1 *Day?A
dpd.show>?A
Date Picker Dialog
Ti*e Picker Dialog
Dow lets see how to display Ti*e Picker Dialog in Android Application. )e will
useTi*ePickerDialog class1 we will use 9 argu*ent constructor1 listed below"
#. $ontext 1 it will be application context
&. $allback function1 used when user select date
'. int for Eour1 which will be visible as selected hour in Ti*e Picker Dialog
H. int for Cinutes1 which will be visible as selected *inutes in Ti*e Picker
Dialog
9. boolean value to set &H Eour for*at or not.
8#
8&
8'
8H
89
8:
8I
8J
8K
#8
Ti*ePickerDialog tpd 3 new Ti*ePickerDialog>this1
new Ti*ePickerDialog.,nTi*e/et7istener>? @

5,verride
public void onTi*e/et>Ti*ePicker view1 int hour,fDay1
int *inute? @
txtTi*e.setText>hour,fDay 6 4"4 6 *inute?A
F
F1 *Eour1 *Cinute1 false?A
tpd.show>?A

Time Picker Dialog
=elow is full source code with x*l file
$reate Dew Android Pro%ect
#. $reate a new pro%ect and fill the re<uired details !ile Dew Android
Pro%ect
&. Dow open *ain.x*l >res-layout? and create si*ple (+I with two textbox and
two button for date and ti*e picker dialog.
8#
8&
8'
8H
89
8:
8I
8J
8K
#8
2Mx*l version34#.84 encoding34utfLJ4M;
27inear7ayout x*lns"android34http"--sche*as.android.co*-apk-res-android4
android"orientation34vertical4 android"layout.width34fill.parent4
android"layout.height34fill.parent4;
2TextGiew android"text$olor34Nfff4 android"text/iOe34&8dp4
android"layout.height34wrap.content4 android"id3456id-textGiew#4
android"text34Pulse I De*o4 android"layout.width34wrap.content4
android"layout.gravity34center.horiOontal4 android"paddingTop34#8dp4
android"padding=otto*34#8dp4;2-TextGiew;
2TextGiew android"text$olor34Nfff4 android"text/iOe34&8dp4
##
#&
#'
#H
#9
#:
#I
#J
#K
&8
&#
&&
&'
&H
&9
&:
&I
&J
&K
'8
'#
'&
''
'H
'9
':
'I
android"layout.height34wrap.content4 android"id3456id-textGiew&4
android"text34Date and Ti*e Picker Dialog4
android"layout.width34wrap.content4
android"layout.gravity34center.horiOontal4 android"paddingTop349dp4
android"padding=otto*34&9dp4;2-TextGiew;
27inear7ayout android"layout.width34*atch.parent4
android"layout.height34wrap.content4
android"id3456id-linear7ayout#4;
20ditText android"layout.width34wrap.content4
android"layout.height34wrap.content4 android"layout.weight34#4
android"id3456id-txtDate4;
2re<uest!ocus;2-re<uest!ocus;
2-0ditText;
2=utton android"layout.height34wrap.content4
android"layout.weight3484 android"id3456id-btn$alendar4
android"text34$alendar4
android"layout.width34#88dp4;2-=utton;
2-7inear7ayout;
27inear7ayout android"layout.width34*atch.parent4
android"layout.height34wrap.content4
android"id3456id-linear7ayout#4;
20ditText android"layout.width34wrap.content4
android"layout.height34wrap.content4 android"layout.weight34#4
android"id3456id-txtTi*e4;
2re<uest!ocus;2-re<uest!ocus;
2-0ditText;
2=utton android"layout.height34wrap.content4
android"layout.weight3484 android"id3456id-btnTi*ePicker4
android"text34Ti*e Picker4 android"layout.width34#88dp4;2-=utton;
2-7inear7ayout;
2-7inear7ayout;
'. Dow lets put Date Picker Dialog box and Ti*e Picker Dialog box code
in Activity class. )hen user click on button1 it should display respective Dialog box .
8#
8&
8'
8H
89
8:
8I
8J
8K
#8
##
package co*.vrs.pulseI.datepickerdialogA

i*port %ava.util.$alendarA

i*port android.app.ActivityA
i*port android.app.DatePickerDialogA
i*port android.app.Ti*ePickerDialogA
i*port android.os.=undleA
i*port android.view.GiewA
i*port android.view.Giew.,n$lick7istenerA
i*port android.widget.=uttonA
#&
#'
#H
#9
#:
#I
#J
#K
&8
&#
&&
&'
&H
&9
&:
&I
&J
&K
'8
'#
'&
''
'H
'9
':
'I
'J
'K
H8
H#
H&
H'
HH
H9
H:
HI
HJ
HK
98
9#
9&
9'
9H
99
9:
9I
i*port android.widget.DatePickerA
i*port android.widget.0ditTextA
i*port android.widget.Ti*ePickerA

public class PulseIDatePickerDialogActivity extends Activity i*ple*ents
,n$lick7istener @

-- )idget (+I
=utton btn$alendar1 btnTi*ePickerA
0ditText txtDate1 txtTi*eA

-- Gariable for storing current date and ti*e
private int *Bear1 *Conth1 *Day1 *Eour1 *CinuteA

-PP $alled when the activity is first created. P-
5,verride
public void on$reate>=undle savedInstance/tate? @
super.on$reate>savedInstance/tate?A
set$ontentGiew>R.layout.*ain?A

btn$alendar 3 >=utton? findGiew=yId>R.id.btn$alendar?A
btnTi*ePicker 3 >=utton? findGiew=yId>R.id.btnTi*ePicker?A

txtDate 3 >0ditText? findGiew=yId>R.id.txtDate?A
txtTi*e 3 >0ditText? findGiew=yId>R.id.txtTi*e?A

btn$alendar.set,n$lick7istener>this?A
btnTi*ePicker.set,n$lick7istener>this?A
F

5,verride
public void on$lick>Giew v? @

if >v 33 btn$alendar? @

-- Process to get $urrent Date
final $alendar c 3 $alendar.getInstance>?A
*Bear 3 c.get>$alendar.B0AR?A
*Conth 3 c.get>$alendar.C,DTE?A
*Day 3 c.get>$alendar.DAB.,!.C,DTE?A

-- 7aunch Date Picker Dialog
DatePickerDialog dpd 3 new DatePickerDialog>this1
new DatePickerDialog.,nDate/et7istener>? @

5,verride
9J
9K
:8
:#
:&
:'
:H
:9
::
:I
:J
:K
I8
I#
I&
I'
IH
I9
I:
II
IJ
IK
J8
J#
J&
J'
JH
J9
J:
JI
JJ
JK
public void onDate/et>DatePicker view1 int year1
int *onth,fBear1 int day,fConth? @
-- Display /elected date in textbox
txtDate.setText>day,fConth 6 4L4
6 >*onth,fBear 6 #? 6 4L4 6 year?A

F
F1 *Bear1 *Conth1 *Day?A
dpd.show>?A
F
if >v 33 btnTi*ePicker? @

-- Process to get $urrent Ti*e
final $alendar c 3 $alendar.getInstance>?A
*Eour 3 c.get>$alendar.E,+R.,!.DAB?A
*Cinute 3 c.get>$alendar.CID+T0?A

-- 7aunch Ti*e Picker Dialog
Ti*ePickerDialog tpd 3 new Ti*ePickerDialog>this1
new Ti*ePickerDialog.,nTi*e/et7istener>? @

5,verride
public void onTi*e/et>Ti*ePicker view1 int hour,fDay1
int *inute? @
-- Display /elected ti*e in textbox
txtTi*e.setText>hour,fDay 6 4"4 6 *inute?A
F
F1 *Eour1 *Cinute1 false?A
tpd.show>?A
F
F
F
H. Dow lets execute application.
Date and Time Picker Screen Click on button to display respective dialog box.
Date Picker Dialog will be visible when you click on calendar button
Time Picker Dialog will be visible when you click on Time Button
Android Dotifications
In this tutorial we shall learn about different types of notifications in android.
!ollowing are the three types of android notifications1
#. Toast Dotification Q /hows *essage that fades away after a few seconds.
>=ackground type also?
&. /tatus Dotification Q /hows notification *essage and displayed till user
action. >=ackground type also?
'. Dialog Dotification Q $o*es out of an active Activity.
>=ackground type? Q is result of so*e background /ervice event that *ay not be
related to current activity. That is1 we can use this notification type in /ervice also1
added to Activity.
#. Toast Dotification
This type of notification will be used when there is no need of user interaction on
seeing this *essage. This *essage occupies a rectangular box which will fade in and
fade out after so*e ti*e. The siOe of the box depends on the *essage content.
!or exa*ple1 when user creates an event using calendar application it will notify the
user as R0vent $reatedS after the create action is co*pleted. Refer the i*age.
Toast notification is best suited for one way infor*ation to the use where we dont
expect any response. Toast *essage does not stop or disturb the current activity1 %ust
the *essage is shown in parallel.
0xa*ple for Android Toast Dotification
Toast notification can be created fro* an Activity or /ervice. Toast is the class to be
used as below1
$ontext app$ontext 3 getApplication$ontext>?A
Toast *ailCessage 3 Toast.*akeText>app$ontext1 R0*ail Received.S1 Toast.
70D(TE.7,D(?A
*ailCessage.set(ravity>(ravity.T,P1 81 8?A --optional
*ailCessage.show>?A
duration Q can be either 70D(TE./E,RT or 70D(TE.7,D(
set(ravity Q is used to position the *essage in screen. =y default it shows at
botto* centered. !irst para*eter is (ravity a constant identifying location in
container broadly like T,P T =,TT,C T 70!T U 1 second and third
para*eters are x1 yLoffset.
&. /tatus Dotification
/tatus notification is used to display rich notification infor*ation especially fro* a
>background? /ervice where user can interact. It will be shown as an icon with an
alert in the status bar. )hen the user pulls down the status bar1 the list of
notification will be in the notification window.
!or exa*ple when a /C/ *essage is received a *essage icon is shown in the status
bar. ,n pull down1 the list of unread *essages will be shown in the notification
window.
0xa*ple shown in i*age" ,n snooOing the alar*1 corresponding notification will be
will be sent to the status bar with notification icon. A ticker *essage will be shown
next to the icon for so*e ti*e. In the i*age the clock icon represents the notification
about the snooOe event and the ticker *essage is shown next to the clock icon.
#. $reate a si*ple notification with an icon alert. Alert can be a ticker text
*essage or sound or vibration or flashlight.
&. Associate notification *essage with details shown on *essage expansion to
activity-intent. Dotification *essage can be a list and it is identified using a
uni<ue identifier. 0xisting *essages can be updated too.
'. Register the notification *essage with notification *anager.
DotificationCanager is a syste* service that *anages all the notifications.
0xa*ple for Android /tatus Dotification
--part # Q notification icon alertint icon 3 R.drawable.notification.iconA
-- a ticker text *essage or sound or vibration or flashlight can be used for
alert$har/e<uence ticker 3 REiSA
long showAt 3 /yste*.currentti*eCillis>?A
--i**ediatelyDotification notification 3 new Dotification>icon1 ticker1 showAt?A
--part & Q associate notification *essage with details shown on *essage expansion to
activity-
intent$har/e<uence notificationTitle 3 4Dotification"4A
$har/e<uence notificationCessage 3 4/C/ Received.4A
Intent intent 3 new Intent>this1 Activity.class?A
PendingIntent ob%PendingIntent 3 PendingIntent.getActivity>this1 81 intent1 8?A
$ontext ctx 3 getApplication$ontext>?A
notification.set7atest0ventInfo>ctx1 notificationTitle1 notificationCessage1
ob%PendingIntent?A
--part ' Q register the notification *essage with notification *anagerprivate static
final int notificationIdentifier 3 #8#A
--an uni<ue nu*ber set by developer to identify a notification1 using this notification
can be updated-
replacedDotificationCanager notificationCanager 3
>DotificationCanager?get/yste*/ervice>$ontext.D,TI!I$ATI,D./0RGI$0?Anoti
ficationCanager.notify>notificationIdentifier1 ob%Dotification?A
Dotification Alerts
/ound"
notification.defaults T3 Dotification.D0!A+7T./,+DDA
--use the above default or set custo* valuse as below
notification.sound 3 +ri.parse>4file"---sdcard-notification-robo.da.*p'4?A
Gibration"
notification.defaults T3 Dotification.D0!A+7T.GI=RAT0A
--use the above default or set custo* valuse as below
longVW vibrate 3 @81&881#881&88FAnotification.vibrate 3 vibrateA
!lash 7ight"
notification.defaults T3 Dotification.D0!A+7T.7I(ET/A--use the above default or
set custo* valuse as below
notification.ledAR(= 3 8xffff8888A--red color
notification.led,nC/ 3 H88A
notification.led,ffC/ 3 988A
notification.flags T3 Dotification.!7A(./E,).7I(ET/A
'. Dialog Dotification
Dialog notification is not an exact type of notification. Dialog is co**on in window
based +Is. A s*all panel that appears on top of an active window and user will not
be able to do any other activity other than acting on the dialog. This is sa*e here
too. !ro* an android Activity a dialog will be launched and the Activity loses focus.
+ser should give input and work on the dialog. ,nce the user action is co*pleted
the dialog is closed. Dialog has *any uses and one a*ong the* is notification to
user.
!or exa*ple we can show a progress bar which is a notification to user. )e can ask
for confir*ation yes or no fro* user and this is a type of notification. !or all
these purposes dialog notification is used. There are *any types of dialogs available
such as1
AlertDialog
ProgressDialog
DatePickerDialog
Ti*ePickerDialog

You might also like