Recipe 2.8 Using the TimePicker

Android Versions
Level 1 and above
Permissions
None
Source Code to Download from Wrox.com
UsingTimePicker.zip

The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM mode. This recipe shows you how to use it.

Solution

Assume you have the following code snippet in the activity_main.xml file, which contains a TimePicker and a Button view:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

    <Button
        android:id="@+id/btnSet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/timePicker"
        android:layout_marginTop="29dp"
        android:text="I am all set!" 
        android:onClick="btnClick"/>

</RelativeLayout>

The TimePicker displays a standard UI to enable users to set a time. By default, it displays the time in the AM/PM format.

The following code snippet shows how you can get the time set by the user using the TimePicker view:

package com.example.usingtimepicker;
import java.text.DecimalFormat;
import java.text.NumberFormat; import android.app.Activity; ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.