如果您不想使用此类对话框的自定义实现,则必须子类DatePickerDialog
化以实现此类行为。您不能仅使用 来阻止对话框关闭DatePickerDialog.OnDateSetListener
。
不幸的是,对话框的实现随着不同的 API 级别而变化,因此通过子类化获得所需的行为并不是那么简单。您需要添加一些技巧以使其可靠地工作。
我创建了一个示例实现,它阻止对话框关闭,除非设置了适当的日期(或者点击取消或返回按钮)。调整它以向用户显示您的警报,最好的地方是onClick()
方法中的 else 分支。
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();
}
}
};