Emsal
Emsal

Reputation: 107

Not all items are selected in recyclerview android

In my OnBindViewHolderI've added the following code:

    if(checkAllItems) {
       viewHolder.checked_for_deletion.setChecked(true);
    } else {
       viewHolder.checked_for_deletion.setChecked(false);
    }

The problem is that OnBindViewHolder is only called for visible items + the cached items which is 2 by default. I need to select also the items that are not visible. I've looked around for solutions but couldn't find any that worked.

Upvotes: 1

Views: 228

Answers (2)

Emsal
Emsal

Reputation: 107

Here is what I did based on the answers above, for some reason I had to change the model based on the view. This doesn't work for obvious reasons since not all items are displayed in the view. I iterated trough the modellist and checked them there.

            checkbox_selectAllListener = new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                int c = 0;
                if(isChecked) {

                    for (TaskModel iterable_element : mDataset) {
                       iterable_element.setCheckedForDeletion(true);
                        Log.e("Setting checked ", ""+ c);
                        c++;
                    }
                } else {
                    for (TaskModel iterable_element : mDataset) {
                        iterable_element.setCheckedForDeletion(false);
                    }

                    Log.e("Setting unchecked ", ""+ c);
                    c++;
                }


                notifyDataSetChanged();
            }
        };

Upvotes: 0

Knossos
Knossos

Reputation: 16068

You cannot check all the items when binding the ViewHolder.

That is because only a certain number of ViewHolders are created at once (to fill your RecyclerView). These ViewHolders are then "recycled" as they pass out of the bounds of the RecyclerView. They are reused for future rows of content.

What you need to do is hold the state of the CheckBox in your data model. Then, you check whether the CheckBox needs to be checked with each call of onBindViewHolder.

Upvotes: 3

Related Questions