I am trying to prevent an AlertDialog box from closing when pressing the back button in Android. I have followed both of the popular methods in this thread, and with System.out.
Only this worked for me:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title);
builder.setMessage(content);
/**
* Make it when the Back button is pressed, the dialog isn't dismissed.
*/
builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
Utilities.makeToast(getContext(), "There is no way back!");
return true; // Consumed
}
else {
return false; // Not consumed
}
}
});
Dialog dialog = builder.create();
/**
* Make it so touching on the background activity doesn't close the dialog
*/
dialog.setCanceledOnTouchOutside(false);
return dialog;
As you can see, I also added a dialog.setCanceledOnTouchOutside(false);
line so tapping outside of the dialog doesn't result in it being closed either.