Search code examples
androidcheckboxdialogcheckboxlistprepare

Can't set checkbox state in onPrepareDialog


I've got a dialog which shows a list of checkboxes. The info which boxes should be checked each time it opens comes from an edittext. I searched for a way to not allow caching of the dialog but couldn't find out how to do that. Now I override onPrepareDialog to set the checkboxes before the dialog opens. I deleted the content of my edittext, opened the dialog and there were still the same boxes checked... can anyone tell me how to reset the checkboxes?

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        ListView lv = ((AlertDialog) dialog).getListView();

        if (lv == null)
            return;

        boolean[] checked = cbDialog.setAndGetCheckedArray();

        String s = "onPrepareDialog... checked=";
        for (int i=0; i<checked.length; i++)
            s+="["+i+"="+checked[i]+"]";
        System.out.println(s);

            // if edittext is empty, all entries in checked[] are false here,
            // but these changes do NOT affect the checkboxes in the dialog:
        for (int i=0; i<checked.length; i++)
            if (checked[i])
                lv.setItemChecked(i, true);
            else 
                lv.setItemChecked(i, false);
    }

Solution

  • Well, I finally found out how to solve this problem, perhaps it may help anyone:

    I've found out that (because of the internal caching mechanism) it may be better not to call showDialog() in the activity and use onCreateDialog() to create a dialog, if the content of the dialog is modified dynamically.

    Instead, I've created a class which extends AlertDialog.Builder. I implemented a method like "showCustomDialog()" where I call .setTitle..., .setMultiChoiceItems(), and finally show(). This method of my custom AlertDialog.Builder I can use in my activity and everything works as expected ;)