效果
核心代码
>方法
/**
* @description 选择日期弹出框
* @param listener 选择日期确定后执行的接口
* @param curDate 当前显示的日期
* @return
* @author wqy
* @time 2020-1-6 14:23
*/
public void showDatePickDialog(DatePickerDialog.OnDateSetListener listener, String curDate) {
Calendar calendar = Calendar.getInstance();
int year = 0,month = 0,day = 0;
try {
year =Integer.parseInt(curDate.substring(0,curDate.indexOf("-"))) ;
month =Integer.parseInt(curDate.substring(curDate.indexOf("-")+1,curDate.lastIndexOf("-")))-1 ;
day =Integer.parseInt(curDate.substring(curDate.lastIndexOf("-")+1,curDate.length())) ;
} catch (Exception e) {
e.printStackTrace();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day=calendar.get(Calendar.DAY_OF_MONTH);
}
DatePickerDialog datePickerDialog = new DatePickerDialog(this,DatePickerDialog.THEME_HOLO_LIGHT,listener, year,month , day);
datePickerDialog.show();
}
>调用
showDatePickDialog(new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
etDate.setText(year + "-" + (month + 1) + "-" + day);
}
}, etDate.getText().toString());
说明:etDate为一个输入框EditText 显示当wujiaox前选择的日期,也可使用 TextView 。
⭐使用EditText 时需注意:将EditText Touch 时弹出输入框的效果禁用掉,所以尽量使用 onTouch 来实现弹出,不用 onClick 事件
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction()==MotionEvent.ACTION_DOWN){
hideInput();//隐藏输入框
switch (view.getId()) {
case R.id.etDate:
showDatePickDialog(new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
//选择日期过后执行的事件
etDate.setText(year + "-" + (month + 1) + "-" + day);
}
}, etDate.getText().toString());
break;
}
}
return false;
}
>hideInput方法 有可能不是当前输入框调出的输入框,在点击之前有输入框也要隐藏掉
/**
* 隐藏键盘
*/
protected void hideInput() {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
View v = getWindow().peekDecorView();
if (null != v) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}