Prevent back button from closing a dialog box

前端 未结 7 1303
别那么骄傲
别那么骄傲 2021-01-30 05:17

I am trying to prevent an AlertDialog box from closing when pressing the back button in Android. I have followed both of the popular methods in this thread, and with System.out.

7条回答
  •  有刺的猬
    2021-01-30 05:49

    Only this worked for me:

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(title);
    builder.setMessage(content);
    
    /**
     * Make it when the Back button is pressed, the dialog isn't dismissed.
     */
    builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
                Utilities.makeToast(getContext(), "There is no way back!");
                return true; // Consumed
            }
            else {
                return false; // Not consumed
            }
        }
    });
    
    Dialog dialog = builder.create();
    
    /**
     * Make it so touching on the background activity doesn't close the dialog
     */
    dialog.setCanceledOnTouchOutside(false);
    
    return dialog;
    

    As you can see, I also added a dialog.setCanceledOnTouchOutside(false); line so tapping outside of the dialog doesn't result in it being closed either.

提交回复
热议问题