Android: How to override onBackPressed() in AlertDialog?
Found a shorter solution :) try this:
accountDialog = builder.create();
accountDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
dialog.dismiss();
activity.finish();
}
});
I finally added a key listener to my dialog to listen to the Back key.
Not as elegant as overriding onBackPressed()
but it works.
Here is the code:
dlgDetails = new AlertDialog.Builder(this)
.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey (DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK &&
event.getAction() == KeyEvent.ACTION_UP &&
!event.isCanceled()) {
dialog.cancel();
showDialog(DIALOG_MENU);
return true;
}
return false;
}
})
//(Rest of the .stuff ...)
For answer in Kotlin see here:Not working onbackpressed when setcancelable of alertdialog is false
This handles both the BACK button and the click OUTSIDE the dialog:
yourBuilder.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
dialog.cancel();
// do your stuff...
}
});
dialog.cancel()
is the key: with dialog.dismiss()
this would handle only the click outside of the dialog, as answered above.