How to disable the positivebutton of an AlertDialog during runtime?

android, android-widget

Solution

You need to obtain a reference to the dialog itself in order to modify it later, so you'll have to change your builder a little, but then you can call `AlertDialog.getButton()` to enable or disable the button anytime you like. Something like this...

//Use create() so you can get the instance back
AlertDialog dialog = AlertDialog.Builder(this)
                .setTitle(getString(R.string.createvfs))
                .setView(newVSView_v11)
                .setPositiveButton(getString(R.string.okay),
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                            }
                        })
                .setNegativeButton(getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                // Canceled.
                            }
                        }).create();
//Then show it
dialog.show();

/* ...Sometime in the distance future... */
dialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);

If you want to actually make the button invisible, that's slightly more difficult. I can't test at the moment whether calling `setVisibility()` on the button will produce good results or not...

HTH

Problem

Is there a way to disable the positivebutton of an AlertDialog during runtime,say from within a TextWatcher? ``` AlertDialog.Builder(this) .setTitle(getString(R.string.createvfs)) .setView(newVSView_v11) .setPositiveButton(getString(R.string.okay), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { } }) .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { // Canceled. } }).show(); ```

Original source