android – recycled recyclerview item keeps the old background color-ThrowExceptions

Exception or error:

I have a recycler view and inside the onClick(View view) i’m changing the background color to almost transparent red view.setBackgroundColor(Color.argb(64, 183, 28, 28));
but something weird is happening which is when I scroll down I see the color has changed for items that have not been clicked yet, my guess is when the item is recycled it is retaining the color. I want to remove that color but removing it inside the constructor for the holder is not working so my question is how do I go about that?

EDIT: after the comment this is more detailed code

public class GridHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public TextView Name;
    public ImageView Photo;
    public GridHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
               Name = (TextView) itemView.findViewById(R.id.name);
        Photo = (ImageView) itemView.findViewById(R.id.photo);
        itemView.setClickable(true);
    }

    @Override
    public void onClick(View view) {

            view.setBackgroundColor(Color.argb(64, 183, 28, 28));
        }
    }
How to solve:

The simplest way to achieve this in my opinion is to give each item in your RecyclerView a state (boolean) and set the background depending on the state. This way when you recycle the view, the correct background is drawn.

if(isClicked){
    itemView.setBackgroundColor(Color.RED);
}
else{
    itemView.setBackgroudnColor(Color.WHITE);
}

###

You should set all attributes in your onBindViewHolder(), because, as you can see, view may not be fresh but recycled and show state of previously presented record. So if background color maters, you must set it too in onBindViewHolder().

###

You need to maintain the state of the background colour outside the ViewHolder (maybe in the Adapter or higher up). Then, in the onBindViewHolder of your Adapter, you set the background colour of your ViewHolder based on that state.

Leave a Reply

Your email address will not be published. Required fields are marked *