page.title=Time Picker parent.title=Hello, Views parent.link=index.html @jd:body

To provide a widget for selecting a time, use the {@link android.widget.TimePicker} widget, which allows the user to select the hour and minute in a familiar interface.

In this tutorial, you'll create a {@link android.app.TimePickerDialog}, which presents the time picker in a floating dialog box at the press of a button. When the time is set by the user, a {@link android.widget.TextView} will update with the new date.

  1. Start a new project named HelloTimePicker.
  2. Open the res/layout/main.xml file and insert the following:
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView android:id="@+id/timeDisplay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""/>
        <Button android:id="@+id/pickTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Change the time"/>
    </LinearLayout>
    

    This is a basic {@link android.widget.LinearLayout} with a {@link android.widget.TextView} that will display the time and a {@link android.widget.Button} that will open the {@link android.app.TimePickerDialog}.

  3. Open HelloTimePicker.java and insert the following class members:
        private TextView mTimeDisplay;
        private Button mPickTime;
    
        private int mHour;
        private int mMinute;
    
        static final int TIME_DIALOG_ID = 0;
    

    This declares variables for the layout elements and time fields. The TIME_DIALOG_ID is a static integer that uniquely identifies the dialog.

  4. Now insert the following code for the {@link android.app.Activity#onCreate(Bundle) onCreate()} method:
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            // 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) {
                    showDialog(TIME_DIALOG_ID);
                }
            });
    
            // 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
            updateDisplay();
        }
    

    First, the content is set to the main.xml layout and then the {@link android.widget.TextView} and {@link android.widget.Button} are captured with {@link android.app.Activity#findViewById(int)}. Then an {@link android.view.View.OnClickListener} is created for the {@link android.widget.Button}, so that when clicked, it will call {@link android.app.Activity#showDialog(int)}, passing the unique integer ID for the time picker dialog. Using {@link android.app.Activity#showDialog(int)} allows the {@link android.app.Activity} to manage the life-cycle of the dialog and will call the {@link android.app.Activity#onCreateDialog(int)} callback method to request the {@link android.app.Dialog} that should be displayed (which you'll define later). After the on-click listener is set, a new {@link java.util.Calendar} is created to get the current hour and minute. Finally, the private updateDisplay() method is called in order to fill the {@link android.widget.TextView} with the current time.

  5. Add the updateDisplay() and pad() methods:
    // updates the time we display in the TextView
    private void updateDisplay() {
        mTimeDisplay.setText(
            new StringBuilder()
                    .append(pad(mHour)).append(":")
                    .append(pad(mMinute)));
    }
    
    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }
    

    The updateDisplay() method uses the member fields for the time and inserts them in the mTimeDisplay {@link android.widget.TextView}. The pad() method returns the appropriate string representation of the hour or minute—it will prefix a zero to the number if it's a single digit.

  6. Add a class member for a {@link android.app.TimePickerDialog.OnTimeSetListener} that will be called when the user sets a new time:
    // the callback received when the user "sets" the time in the dialog
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                updateDisplay();
            }
        };
    

    When the user is done setting the time (clicks the "Set" button), the onTimeSet() method is called and it updates the member fields with the new time and updates the layout's {@link android.widget.TextView}.

  7. Add the {@link android.app.Activity#onCreateDialog(int)} callback method:
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this,
                    mTimeSetListener, mHour, mMinute, false);
        }
        return null;
    }
    

    This is an {@link android.app.Activity} callback that is passed the identifier you passed to {@link android.app.Activity#showDialog(int)}, in the {@link android.widget.Button}'s on-click listener. When the ID matches, this initializes the {@link android.app.TimePickerDialog} with the member variables initialized at the end of onCreate() and the {@link android.app.TimePickerDialog.OnTimeSetListener} created in the previous step.

  8. Run the application.

When you press the "Change the time" button, you should see the following:

References

  1. {@link android.widget.TimePicker}
  2. {@link android.app.TimePickerDialog.OnTimeSetListener}
  3. {@link android.widget.Button}
  4. {@link android.widget.TextView}
  5. {@link java.util.Calendar}