通過學習DatePickerDialog,它為彈出一個修改系統時間的模态對話框,建立DatePickerDialog步驟如下:
package com.dateandtime;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
public class MainActivity extends Activity {
private Button showDatePickerButton = null;
//該常量用于辨別DatePickerDialog
private static final int DATE_PICKER_ID = 1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showDatePickerButton = (Button) findViewById(R.id.showDatePickerButton);
showDatePickerButton.setOnClickListener(new ButtonListener());
}
private class ButtonListener implements OnClickListener {
@Override
public void onClick(View v) {
//此方法用于顯示DatePickerDialog
showDialog(DATE_PICKER_ID);
}
}
//監聽器,使用者監聽使用者點下DatePikerDialog的set按鈕時,所設定的年月日
DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
//監聽器,使用者監聽使用者點下DatePikerDialog的set按鈕時,所設定的年月日
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
System.out.println(year + "-" + monthOfYear + "-" + dayOfMonth);
}
};
//建立一個DatePickerDialog對象
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
//設定DatePickerDialog顯示預設的時間
return new DatePickerDialog(this, onDateSetListener, 2010, 11, 25);
}
return null;
}
}