I am using the following method to pop up the dialog to pick the date.
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDi
If you don't want to use a custom implementation of such dialog, you have to subclass DatePickerDialog to achieve such behavior. You can't block the dialog from closing just with DatePickerDialog.OnDateSetListener.
Unfortunatelly, implementations of the dialog vary with different API levels, so it's not that trivial to get the desired behavior with subclassing. You need to add some hacks to make it work reliably.
I've created a sample implementation that blocks the dialog from closing unless an appropriate date is set (or a cancel or back button is hit). Adjust it to display your alert to the users, the best place is the else branch in onClick() method.
class CheckingDatePickerDialog extends DatePickerDialog {
private int year;
private boolean cancel = false;
private boolean isCancelable = true;
CheckingDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
super(context, callBack, year, monthOfYear, dayOfMonth);
this.year = year;
}
CheckingDatePickerDialog(Context context, int theme, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
super(context, theme, callBack, year, monthOfYear, dayOfMonth);
this.year = year;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// allow closing the dialog with cancel button
Button btn = getButton(BUTTON_NEGATIVE);
if (btn != null) {
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cancel = true;
dismiss();
}
});
}
}
@Override
public void setCancelable(boolean flag) {
isCancelable = false;
super.setCancelable(flag);
}
@Override
public void onBackPressed() {
// allow closing the dialog with back button if the dialog is cancelable
cancel = isCancelable;
super.onBackPressed();
}
private boolean isOldEnough() {
// test if the date is allowed
return year <= 1994;
}
@Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// necessary for some Honeycomb devices
DatePicker dp = getDatePicker();
this.year = dp.getYear();
}
if (isOldEnough()) {
// OnDateSetListener is called in super.onClick()
super.onClick(dialog, which);
} else {
// place your alert here
}
}
@Override
public void onDateChanged(DatePicker view, int year, int month, int day) {
// on some Honeycomb devices called only with the first change
// necessary for devices running Android 2.x
this.year = year;
super.onDateChanged(view, year, month, day);
}
@Override
public void dismiss() {
if (cancel || isOldEnough()) {
// do not allow the dialog to be dismissed unless a cancel or back button was clicked
super.dismiss();
}
}
};