Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent back button from closing a dialog box

Tags:

android

back

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.println I can see that in both cases the code executes. However, the back button still closes the dialog box.

What could I be doing wrong? Ultimately I'm trying to prevent the back button closing a dialog box - it is a disclaimer that is displayed the first time the app is run and I don't want the user to have any option but to press the "Accept" button in order for the app to continue.

like image 329
CaptainProg Avatar asked Aug 27 '12 22:08

CaptainProg


People also ask

How do you prevent a dialog from closing when a button is clicked?

If you wish to prevent a dialog box from closing when one of these buttons is pressed you must replace the common button handler for the actual view of the button.

What is a dialog button?

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed. Dialog Design.


2 Answers

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;            }        }); 
like image 171
Sam Avatar answered Oct 04 '22 11:10

Sam


To prevent the back button closes a Dialog (without depending on Activity), just the following code:

alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {     @Override     public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {         // Prevent dialog close on back press button         return keyCode == KeyEvent.KEYCODE_BACK;     } }); 
like image 44
falvojr Avatar answered Oct 04 '22 11:10

falvojr