Prevent back button from closing a dialog box

前端 未结 7 1318
别那么骄傲
别那么骄傲 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 05:25

    Simply use the setCancelable() feature:

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setCancelable(false);
    

    This prevents the back button from closing the dialog, but leaves the "negative" button intact if you chose to use it.


    While any user that does not want to accept your terms of service can push the home button, in light of Squonk's comment, here two more ways to prevent them from "backing out" of the user agreement. One is a simple "Refuse" button and the other overrides the back button in the dialog:

    builder.setNegativeButton("Refuse", new OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which) {
                   finish();
               }
           })
           .setOnKeyListener(new OnKeyListener() {
               @Override
               public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                   if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP)
                       finish();
                   return false;
               }
           });
    

提交回复
热议问题