0

I am in Android Studio with java and have an AlertDialog with two buttons. My question is: Can I disable that when I press on the background and not on a button, that the dialog doesn't disappear?

I use this code to show the dialog:

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialogTheme);
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_wellcome_start_dialog,(ConstraintLayout)findViewById(R.id.layoutDialogConstrainer));
builder.setView(view);
((TextView) view.findViewById(R.id.textTitle)).setText(getResources().getString(R.string.titel));
((TextView) view.findViewById(R.id.textMessage)).setText(getResources().getString(R.string.startinfoone));
((Button) view.findViewById(R.id.buttonYes)).setText(getResources().getString(R.string.ok));
((Button) view.findViewById(R.id.buttonNo)).setText(getResources().getString(R.string.ueberspringen));
((ImageView) view.findViewById(R.id.imageIcon)).setImageResource(R.drawable.ic_info);

final AlertDialog alertDialog = builder.create();

view.findViewById(R.id.buttonYes).setOnClickListener(new View.OnClickListener() {
     @Override
         public void onClick(View v) {
         alertDialog.dismiss();
         weiter();
     }
});

view.findViewById(R.id.buttonNo).setOnClickListener(new View.OnClickListener() {
     @Override
         public void onClick(View v) {
         alertDialog.dismiss();
     }
});

if (alertDialog.getWindow() != null){
     alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
}

alertDialog.show();

Thanks!

Kes
  • 91
  • 7
  • `alertDialog.setCanceledOnTouchOutside(false)`. – ADM Apr 08 '20 at 07:16
  • 3
    Does this answer your question? [How to dismiss the dialog with click on outside of the dialog?](https://stackoverflow.com/questions/8384067/how-to-dismiss-the-dialog-with-click-on-outside-of-the-dialog) – Oleg Skidan Apr 08 '20 at 07:17

1 Answers1

3

Set the setCancelable property of the AlertDialog.Builder to false:

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialogTheme);
builder.setCancelable(false);

And also alertDialog.setCanceledOnTouchOutside(false);

jeprubio
  • 17,312
  • 5
  • 45
  • 56