Search This Blog

Wednesday, 1 August 2012

Time Picker in android

In my previous post Date Picker in android, I discuss about how to create Date Picker now we will cover another important aspect Timepickerdialog in android. While developing android application we meet so many situation where we need to pick time. In time picker also, we have two important  steps to remember

1) Call back listener that will return Time in hour and minute 

2) And Time picker dialog object


Note - Always use overridden method onCreateDialog(int id) of activity to avoid window leak exception while changing orientation of activity

Making call back listener to Time picker Dialog


      OnTimeSetListener onTimeSetListener = new OnTimeSetListener() {  
           @Override  
           public void onTimeSet(TimePicker view, int hourOfDay, int minute) {  
                Builder builder = new AlertDialog.Builder(DateAndTimePicker.this);  
                builder.setMessage("Selected Time : " + hourOfDay + ":" + minute);  
                builder.setPositiveButton("OK", null);  
                builder.show();  
           }  
      };  

Now our time picker call back listener is ready now we just need to attach it with Time picker dialog object. In normal Time picker we do not have way to select AM and PM time for that i will post another article which include Time and date picker together

Create TimePickerDialog 

 @Override  
      protected Dialog onCreateDialog(int id) { 
           Calendar calendar = Calendar.getInstance();  
           switch (id) {  
            case 2:  
                TimePickerDialog timePicker = new TimePickerDialog(this,  
                          onTimeSetListener, calendar.get(Calendar.HOUR_OF_DAY),  
                          calendar.get(Calendar.MINUTE), false);  
                return timePicker;  
           }  
           return super.onCreateDialog(id);  
      }  
 }  

Now look at the screen shot what exactly this code will brings.........

Time Picker Dialog
Time Picker
 Download source from following link              DownLoad Source Code

Related Link on this blog

How to create a custom dialog ? , How to create a custom dialog and built in dialog of all type?

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