簡介 下面以一個讓使用者選擇日期、時間的例子來示範DatePicker和TimePicker的功能和用法step1:建立一個項目DateAndTimePicker step2:編寫應用的UI介面 /layout/main.xml[html] <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="選擇購買此書的具體時間" /> <DatePicker android:id="@+id/datePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"/> <TimePicker android:id="@+id/timePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"/> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:editable="false" android:cursorVisible="false" android:id="@+id/show" /> </LinearLayout> step3:主程式MainActivity.java[java] package cn.roco.picker; import java.util.Calendar; import android.app.Activity; import android.os.Bundle; import android.widget.DatePicker; import android.widget.DatePicker.OnDateChangedListener; import android.widget.EditText; import android.widget.TimePicker; import android.widget.TimePicker.OnTimeChangedListener; public class MainActivity extends Activity { private int year; private int month; private int day; private int hour; private int minute; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker); TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker); Calendar calendar = Calendar.getInstance(); year = calendar.get(Calendar.YEAR); month = calendar.get(Calendar.MONTH); day = calendar.get(Calendar.DAY_OF_MONTH); hour = calendar.get(Calendar.HOUR); minute = calendar.get(Calendar.MINUTE); datePicker.init(year, month, day, new OnDateChangedListener() { @Override public void onDateChanged(DatePicker view, int year, int month, int day) { MainActivity.this.year = year; MainActivity.this.month = month; MainActivity.this.day = day; // 顯示時間 showDate(year, month, day, hour, minute); } }); timePicker.setOnTimeChangedListener(new OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker view, int hour, int minute) { MainActivity.this.hour = hour; MainActivity.this.minute = minute; // 顯示時間 showDate(year, month, day, hour, minute); } }); } private void showDate(int year, int month, int day, int hour, int minute) { EditText show = (EditText) findViewById(R.id.show); show.setText("您的購買日期為:" + year + "年" + month + "月" + day + "日 " + hour + "時" + minute + "分 "); } } step4:部署應用到模擬器上,並選擇日期和時間