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

In this article, I am going to explain how to create a 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 TextView will update with the new date.

·         Start a new project named TimePickerDemo.

·         Open the res/layout/main.xml file and insert the following:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android=""
        android:text="Change the time"/>

Open the activity file and add the following code as shown below:

import java.util.Calendar;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class TimePickerActivity extends Activity {

        private TextView mTimeDisplay;
        private Button mPickTime;
        private int mHour;
        private int mMinute;

        static final int TIME_DIALOG_ID=0;

     public void onCreate(Bundle savedInstanceState) {

         // capture our View elements
         mTimeDisplay = (TextView) findViewById(;

         // add a click listener to the button
         mPickTime.setOnClickListener(new View.OnClickListener() {

                      public void onClick(View v) {


         // get the current time
         final Calendar c=Calendar.getInstance();

         // display the current date

     // updates the time we display in the TextView
     private void updateDisplay()

        private Object pad(int mMinute2) {

                      return String.valueOf(mMinute2);
                      return "0"+String.valueOf(mMinute2);

        // the callback received when the user "sets" the time in the dialog
        private TimePickerDialog.OnTimeSetListener mtimeSetListener=new
                                             TimePickerDialog.OnTimeSetListener() {
                                            TimePickerDialog.OnTimeSetListener() {

               public void onTimeSet(TimePicker view, int hourOfDay, int minute) {


        protected Dialog onCreateDialog(int id)
             case TIME_DIALOG_ID:
               return new TimePickerDialog(this,mtimeSetListener,mHour,mMinute,false);
           return null;

·         Run the application.
Output will something like below:

Time picker in Android Application

When you click on the button (Change the time), a time picker dialog will open, you can set the time from the time picker dialog.

Time picker in Android Application

After setting the time, a new time will display in the TextView.

  Modified On Mar-23-2018 02:12:08 AM

Leave Comment