Widget Catalog: TimePicker

Just as DatePicker allows the user to pick a date, TimePicker allows the user to pick a time. This widget is a bit simpler to use, insofar as you do not have the option of the integrated CalendarView as you do with DatePicker. In other respects, TimePicker follows the patterns established by DatePicker.

Note that TimePicker only supports hours and minutes, not seconds or finer granularity.

Key Usage Tips

With DatePicker, the act of supplying an OnDateSetListener also required you to supply the year/month/day to use as a starting point. TimePicker is more intelligently designed: setting the OnTimeSetListener is independent from adjusting the hour or minute.

As with DatePicker, TimePicker works well with Calendar and GregorianCalendar, in terms of setting and getting the hour/minute/second from the TimePicker and converting it into something you can use in your code.

There is a bug in which your OnTimeSetListener is not invoked when the user changes between AM and PM when viewing the TimePicker in 12-hour display mode.

A Sample Usage

The sample project can be found in WidgetCatalog/TimePicker.

Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  android:gravity="center_vertical">

  <TimePicker
    android:id="@+id/picker"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

</LinearLayout>
(from WidgetCatalog/TimePicker/app/src/main/res/layout/main.xml)

Activity:

package com.commonsware.android.wc.timepick;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.Toast;
import java.util.Calendar;

public class TimePickerDemoActivity extends Activity implements
    OnTimeChangedListener {
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TimePicker picker=(TimePicker)findViewById(R.id.picker);

    picker.setOnTimeChangedListener(this);
  }

  @Override
  public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
    Calendar then=Calendar.getInstance();

    then.set(Calendar.HOUR_OF_DAY, hourOfDay);
    then.set(Calendar.MINUTE, minute);
    then.set(Calendar.SECOND, 0);

    Toast.makeText(this, then.getTime().toString(), Toast.LENGTH_SHORT)
         .show();
  }
}
(from WidgetCatalog/TimePicker/app/src/main/java/com/commonsware/android/wc/timepick/TimePickerDemoActivity.java)

Visual Representation

Android 2.3.3
Figure 1056: Android 2.3.3

Android 4.0.3
Figure 1057: Android 4.0.3

Android 5.0
Figure 1058: Android 5.0

Android 6.0, Landscape