tags:

views:

572

answers:

1

Is there a simple way to change the contents of a dialog box in Android without having to re-create the dialog box? I know that Activity.onCreateDialog() is only called once when the dialog first needs to be created, and this is where you initially set the dialog's contents. I need to change the dialog's contents later, so I'm wondering what is the proper way to do this.

+1  A: 

The onPrepareDialog() method is called just before each time the Dialog is displayed allowing you to update it appropriately.

It's passed the same int ID as onCreateDialog() and the Dialog that you created in that method.

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    //Always call through to super implementation
    super.onPrepareDialog(id, dialog);

    switch (id) {
        case DIALOG_TIME:
            ((AlertDialog)dialog).setMessage("The time is " + new Date());
            break;
    }
}
Dave Webb
Don't know how I missed that. Thanks!
tronman
This works fine if you want to change an icon, message, title, and a few other items, but I don't think it will work if you want to change the items in a list. For example, if you called AlertDialog.Builder's setSingleChoiceItems() method, you can't change these items in onPrepareDialog(). The only solution is to create an OnDismissListener for the dialog which calls removeDialog()... this forces the onCreateDialog() method to be called every time.
tronman