設置日期DatePickerDialog
package com.example.testview; import java.util.Calendar; import java.util.Date; import java.util.Locale; import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; import android.view.View; import android.view.View.OnClickListener; import android.app.DatePickerDialog; /** * * DatePickerDialog是設置日期對話框,通過OnDateSetListener監聽並重新設置日期, * 當日期被重置后,會執行OnDateSetLintener類中的方法onDateSet() * */ public class DatePickerDialogExample extends Activity { private TextView showdate; private Button setdate; private int year; private int month; private int day; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.datepickerdialog); showdate=(TextView) this.findViewById(R.id.showtime); setdate=(Button) this.findViewById(R.id.setdate); //初始化Calendar日歷對象 Calendar mycalendar=Calendar.getInstance(); year=mycalendar.get(Calendar.YEAR); //獲取Calendar對象中的年 month=mycalendar.get(Calendar.MONTH);//獲取Calendar對象中的月 day=mycalendar.get(Calendar.DAY_OF_MONTH);//獲取這個月的第幾天 showdate.setText("當前日期:"+year+"-"+(month+1)+"-"+day); //顯示當前的年月日 //添加單擊事件--設置日期 setdate.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { /** * 構造函數原型: * public DatePickerDialog (Context context, DatePickerDialog.OnDateSetListener callBack, * int year, int monthOfYear, int dayOfMonth) * content組件運行Activity, * DatePickerDialog.OnDateSetListener:選擇日期事件 * year:當前組件上顯示的年,monthOfYear:當前組件上顯示的月,dayOfMonth:當前組件上顯示的第幾天 * */ //創建DatePickerDialog對象 DatePickerDialog dpd=new DatePickerDialog(DatePickerDialogExample.this,Datelistener,year,month,day); dpd.show();//顯示DatePickerDialog組件 } }); } private DatePickerDialog.OnDateSetListener Datelistener=new DatePickerDialog.OnDateSetListener() { /**params:view:該事件關聯的組件 * params:myyear:當前選擇的年 * params:monthOfYear:當前選擇的月 * params:dayOfMonth:當前選擇的日 */ @Override public void onDateSet(DatePicker view, int myyear, int monthOfYear,int dayOfMonth) { //修改year、month、day的變量值,以便以后單擊按鈕時,DatePickerDialog上顯示上一次修改后的值 year=myyear; month=monthOfYear; day=dayOfMonth; //更新日期 updateDate(); } //當DatePickerDialog關閉時,更新日期顯示 private void updateDate() { //在TextView上顯示日期 showdate.setText("當前日期:"+year+"-"+(month+1)+"-"+day); } }; }