Search code examples
javaandroidandroid-studioandroid-alertdialog

How to Make alert dialog close with buttons only in android


I want to make a alert dialog close when the user choose one of the available options in the box only, and doesn't close when he click the faded area around the alert dialog. So how can i prevent the alert dialog from close in that way ?

if (totalCount == 10){
        AlertDialog.Builder rateDialog = new AlertDialog.Builder(MainActivity.this);
        LayoutInflater layoutInflater = getLayoutInflater();
        View view = layoutInflater.inflate(R.layout.rating_deign, null);
        rateDialog.setView(view);
        final AlertDialog alert = rateDialog.create();
        alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        alert.show();

        btn_rate = view.findViewById(R.id.btn_rate);
        close = view.findViewById(R.id.close);


        btn_rate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                totalCount = 12;
                editor.commit();
                alert.cancel();
            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                totalCount = 0;
                editor.commit();
                alert.cancel();
            }
        });
    }

Solution

  • alert.setCancelable(false) you need to add.

    Sets whether the dialog is cancelable or not. Default is true.