views:

337

answers:

1

I reuse an AlertDialog box in my android app.

I create a dialog in the onCreateDialog() method and in the onPrepareDialog() method, I try to change the text of the positiveButton using the following code.

alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, this.getString(R.string.add), new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
          //Handler code
    }
}

The onclick listener is getting changed, but the button text is not changed.

Is it a bug in Android or am I doing something wrong?

A: 

This works for me

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {

        case DIALOG_ID:
            return AlertDialog.Builder(this).setTitle(R.string.contact_groups_add)
    .setView(addView).setPositiveButton(R.string.ok,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,
                        int whichButton) {

                }
            }).setNegativeButton(R.string.cancel,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,
                        int whichButton) {
                }
            }).create();
    }
    return null;
}
Pentium10
You have this code in onCreateDialog() or in onPrepareDialog() ?
Sudar
In none of them. I don't reused those methods of the activity. This code simply shows an alert dialog with the view from addView (inflated prior).
Pentium10
I understand this code. But my question was different.I already use onCreateDialog() and onPrepareDialog() functions. I created the dialog in the onCreateDilaog() method but when I try to change the text of the positive button in the onPrepareDialog() it is only changing the onClickListener and not the text.
Sudar
You can easily adapt my example to your needs. Just call `.create();` instead of `show()` and return in your `onCreateDialog` method the `Dialog` created by the code.
Pentium10
My onCreateDialog() code works properly without any issues. My problem is that, when I try to change the text of the positive button in the onPrepareDialog() using the setButton() method, the text is not changed.The reason why I am doing it in onPreapareDialog() is that onCreateDialog() will be called only once when the dialog is created for the first time.I want to reuse the same dialog, but only change the text of the positive button from "Add" to "Edit". When I set the text using the setButton method, it is not getting changed.
Sudar