Home | History | Annotate | Download | only in views
      1 page.title=Hello, TimePicker
      2 parent.title=Hello, Views
      3 parent.link=index.html
      4 @jd:body
      5 
      6 <p>A {@link android.widget.TimePicker} is a widget that allows the 
      7 user to select the time by hour, minute and AM or PM.</p>
      8 
      9 
     10 <ol>
     11   <li>Start a new project/Activity called HelloTimePicker.</li>
     12   <li>Open the layout file and make it like so:
     13     <pre>
     14 &lt;?xml version="1.0" encoding="utf-8"?>
     15 &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     16     android:layout_width="wrap_content"
     17     android:layout_height="wrap_content"
     18     android:orientation="vertical">
     19 
     20     &lt;TextView android:id="@+id/timeDisplay"
     21         android:layout_width="wrap_content"
     22         android:layout_height="wrap_content"
     23         android:text=""/>
     24 
     25     &lt;Button android:id="@+id/pickTime"
     26         android:layout_width="wrap_content"
     27         android:layout_height="wrap_content"
     28         android:text="Change the time"/>
     29 
     30 &lt;/LinearLayout>
     31 </pre>
     32 	<p>For the layout, we're using a vertical LinearLayout, with a {@link android.widget.TextView} that
     33 	will display the time and a {@link android.widget.Button} that will initiate the 
     34         {@link android.widget.TimePicker} dialog.
     35 	With this layout, the TextView will sit above the Button.
     36 	The text value in the TextView is set empty, as it will be filled by our Activity
     37 	with the current time.</p>
     38     </li> 
     39 
     40   <li>Open HelloTimePicker.java. Insert the following to the HelloTimePicker class:
     41 <pre>
     42 private TextView mTimeDisplay;
     43 private Button mPickTime;
     44 
     45 private int mHour;
     46 private int mMinute;
     47 
     48 static final int TIME_DIALOG_ID = 0;
     49 
     50 &#64;Override
     51 protected void onCreate(Bundle savedInstanceState) {
     52     super.onCreate(savedInstanceState);
     53     setContentView(R.layout.main);
     54     
     55     // capture our View elements
     56     mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
     57     mPickTime = (Button) findViewById(R.id.pickTime);
     58 
     59     // add a click listener to the button
     60     mPickTime.setOnClickListener(new View.OnClickListener() {
     61         public void onClick(View v) {
     62             showDialog(TIME_DIALOG_ID);
     63         }
     64     });
     65 
     66     // get the current time
     67     final Calendar c = Calendar.getInstance();
     68     mHour = c.get(Calendar.HOUR_OF_DAY);
     69     mMinute = c.get(Calendar.MINUTE);
     70 
     71     // display the current date
     72     updateDisplay();
     73 }
     74 </pre>
     75 <p class="note"><strong>Tip:</strong> Press Ctrl(or Cmd) + Shift + O to import all needed packages.</p>
     76         <p>We start by instantiating variables for our View elements and time fields.
     77 	The <code>TIME_DIALOG_ID</code> is a static integer that uniquely identifies the dialog. In the
     78 	<code>onCreate()</code> method, we get prepared by setting the layout and capturing the View elements. 
     79 	We then set an on-click listener for the Button, so that when it is clicked, it will
     80 	show our TimePicker dialog. The <code>showDialog()</code> method will perform a callback
     81 	to our Activity. (We'll define this callback in the next section.) We then create an
     82 	instance of {@link java.util.Calendar} and get the current hour and minute. Finally, we call 
     83 	<code>updateDisplay()</code>&mdash;our own method that will fill the TextView with the time.</p>
     84 </li>
     85 
     86 <li>After the <code>onCreate()</code> method, add the <code>onCreateDialog()</code> callback method:
     87 <pre>
     88 &#64;Override
     89 protected Dialog onCreateDialog(int id) {
     90     switch (id) {
     91     case TIME_DIALOG_ID:
     92         return new TimePickerDialog(this,
     93                 mTimeSetListener, mHour, mMinute, false);
     94     }
     95     return null;
     96 }
     97 </pre>
     98 	<p>This is passed the identifier we gave <code>showDialog()</code> and initializes
     99 	the TimePicker to the time we retrieved from our Calendar instance. It will be called by 
    100         <code>showDialog()</code>.</p>
    101 </li>
    102 
    103 <li>Now add our <code>updateDisplay()</code> method:
    104 <pre>
    105 // updates the time we display in the TextView
    106 private void updateDisplay() {
    107     mTimeDisplay.setText(
    108         new StringBuilder()
    109                 .append(pad(mHour)).append(":")
    110                 .append(pad(mMinute)));
    111 }
    112 </pre>
    113 	<p>This simply takes our member fields for the time and inserts them in 
    114 	the <code>mTimeDisplay</code> TextView. Note that we call a new method, <code>pad()</code>,
    115 	on the hour and minute. (We'll create this method in the last step.)</p>
    116 </li>
    117 
    118 <li>Next, add a listener to be called when the time is reset:
    119 <pre>
    120 // the callback received when the user "sets" the time in the dialog
    121 private TimePickerDialog.OnTimeSetListener mTimeSetListener =
    122     new TimePickerDialog.OnTimeSetListener() {
    123         public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    124             mHour = hourOfDay;
    125             mMinute = minute;
    126             updateDisplay();
    127         }
    128     };
    129 </pre>
    130 	<p>Now when the user is done setting the time (clicks the "Set" button), we update our member fields with
    131 	the new time and update our TextView.</p>
    132 </li>
    133 <li>Finally, add the <code>pad()</code> method that we called from the <code>updateDisplay()</code>:
    134 <pre>
    135 private static String pad(int c) {
    136     if (c >= 10)
    137         return String.valueOf(c);
    138     else
    139         return "0" + String.valueOf(c);
    140 }
    141 </pre>
    142 	<p>This method returns the appropriate String representation of the hour or minute.
    143 	It will prefix a zero to the number if it's a single digit.
    144   	</p>
    145 </li>
    146 
    147 <li>Now run it.</li>
    148 </ol>
    149 <p>When you press the "Change the time" button, you should see the following:</p>
    150 <img src="images/hello-timepicker.png" width="150px" />
    151 
    152 <h3>References</h3>
    153 <ol>
    154   <li>{@link android.widget.TimePicker}</li>
    155   <li>{@link android.widget.Button}</li>
    156   <li>{@link android.widget.TextView}</li>
    157   <li>{@link java.util.Calendar}</li>
    158 </ol>
    159 
    160