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();
}
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
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;
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With