Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Using a Timepicker Widget

In Chapter: GUI Alerts: Menus, Dialogs, Toasts and Notifications
Author: Pratik Rupwal ('prupwal')
Published? true
FormatLanguage: WikiFormat


Sometimes we need to ask the user to enter the time for processing some element in the application. Accepting time in Text boxes is not graceful as well as requires validation.


Timepicker widget can be used for accepting time from the user. It makes the appearance graceful and reduces the requirement of validation.


Below code explains how to show the current time on the screen and gives a button, clicking on which produces the timepicker widget to the user for accepting the time.

public class Main extends Activity 

private TextView mTimeDisplay;
private Button mPickTime;

private int mHour;
private int mMinute;

static final int TIME_DIALOG_ID = 0;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) 
        // capture our View elements
        mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
        mPickTime = (Button) findViewById(R.id.pickTime);

        // add a click listener to the button
        mPickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

        // get the current time
        final Calendar c = Calendar.getInstance();
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);

        // display the current date

    // The below overridden method gets invoked when 'showDialog()' is called inside 'onClick()' method defined 
      // for handling the click event of button 'change the time' 

    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this,
                    mTimeSetListener, mHour, mMinute, false);
        return null;
 // updates the time we display in the TextView
    private void updateDisplay() {
            new StringBuilder()
 // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
     public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
        private static String pad(int c) 
            if (c >= 10)
                return String.valueOf(c);
                return "0" + String.valueOf(c);

The below screenshot shows the timepicker appearing on the screen after clicking on 'change the time' button.