Search code examples
androidandroid-alertdialog

HowTo prevent AlertDialog.Builder cancelOnTouchOutside


With ordinary dialog we can use cancelOnTouchOutside but with AlertDialog.Builder we can't use it Is there a way to do it?

AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(getString(R.string.tx_newgame));
alert.setMessage(getString(R.string.tx_newgamesure));
// Réponse Oui
alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int which) {
    dialog.dismiss(); // ferme le dialogue et commence une nouvelle partie
    //....
  }
});
// Réponse Non
alert.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialog, int which) {
    dialog.cancel();
    //....
  }
});
=> alert.setCanceledOnTouchOutside(false);  // need fix here
alert.show();

Solution

  • It's very simple, follow these steps

    AlertDialog dialog;
     AlertDialog.Builder alert = new AlertDialog.Builder(this);
    
     dialog=alert.create();
     //CanceledOnTouchOutside
     dialog.setCanceledOnTouchOutside(false);