Search This Blog

Wednesday 1 August 2012

Date picker in android

In android application development, picker and dialog has an important place. Today i am going to discuss how to create a simple date picker dialog and time picker dialog. All though i know i am very late to write about this basic concept, but i realize that even-though a lots of matter and article available on this but they lack in term of explanation. So here i go with my attempt.

We need two things here

1) Dialog picker (either date or time) Object

2) And call back so that we can capture date or time when user set date

We will set current date or time when picker will open first time using calender object. Creating Datepickerdialog object inside overridden method of activity ,oncreatedialog() is best way. It will handle the orientation change effectively and you will avoid window leak exception quite easily

Making a call back listener for Datepickerdialog 

      OnDateSetListener ondate = new OnDateSetListener() {  
           public void onDateSet(DatePicker view, int year, int monthOfYear,  
                     int dayOfMonth) {  
                Builder builder = new AlertDialog.Builder(DateAndTimePicker.this);  
                builder.setMessage("Selected date : " + year + "/"  
                          + (++monthOfYear) + "/" + dayOfMonth);  
                builder.setPositiveButton("OK", null);  

It will return the date when you will click select button of  Datepickerdialog. Now override onCreateDialog(int d) and return Datepickerdialog object

      protected Dialog onCreateDialog(int id) {  
           Calendar calendar = Calendar.getInstance();  
           switch (id) {  
           case 1:  
                DatePickerDialog datePicker = new DatePickerDialog(this, ondate,  
                          calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),  
                return datePicker;  
           return super.onCreateDialog(id);  

DatePicker in android
Date Picker View

Date Picker selected value
Selected date

Follow this link to download source   Download Source Code


No comments:

Post a Comment

Feedback always help in improvement. If you have any query suggestion feel free to comment and Keep visiting my blog to encourage me to blogging

Android News and source code