1

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));
        }
    }
Cœur
  • 37,241
  • 25
  • 195
  • 267
user1
  • 254
  • 1
  • 15
  • Welcome to StackOverflow. If you want to be helper, you shall consider providing all relevant information, including source code that is misbehaving. Asking question in the way you just did usually ends with question being downvoted, closed or ignored. – Marcin Orlowski May 09 '16 at 17:42
  • @MarcinOrlowski I did provide the code that is misbehaving, and edited to provide more details – user1 May 09 '16 at 17:48

3 Answers3

1

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);
}
Stefan
  • 2,098
  • 2
  • 18
  • 29
1

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().

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
1

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.

colin
  • 87
  • 5