I have an AlertDialog and its setCancelable() is false. In Onbackpressed function I want the AlertDialog to be closed. But when setCancelable
The easiest work-around for this problem is to set an OnKeyListener and automatically detect when the user hits the back button.
Java:
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setOnKeyListener(new Dialog.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_UP) {
dialog.cancel;
return true;
}
return false;
}
});
return dialog;
}
Kotlin:
dialog = AlertDialog.Builder(this)
.setCancelable(false)
.create()
dialog.show()
dialog.setOnKeyListener (object : Dialog.OnKeyListener {
override fun onKey(dialogInterface: DialogInterface, keyCode: Int, keyEvent: KeyEvent) {
if(keyCode == KeyEvent.KEYCODE_BACK and keyEvent.action == KeyEvent.ACTION_UP) {
dialog.dismiss()
true
}
false
}})
Note that I added an extra condition in the if-statement, all this does is to make sure this does not fire twice.
I hope this helps you.