TimePickerDialog

The TimePicker we saw here takes a lot of screen space. You might want to pop up a TimePickerDialog instead. It takes the same amount of space, but, like any Dialog, it remains visible for only a short time. (A Dialog is the Android equivalent of an iPhone UIActionSheet or a view managed by a modal view controller.) See the time picker dialog tutorial.

This app creates only one dialog, although it can pop up again and again. A more complicated app might create several different dialogs. Each dialog therefore has its own id number, e.g., TIME_PICKER_DIALOG_ID.

For each dialog, the onCreateDialog method of the Activity is called only once, to create the dialog. The onPrepareDialog method is called each time the dialog is popped up. Do not call these methods yourself—they’re called automatically when you call showDialog.

Four ways to make the dialog disappear

The cancel button does not call onCancel.

  1. Press the set button in the lower right corner of the TimePickerDialog. Calls onTimeSet and onDismiss.
  2. Press the cancel button in the lower left corner of the TimePickerDialog. Calls onDismiss.
  3. Press the Android back button. Calls onCancel and onDismiss.
  4. Change the app’s configuration (e.g., portrait to landscape). Calls onDismiss and the dialog reappears in the new orientation.

Format the time

The setText method of the activity formats the time in 12- or 24-hour format, depending on the setting set by the Android Settings app. Warning: the getTimeFormat method of class android.text.format.DateFormat returns an object of class java.text.DateFormat. The two DateFormats are two different classes.

Source code in Picker.zip

  1. PickerActivity.java
  2. main.xml
  3. AndroidManifest.xml

Things to try

  1. Go to the settings app and change the time to 24-hour format. Will the TimePicker reflect this change?

  2. What if you wanted to call a method when (and only when) the user presses the “Cancel” button in the lower left corner of the TimePickerDialog?

  3. Can the dialog id numbers (e.g., TIME_PICKER_DIALOG_ID) be a set of Java enums?