Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Prevent an Alert Dialog Getting Closed by Back Button

I have an alert dialog like this:

    AlertDialog.Builder oyunaBaslaDialog = new AlertDialog.Builder(this);
    oyunaBaslaDialog.setMessage("A Takımı");
    oyunaBaslaDialog.setNeutralButton("Başla!",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    oyunOyna();
                }
            });
    oyunaBaslaDialog.show();

This dialog is shown in onCreate method. And I want it just to be closed by the button on it. But Hardware Back Button can also close this dialog without dialog's action performed.

I dont want the back button close this dialog, what can i do?

like image 505
Batuhan Avatar asked Aug 18 '11 20:08

Batuhan


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.

How do I stop alert dialog from closing the flutter?

To make your AlertDialog widget not close when user taps on the screen space outside the alert box, set barrierDismissible property to false in showDialog() helper method.

What is the difference between an alert and an alert dialog?

AlertDialog is a lightweight version of a Dialog. This is supposed to deal with INFORMATIVE matters only, That's the reason why complex interactions with the user are limited. Dialog on the other hand is able to do even more complex things .

How do I turn off alerts in dialog?

AlertDialog generally consists of the main title, the message, and two buttons, technically termed as a positive button and a negative button. Both positive and negative buttons can be programmed to perform various actions. By default, the negative button lets close the AlertDialog without any additional lines of code.


2 Answers

Use Dialog.setCancelable():

Sets whether this dialog is cancelable with the BACK key.

In your code this would be:

oyunaBaslaDialog.setCancelable(false);
like image 159
Jacob Ras Avatar answered Sep 24 '22 08:09

Jacob Ras


Implement setOnKeyListener and catch the KeyEvent.KEYCODE_BACK. If you return true in this method, dialog will not close.

like image 30
CommonMan Avatar answered Sep 26 '22 08:09

CommonMan