Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onBackPressed doesn't work with AlertDialog

My code displays an AlertDialog, which exits the activity by pressing the positive button. I want it to be able to exit on back button as well. But my onBackPressed does not work when I have .setCancelable(false) . How do I fix this without changing it to .setCancelable(true)

// show in dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("BROADCAST")
            .setMessage(text)
            .setCancelable(false)
            .setPositiveButton("Dismiss",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            finish();
                        }
                    });
    AlertDialog alert = builder.create();
    alert.show();
}

@Override
public void onBackPressed() {
    finish();
}
like image 608
user352806 Avatar asked Mar 04 '17 18:03

user352806


2 Answers

easy peeasy..

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("BROADCAST")
        .setMessage(text)
        .setCancelable(true)
        .setPositiveButton("Dismiss",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        finish();
                    }
                })
        .setOnDismissListener(new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialog) {
                                    finish();
                                }
                            });
AlertDialog alert = builder.create();
alert.setCanceledOnTouchOutside(false);
alert.show();

For answer in Kotlin see here:Not working onbackpressed when setcancelable of alertdialog is false

like image 75
Abhishek Singh Avatar answered Oct 14 '22 11:10

Abhishek Singh


you can set a key listener

builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

                    if(keyCode == KeyEvent.KEYCODE_BACK){
                        dialog.dismiss(); // dismiss the dialog
                       YourActivity.this.finish(); // exits the activity

                    }

                    return true;
                }
            })
like image 4
Majeed Khan Avatar answered Oct 14 '22 10:10

Majeed Khan