简体   繁体   中英

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();
            }
        });
    }

alert.setCancelable(false) you need to add.

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

rateDialog.dismiss is correct answer.

rateDialog.dismiss()

alert.setCancelable(false)

From setCancelable you are minimising your dialog not Closing. By setting setCancelable(false) you can cancel (disappear) the dialog by clicking anywhere of the activity except dialog.

Conclusion: For Closing of dialog use dismiss().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM