How do I detect a cancel click of the datepicker dialog?
If you want to perform a different action depending on whether the user selected a date or not you can use an onDismiss handler. Be sure to set a Boolean (e.g., "isDataSet") to indicate whether the user selected a date or not. Here's an example:
// Date Picker Dialog
public void showDatePickerDialog(View view) {
int year, month, day;
isDataSet = false; // this is used by the onDismiss handler
// Set initial time period in DatePicker to current month
calendarCurrent = Calendar.getInstance();
month = calendarCurrent.get(Calendar.MONTH);
day = calendarCurrent.get(Calendar.DAY_OF_MONTH);
year = calendarCurrent.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(YourActivity.this, dateSetListener, year, month, day );
datePickerDialog.setOnDismissListener(mOnDismissListener);
datePickerDialog.show();
datePickerDialog_visible=true; //indicate dialog is up
} // [END showDatePickerDialog]
//onDismiss handler
private DialogInterface.OnDismissListener mOnDismissListener =
new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
datePickerDialog_visible=false; //indicate dialog is cancelled/gone
if (isDataSet) { // [IF date was picked
//do something, date now selected
} else {
//do someething else, dialog cancelled or exited
}
}
};
Here's how I did it:
DatePickerDialog dialog = new DatePickerDialog(this,
mDateSetListener,
year, month, day);
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
// Do Stuff
}
}
});