前言:
个人Android小白,写到这了,就记录一下,希望可以帮助到大家。
Android输入框点击弹出日期选择框
// 获取 文本编辑框控制权
EditText returnTime = findViewById(R.id.return_time);
// 日期选择触发器
returnTime.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
showDatePickDlg();
return true;
}
return false;
}
});
// 进入文本编辑框焦点触发日期选择器
returnTime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showDatePickDlg();
}
}
});
/**
* 弹出日期选择框
* 选择日期不能小于当天
*/
private void showDatePickDlg() {
Calendar calendar = Calendar.getInstance();
// 获取当前日期
final int mYear = calendar.get(Calendar.YEAR);
final int mMonth = calendar.get(Calendar.MONTH);
final int mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(BorrowActivity.this,
new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
// 判断选择年是否小于当前年
if (year < mYear) {
view.updateDate(mYear, mMonth, mDayOfMonth);
toast = ToastUtil.toastHint(toast,BorrowActivity.this,"归还日期不能小于当天,请重新选择!");
return;
}
// 判断选择月是否小于当前月
if (year == mYear && month < mMonth) {
view.updateDate(mYear, mMonth, mDayOfMonth);
toast = ToastUtil.toastHint(toast,BorrowActivity.this,"归还日期不能小于当天,请重新选择!");
return;
}
// 判断选择日是否小于当前日
if (year == mYear && month == mMonth && dayOfMonth < mDayOfMonth) {
view.updateDate(mYear, mMonth, mDayOfMonth);
toast = ToastUtil.toastHint(toast,BorrowActivity.this,"归还日期不能小于当天,请重新选择!");
return;
}
BorrowActivity.this.returnTime.setText(year+"-"+(month+1)+"-"+dayOfMonth);
}
},
mYear,
mMonth,
mDayOfMonth);
datePickerDialog.show();
}