RecyclerView BackgroundColor

I used RecyclerView

to display some text data. I have logic to choose different cards.

I would like to change the appearance of the selected cards.

public void toggleSelection(int pos)
    {
        RecyclerView.ViewHolder viewHolder = recView.findViewHolderForPosition(pos);
        if (selectedItems.get(pos, false)) {
            selectedItems.delete(pos);
            viewHolder.itemView.setBackgroundColor(Color.WHITE);
        }
        else {
            selectedItems.put(pos, true);
            viewHolder.itemView.setBackgroundColor(Color.GREEN);
        }
        notifyItemChanged(pos);
    }

      

If I use my code like this it works. The onClick event fires this code and my map background color changes to green.

So here's my problem: scrolling down shows other cards in the same relative position (but further down the list) with the same background color, even if they are not selected; selecting the first card and scrolling down to where the eighth card is the top visible card reveals the eighth card.

+3


source to share


1 answer


You need to explicitly set the colors in the method onBindViewHolder()

.

View recycler as the title suggests to recycle the views, so the 0th item is being recycled as the 8th item in your case. They share the same view holder created with the method onCreateViewHolder()

. And every time any of them comes into view, the method is called onBindViewHolder()

. I suggest you create an additional boolean field in your data model, telling you if you have selected the view or not. You have to switch it to toggleSelection()

. Then in onBindViewHolder()

you check the value of this field and set your color accordingly.



+6


source







All Articles