Android Time Picker Example

Android it’s very easy to set the time using the android.widget.TimePickercomponent. In this tutorial we are going to see how the user can select the hour, and the minute using the android.app.TimePickerDialog which is an easy to use dialog box.

 

For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SKD 4.2

1. Create a new Android Project

Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project. You have to specify the Application Name, the Project Name and the Package Name in the appropriate text fields and then click Next.

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

Select “BlankActivity” and click Next.

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created. Then, click Finish.

2. Adding resources

Use the Package Explorer in Eclipse to navigate to res/values/strings.xml

When you open the strings.xml file, Eclipse will display the graphical Resources View editor :

That’s a nice and easy tool you can use to add several resources to your application like strings, integers, color values etc. But we are going to use the traditional way and that is editing the strings.xml file by hand. In the bottom of the screen, press the string.xml tab and paste the following code :

1 <?xml version="1.0" encoding="utf-8"?>
2 <resources>
3
4     <string name="app_name">TimePickerExample</string>
5     <string name="button_label">Change Time</string>
6     <string name="time_txt">Current Time (H:M): </string>
7     <string name="menu_settings">Settings</string>
8
9 </resources>

So, we’ve just created some string resources that we can use in many ways and in many places in our app.

3. Creating the Time Picker

Open res/layout/main.xml file :

And paste the following code :

01 <?xml version="1.0" encoding="utf-8"?>
02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03     android:layout_width="fill_parent"
04     android:layout_height="fill_parent"
05     android:orientation="vertical" >
06
07     <Button
08         android:id="@+id/button"
09         android:layout_width="wrap_content"
10         android:layout_height="wrap_content"
11         android:text="@string/button_label" />
12
13     <TextView
14         android:id="@+id/time_label"
15         android:layout_width="wrap_content"
16         android:layout_height="wrap_content"
17         android:text="@string/time_txt"
18         android:textAppearance="?android:attr/textAppearanceLarge" />
19
20     <TextView
21         android:id="@+id/txtTime"
22         android:layout_width="wrap_content"
23         android:layout_height="wrap_content"
24         android:text=""
25         android:textAppearance="?android:attr/textAppearanceLarge" />
26
27     <TimePicker
28         android:id="@+id/timePicker"
29         android:layout_width="wrap_content"
30         android:layout_height="wrap_content" />
31
32 </LinearLayout>

Now you may open the Graphical Layout editor to preview the User Interface you created:

4. Code

Go to the java file that contains the code of the activity you’ve just created and paste the following code:

001 package com.javacodegeeks.android.timepickerexample;
002
003 import java.util.Calendar;
004 import android.app.Activity;
005 import android.app.Dialog;
006 import android.app.TimePickerDialog;
007 import android.os.Bundle;
008 import android.view.View;
009 import android.view.View.OnClickListener;
010 import android.widget.Button;
011 import android.widget.TextView;
012 import android.widget.TimePicker;
013
014 public class MainActivity extends Activity {
015
016     private TextView textViewTime;
017     private TimePicker timePicker;
018     private Button button;
019
020     private int hour;
021     private int minute;
022
023     static final int TIME_DIALOG_ID = 999;
024
025     @Override
026     public void onCreate(Bundle savedInstanceState) {
027         super.onCreate(savedInstanceState);
028         setContentView(R.layout.main);
029
030         setCurrentTimeOnView();
031         addButtonListener();
032
033     }
034
035     // display current time
036     public void setCurrentTimeOnView() {
037
038         textViewTime = (TextView) findViewById(R.id.txtTime);
039         timePicker = (TimePicker) findViewById(R.id.timePicker);
040
041         final Calendar c = Calendar.getInstance();
042         hour = c.get(Calendar.HOUR_OF_DAY);
043         minute = c.get(Calendar.MINUTE);
044
045         // set current time into textview
046         textViewTime.setText(newStringBuilder().append(padding_str(hour)).append(":").append(padding_str(minute)));
047
048         // set current time into timepicker
049         timePicker.setCurrentHour(hour);
050         timePicker.setCurrentMinute(minute);
051
052     }
053
054     public void addButtonListener() {
055
056         button = (Button) findViewById(R.id.button);
057
058         button.setOnClickListener(new OnClickListener() {
059
060             @Override
061             public void onClick(View v) {
062
063                 showDialog(TIME_DIALOG_ID);
064
065             }
066
067         });
068
069     }
070
071     @Override
072     protected Dialog onCreateDialog(int id) {
073         switch (id) {
074         case TIME_DIALOG_ID:
075             // set time picker as current time
076             return new TimePickerDialog(this, timePickerListener, hour, minute,false);
077
078         }
079         return null;
080     }
081
082     private TimePickerDialog.OnTimeSetListener timePickerListener =  newTimePickerDialog.OnTimeSetListener() {
083         public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
084             hour = selectedHour;
085             minute = selectedMinute;
086
087             // set current time into textview
088             textViewTime.setText(newStringBuilder().append(padding_str(hour)).append(":").append(padding_str(minute)));
089
090             // set current time into timepicker
091             timePicker.setCurrentHour(hour);
092             timePicker.setCurrentMinute(minute);
093
094         }
095     };
096
097     private static String padding_str(int c) {
098         if (c >= 10)
099            return String.valueOf(c);
100         else
101            return "0" + String.valueOf(c);
102     }
103 }

5. Run the application

This is the main screen of our Application. When the application launches, the setCurrentTimeOnView() method is called, finds out the current time using java.util.Calendar, and updates the values both on the TextView and the Time Picker:

Now, press “Change Time”. When you press that button, the onClick method is called, which calls showDialog(). Now, when showDialog() is called, automatically onCreateDialog() is called. onCreateDialog() creates and returns a new TimePickerDialog . And so the dialog window with a Time Picker pops up. You can now adjust the time:

When you press “Done” the onTimeSet() method is called and it updates the values in the TextView and in the Time Picker:

Download Eclipse Project

This was an Android Time Picker Example. Download the Eclipse Project of this tutorial: AndroidTimePickerExample.zip

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s