why setCanceledOnTouchOutside(false) doesn't work in Alert builder?
I have an alert dialog in my activity and don't want user can dismiss it by clicking outside of the dialog. Based on my research (like this) I found setCanceledOnTouchOutside(false); method. However, I couldn't use it in my application and it is possible to dismiss dialog while I have this method.
this is my code:
private AlertDialog alertDialog; alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setCanceledOnTouchOutside(false); alertDialog.setTitle(""); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { switch (intAlertAction) { case 1: case 2: case 3: default: } } });
any suggestion would be appreciated.
Answers
This is an interesting question and I think I know your answer.
I have been testing an application on different platforms and I noticed a small difference between them. Above android 4.0 when you touch a Toast message, it simply disappears. I guess it is the same with dialogs (and AlertDialogs). It simply "disappears" when touching (but it is not dismissed! - just cannot be seen).
Hope it helped!
setCanceledOnTouchOutside only prevents dismissing by clicking outside of the dialog. But you can still dismiss it with back button for instance.
If you don't want your dialog to be cancelable at all use dialog.setCancelable(false)
I just tested your (fixed) code and it works as expected: the user cannot dismiss dialog when clicking out of it. Try it:
AlertDialog alertDialog; alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setCanceledOnTouchOutside(false); alertDialog.setTitle(""); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); alertDialog.show();
just
dialog.setCancelable(false);
Problem is solved!!
AlertDialog alertDialog; alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setCanceledOnTouchOutside(false); alertDialog.setCancelable(false); alertDialog.setTitle(""); alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); alertDialog.show();