先來看看吧:
下面來貼出代碼吧,其中main.xml代碼為:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" 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:id="@+id/show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:cursorVisible="false" android:editable="false" /></LinearLayout>
其中java代碼為:
public class AndroidDemo5Activity extends Activity {// 記錄當前的時間private int year;private int month;private int day;private int hour;private int minute;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);setContentView(R.layout.main);DatePicker date = (DatePicker) findViewById(R.id.datePicker);TimePicker time = (TimePicker) findViewById(R.id.timePicker);// 或許當前的年月日,小時,分鐘Calendar ca = Calendar.getInstance();year = ca.get(Calendar.YEAR);month = ca.get(Calendar.MONTH);day = ca.get(Calendar.DAY_OF_MONTH);hour = ca.get(Calendar.HOUR);minute = ca.get(Calendar.MINUTE);// 初始化DatePickerdate.init(year, month, day, new OnDateChangedListener() {@Overridepublic void onDateChanged(DatePicker arg0, int year, int month,int day) {AndroidDemo5Activity.this.year = year;AndroidDemo5Activity.this.month = month;AndroidDemo5Activity.this.day = day;// 顯示目前時間和日期showDate(year, month, day, hour, minute);}});// 為TimerPicker指定事件監聽器time.setOnTimeChangedListener(new OnTimeChangedListener() {@Overridepublic void onTimeChanged(TimePicker arg0, int hour, int minute) {AndroidDemo5Activity.this.hour = hour;AndroidDemo5Activity.this.minute = minute;}});}protected void showDate(int year2, int month2, int day2, int hour2,int minute2) {EditText text = (EditText) findViewById(R.id.show);text.setText("您的購買時間為:" + year2 + "年" + month2 + "月" + day2 + "日"+ hour2 + "時" + minute2 + "分");}}