Ted
Ted

Reputation: 20184

Why does alert.getButton(AlertDialog.BUTTON_POSITIVE) return NULL?

(Sorry, found out that this question was already answered, see below)

So, I first tried to extend the AlertDialog so that I could do some stuff with the EditTexts I need to have in my popup, but when I couldnt get that to work, I am now using the normal AlertDialog.Builder inside my MainActivity to create what I need.

The code below creates an AlertDialog and uses "setView" to add my custom view to it. When the AlertDialog first is shown, its POSITIVE button should be disabled, and only when all the EditTexts have text should the POSITIVT button be enabled.

So I try to do this by, after using builder.create(), getting the positive button.

However, alert.getButton(AlertDialog.BUTTON_POSITIVE) returns NULL. Why?

final EditText ed1 = (EditText) findViewById(R.id.editTextPausArea);
final EditText ed2 = (EditText) findViewById(R.id.EditTextPausTimeFrom);
final EditText ed3 = (EditText) findViewById(R.id.EditTextPausTimeTo);

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this)
.setTitle("Begär paus")
.setView(view)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {


    }
}).setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        // Do nothing.
    }
});

final AlertDialog alert = builder.create();
final Button b = alert.getButton(AlertDialog.BUTTON_POSITIVE);
b.setEnabled(false); // NullPointerException here!

Upvotes: 3

Views: 7573

Answers (2)

osiris81
osiris81

Reputation: 507

I had the same problem. My working solution for this problem was to call:

alert.show()

before accessing the button

Upvotes: 8

Uday
Uday

Reputation: 6023

this may help

.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() {                
    @Override
    public void onClick(DialogInterface dialog, int which) {
         ((AlertDialog)dialog).getButton(which).setVisibility(View.INVISIBLE);

    }
})

Upvotes: -3

Related Questions