views:

46

answers:

2

I've got a dialog which shows a list of checkBoxes. I'd like to set different boxes checked each time the dialog is showed. But that only works the first time.. I want it work every time the dialog is showed! It would be great if anyone can help...

This is my code:

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

            case CHECKBOX_LIST_DIALOG:

                final CharSequence[] weeks = new CharSequence[53];

                for (int i=0; i<=52; i++) {
                    weeks[i] = String.valueOf(i+1);
                }

                return new AlertDialog.Builder(this).setTitle(
                        R.string.txt_week_checkbox_list).setMultiChoiceItems(
                        weeks, getCheckedBoxes(),
                        new DialogInterface.OnMultiChoiceClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
                                checked[whichButton] = isChecked;
                            }
                        }).setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                EditText editText = (EditText) findViewById(R.id.edittext_weeks);
                                editText.setText(generateString());
                            }
                        }).setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                            }
                        }).create();
}
+1  A: 

Managed dialogs created via onCreateDialog() are cached. You will need to override onPrepareDialog(), so you get control when the dialog is next shown. You are passed the Dialog object. Cast that to an AlertDialog, call getListView(), and use setItemChecked() to toggle each checkbox on or off.

CommonsWare
A: 

Great! That did it, thanks!! That was exactly what I was looking for :-) Here's what I did to make it work like you explained:

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    ListView lv = ((AlertDialog) dialog).getListView();
    boolean[] checked = myDialog.getCheckedBoxes();
    for (int i=0; i<checked.length; i++)
        if (checked[i])
            lv.setItemChecked(i, true);
}
cody