The Date Picker and Time Picker Controls

As the names suggest, you use the DatePicker control to select a date and the TimePicker control to pick a time. Listing 4-21 and Figure 4-9 show examples of these controls.

Listing 4-21. The DatePicker and TimePicker Controls in XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">

<DatePicker android:id="@+id/datePicker"

android:layout_width="wrap_content" android:layout_height="wrap_content" />

<TimePicker android:id="@+id/timePicker"

android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

Figure 4-9. The DatePicker and TimePicker UIs

If you look at the XML layout, you can see that defining these controls is quite easy. The user interface, however, looks a bit overdone. Both controls seem a bit oversized, but for a mobile device, you can't argue with the look and feel.

As with any other control in the Android toolkit, you can access the controls program-matically to initialize them or to retrieve data from them. For example, you can initialize these controls as shown in Listing 4-22.

Listing 4-22. Initializing the DatePicker and TimePicker with Date and Time, Respectively protected void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState);

setContentView(R.layout.datetime);

DatePicker dp = (DatePicker)this.findViewByld(R.id.datePicker); dp.init(2008, 11, 10, null);

TimePicker tp = (TimePicker)this.findViewByld(R.id.timePicker); tp.setIs24HourView(true); tp.setCurrentHour(new Integer(io)); tp.setCurrentMinute(new Integer(io));

Listing 4-22 sets the date on the DatePicker to November 10, 2008. Similarly, the number of hours and minutes is set to 10. Note also that the control supports 24-hour view.

Finally, note that Android offers versions of these controls as modal windows, such as DatePickerDialog and TimePickerDialog. These controls are useful if you want to display the control to the user and force the user to make a selection.

0 0

Post a comment