package com.mrzhu.datedialog;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
/**
* DatePickerDialog,单击按钮调用setDate(),setDate()调用showDialog(int id)
* showDialog(int id)调用onCreateDialog(int id),onCreateDialog(int id)
* 使用到回调函数setDateCallBack,setDateCallBack调用upDateDisplay()设置日期
* @author ZLQ
*
*/
public class DateDialogTestActivity extends Activity {
private static final int DIALOG_DATE_ID = 0;
//用于显示日期的TextView
private TextView tv_set_date;
//当前系统的年月日
private int mYear;
private int mMonth;
private int mDay;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv_set_date = (TextView) findViewById(R.id.tv_set_date);
Calendar calendar = Calendar.getInstance();
mYear = calendar.get(Calendar.YEAR);
mMonth = calendar.get(Calendar.MONTH);
mDay = calendar.get(Calendar.DAY_OF_MONTH);
//updateDiaplay()把日期显示到TextView上
updateDiaplay();
}
private void updateDiaplay(){
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(mYear).append("年").append(mMonth).append("月").append(mDay).append("日");
tv_set_date.setText(stringBuffer);
}
//单击按钮调用setDate()方法
public void setDate(View v){
setDate();
}
//setDate()方法调用showDialog(int id)方法,showDialog(int id)方法调用onCreateDialog(int id)
private void setDate() {
showDialog(DIALOG_DATE_ID);
}
@Override
protected Dialog onCreateDialog(int id) {
switch(id){
case DIALOG_DATE_ID:
//返回一个日期对话框
return new DatePickerDialog(this, setDateCallBack, mYear, mMonth, mDay);
}
return super.onCreateDialog(id);
}
//回调函数,int year, int monthOfYear,int dayOfMonth三个参数为日期对话框设置的日期
private OnDateSetListener setDateCallBack = new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
updateDiaplay();
}
};
}
<?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/tv_set_date"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="setDate"
android:text="@string/btn_set_date" />
</LinearLayout>