setOnCancelListener and setOnDismissListener is not called for AlertDialog for back button pressed or touch outside
The problem happens when you are using DialogFragment
to display Dialog
According to http://developer.android.com/reference/android/app/DialogFragment.html, the solution is to override onCancel
in DialogFragment
Please take note from http://developer.android.com/reference/android/app/DialogFragment.html#onCreateDialog(android.os.Bundle) too
Note: DialogFragment own the Dialog.setOnCancelListener and Dialog.setOnDismissListener callbacks. You must not set them yourself. To find out about these events, override onCancel(DialogInterface) and onDismiss(DialogInterface).
// This is DialogFragment, not Dialog
@Override
public void onCancel(DialogInterface dialog) {
}
If you are using AlertDialog
, see
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// dialog dismiss without button press
}
});
and dialog.setCanceledOnTouchOutside(true)
(thanks @LeosLiterak)
You have not set backPressed
key event
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
@Override
public boolean onKey(DialogInterface arg0, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
}
return true;
}
});
you should read this topic: How to dismiss the dialog with click on outside of the dialog?
Dialog dialog = new Dialog(context)
dialog.setCanceledOnTouchOutside(true);
in your DialogFragment, override
@Override
public void onStop() {
super.onStop();
if (mListener != null) {
// do something here
}
}