Android日期选择控件DatePicker用法
本例通过点击button显示DatePicker对话框
先看截图
布局文件很简单,只是一个Button
首先获取系统时间
private int mYear; private int mMonth; private int mDay; private Calendar calendar;
calendar = Calendar.getInstance(); mYear = calendar.get(Calendar.YEAR); mMonth = calendar.get(Calendar.MONTH); mDay = calendar.get(Calendar.DAY_OF_MONTH);
下面来看一下如何显示DatePicker
有两种方法:
一、直接new一个Dialog
mBtnBirthday.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //mDateSetListener监听用户选择 //mYear, mMonth, mDay当前日期 new DatePickerDialog(SettingsEditUserInfo.this, mDateSetListener, mYear, mMonth, mDay).show(); } });
二、使用showDialog显示
private static final int DATE_DIALOG_ID = 1;
showDialog(DATE_DIALOG_ID);
/** * 当显示时间窗口被创建时调用 */ @Override protected Dialog onCreateDialog(int id) { switch (id) { case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); } return null; } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch (id) { case DATE_DIALOG_ID: ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay); break; default: break; } }
设置显示当前日期
/** * 设置日期 */ private void setDateTime() { final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay =c.get(Calendar.DAY_OF_MONTH);
//更新Button上显示的日期
updateDateDisplay(); }
监听事件
/** * 监听日期变化 */ private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; //更新Button上显示的日期 updateDateDisplay(); } };
/** * 更新日期显示(记得month要+1,因为DatePicker索引是0-11) */ private void updateDateDisplay() { mBtnBirthday.setText(new StringBuilder().append(mYear).append("-") .append(mMonth + 1).append("-").append(mDay)); }
over