How to create Time Picker dialog for selecting time in Android

Sometimes we may require the user to set time in our application. While doing so instead of asking the user to enter the time data in raw form, we can provide him with a beautiful GUI to input the data.

Android comes equipped with a widget named TimePicker which we can integrate in our application to provide this functionality to the end users. It has an elegant look and design. So, lets get started.

To demonstrate how to use TimePicker widget we will create a layout which will have a textview and button. The button will be used to choose a new time and once chosen the updated time will be displayed in the textview. Create a new Android project with the following properties:

  • Project Name – Time Picker
  • Name of the Application – Time Picker
  • Package name – com.botskool.TimePicker
  • Activity Name – TimePickerActivity

Create a new XML file in res/layout/ and name it as main.xml and copy the following code to it:

<?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="Time will appear here after being selected"
    android:textSize="30sp"/>
    <Button android:id="@+id/pickTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change the time"/>
</LinearLayout>

Our application consists of a textview and a button. The textview will be used to display the time set up by the user. When the application loads initially it will display the current time. The button displays the Time Picker dialog to the user. Finally, add the following code to TimePickerActivity.java:

package com.botskool.TimePicker;

import java.util.Calendar;

import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class TimePickerActivity extends Activity {
	/** Private members of the class */
	private TextView displayTime;
    private Button pickTime;

    private int pHour;
    private int pMinute;
    /** This integer will uniquely define the dialog to be used for displaying time picker.*/
    static final int TIME_DIALOG_ID = 0;
    
    /** Callback received when the user "picks" a time in the dialog */
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                pHour = hourOfDay;
                pMinute = minute;
                updateDisplay();
                displayToast();
            }
        };
    
    /** Updates the time in the TextView */
    private void updateDisplay() {
        displayTime.setText(
            new StringBuilder()
                    .append(pad(pHour)).append(":")
                    .append(pad(pMinute)));
    }
    
    /** Displays a notification when the time is updated */
    private void displayToast() {
    	Toast.makeText(this, new StringBuilder().append("Time choosen is ").append(displayTime.getText()),	 Toast.LENGTH_SHORT).show();
            
    }
    
    /** Add padding to numbers less than ten */
    private static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /** Capture our View elements */
        displayTime = (TextView) findViewById(R.id.timeDisplay);
        pickTime = (Button) findViewById(R.id.pickTime);

        /** Listener for click event of the button */
        pickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        /** Get the current time */
        final Calendar cal = Calendar.getInstance();
        pHour = cal.get(Calendar.HOUR_OF_DAY);
        pMinute = cal.get(Calendar.MINUTE);

        /** Display the current time in the TextView */
        updateDisplay();
    }
    
    /** Create a new dialog for time picker */
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this,
                    mTimeSetListener, pHour, pMinute, false);
        }
        return null;
    }
}

Here, we start by declaring the members of our class. We use onCreate() function to map our class members to the corresponding variables in the layout. Additionally, we register ourselves to the on-click listener event of the button. When a user clicks on the button, we call the showDialog() function. A call to onCreateDialog() function needs to be made the first time showDialog() function executes in order to create an instance of dialog TimePickerDialog. Once an instance is created we use it again and again whenever user clicks on the button to setup a new time. Also, we retreive the current time and call updateDisplay() function inside onCreate() function.

The updateDisplay() function is used to update the layout's TextView, displayTime, by using the values of the private time members of the class.

Also, the TimePickerDialog.OnDateSetListener listens for when the user has set the time (by clicking on the button). Whenever this happens, the onTimeSet() callback method is called, which is defined to update the pHour and pMinute member fields with the new time set by the user. After this the private updateDisplay() method is called to update the TextView and displayToast() method is called to show a notification informing about the time change.

Thats it! Now compile and run the Android application. If you click on the button the time picker widget will be displayed as shown below:

After the user sets the time, the textview is updated along with a notification as shown below:

 

Comments

Member since:
7 August 2017
Last activity:
1 year 14 weeks

kanye west shoes

michael kors bags

ua shoes

ray ban erika

prada handbags

payless shoes online

official kate spade website

coach outlet online

pandora rings

pandoracharms

pandora rings uk

Coach Sunglasses Outlet

balenciaga outlet

Engagement Rings - Official

Nike Air Max 180

official michael kors

Ray Ban sunglasses

shoes sale

Nike Air Max

Air Max 180

burberry outlet

Dreamland Jewelry - Official

birkenstock sandals

birkenstock

Nike Air Max Couple

coach outlet online

prada outlet online

louis vuitton outlet online

Nike Air Jordan

gel kayano

official michael kors

michael kors outlet bags

Hugo Boss Store

payless shoes

Premier Jewelry - Official

ray ban outlet

Coach Handbags

pandora sale

coach watches

nike store

football jerseys

louis vuitton outlet online

coach outlet online sale

Add Your Link Free

backlink

louis vuitton us

michael kors

Nike Air Jordan Enfants

michael kors

Michael Kors Handbags Outlet Sale

kate spade outlet online

Green Cleaned

ugg boots

sunglasses

Nike Blazer Femmes

evbid

Wine

coach outlet

birkenstock outlet

Burberry Australia

payless near me

Chanel Outlet

north face sale

Nike Air Max

Prada Shoes - Official

michael kors outlet

ray ban wayfarer sunglasses

Oakley Sunglasses

puma sneakers outlet

payless shoes

nike free shoes

diesel watches

burberry outlet canada

prada sale

puma sneakers sale

louis vuitton outlet

Air Max 180 Homme

Jewelry Armoire - Official

coach handbags sale

Hermes Outlet

timberland shoes

Nike Air Max 2017

coachs outlet

louis vuitton outlet online

Nike Jordans

football jerseys

burberry outlet sale

Nike Free 3.0

michael kors outlet online

ray ban wayfarer

ray ban sunglasses

Rolex Watch

michael kors

michael kors

nike huarache shoes

ray ban sale

Adamson

pandora necklaces

kate spade italy

coach australia

pandora uk

pandora uk

swatch watch

michael kors watches

michael kors

rayban prescription sunglasses

Brighton Jewelry - Official

prada outlet online

Nike Air Force

michael kors outlet

fulam shoes

softball jerseys

Nike Air Max

balenciaga us

Air Max 1 Homme

michael kors

Watches

Air Jordan Enfant

chrome store canada

sunglasses store

coach outlet

michael kors outlet

Nike Free Run

mk outlet online

michael kors outlet

the beat

seiko watches

michael kors

Lifestyle

Air Max 90 Femme

hermes outlet

Nike Air Jordan enfants

hermes outlet

prada purses

kate spade outlet

nike jordan shoes

me adc8.7