实现的效果是单击EditText输入框弹出日历,选择完成后EditText中填入选择的日期。直接给EditText设置监听事件即可,代码如下:
EditText.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View arg0) {DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {@Overridepublic void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {// TODO Auto-generated method stubmYear = year;mMonth = monthOfYear;mDay = dayOfMonth;if (mMonth + 1 < 10) {if (mDay < 10) {startday = new StringBuffer().append(mYear).append("-").append("0").append(mMonth + 1).toString();} else {startday = new StringBuffer().append(mYear).append("-").append("0").append(mMonth + 1).toString();}} else {if (mDay < 10) {startday = new StringBuffer().append(mYear).append("-").append(mMonth + 1).toString();} else {startday = new StringBuffer().append(mYear).append("-").append(mMonth + 1).toString();}}EditText.setText(startday);//一定要有这行代码,把选择的日期填入到EditText中}};new DatePickerDialog(getActivity(), onDateSetListener, mYear,mMonth, mDay).show();}});
我所做的项目需要日期的格式为:XXXX-XX,只需要年月不需要日,所以我做了简单的字符串拼接。
效果如下:
单击完成后的效果: