How to keep an alertdialog open after button onclick is fired? [duplicate]

You do not need to create a custom class. You can register a View.OnClickListener for the AlertDialog. This listener will not dismiss the AlertDialog. The trick here is that you need to register the listener after the dialog has been shown, but it can neatly be done inside an OnShowListener. You can use an accessory boolean variable to check if this has already been done so that it will only be done once:

    /*
     * Prepare the alert with a Builder.
     */
    AlertDialog.Builder b = new AlertDialog.Builder(this);

    b.setNegativeButton("Button", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {}
    });
    this.alert = b.create();

    /*
     * Add an OnShowListener to change the OnClickListener on the
     * first time the alert is shown. Calling getButton() before
     * the alert is shown will return null. Then use a regular
     * View.OnClickListener for the button, which will not 
     * dismiss the AlertDialog after it has been called.
     */

    this.alertReady = false;
    alert.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            if (alertReady == false) {
                Button button = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //do something
                    }
                });
                alertReady = true;
            }
        }
    });

Part of this solution was provided by http://groups.google.com/group/android-developers/browse_thread/thread/fb56c8721b850124#

Leave a Comment