From API 11, DatePicker can confirm your date.
Following the guide, you refer to when you redefine onCreateDialog, get a DatePicker, and set the minimum and maximum date:
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { // no changes from guide ... final DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day); dialog.getDatePicker().setMinDate(minDate); dialog.getDatePicker().setMaxDate(minDate); return dialog; }
Thus, the user cannot select the wrong date, so there is no need to manually check the date.
For older versions, you can use a boolean to control when closure is allowed, and implement your own logic. Here I will try to illustrate where you need to extend the code:
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { final DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day){ @Override public void onBackPressed() { allowClose = true; super.onBackPressed(); } @Override public void onClick(DialogInterface dialog, int which) { if (which==DialogInterface.BUTTON_POSITIVE && validate()){ allowClose = true; } super.onClick(dialog, which); } @Override public void dismiss() { if (allowClose) { super.dismiss(); } } }; return dialog; } private void onCancelBtnClick() { allowClose = true; dismiss(); }
source share