Not working onbackpressed when setcancelable of alertdialog is false

后端 未结 5 1130
名媛妹妹
名媛妹妹 2020-12-06 18:02

I have an AlertDialog and its setCancelable() is false. In Onbackpressed function I want the AlertDialog to be closed. But when setCancelable

5条回答
  •  情歌与酒
    2020-12-06 18:40

    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.

提交回复
热议问题