简体   繁体   中英

Checkboxes become unchecked in Dialog when scrolling

I am using AlertDialog.Builder.setMultiChoiceItems to show checkboxes with texts. I can display the checked items successfully, but whenever I scroll it down or up, some of them become randomly unchecked. Below is my code.

What can I do to fix this? Any help appreciated!

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Title")
    .setMultiChoiceItems(items, selectedItems,
            new DialogInterface.OnMultiChoiceClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which,
                                    boolean isChecked) {
                    selected[which] = isChecked;
                }
            })
    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dialog.dismiss();
        }
    })
    .setNegativeButton(R.string.preklici, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
        }
    });

I think you are implementing checkbox in list View item so you can go through this answer. https://stackoverflow.com/a/10896140/6869491 hope it will help

You need to handle the check state of the checkbox in the code. Create a list of already selected items

So create ArrayList<Integer> selList=new ArrayList(); then on your setMultiChoiceItems do the following -

.setMultiChoiceItems(items, selectedItems,
                new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which,
                                        boolean isChecked) {

                            // If user select a item then add it in selected items
                            selectedItems.add(which);
                            multichoiceDialog.getListView().setItemChecked(which, isChecked);// You can tell the dialog to update its state here. 

                    }
                }

Please note I have only shown 1 part of your code so only use the content inside the setMultiChoiceItems method. Otherwise you might have to take care of the braces on your own :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM