1

I have a RecyclerView in which when a user clicks on an item, the background color of the RecyclerView changes. When the user clicks on another item, I want the background color of the previous selected item to return to normal and the new item's background color to change. How do I do this?

khateeb
  • 5,265
  • 15
  • 58
  • 114

1 Answers1

2

Simple way is have a global variable, save position on click of item and notifyDataSetChanged and in onBindView compare the position if equal then set background color else set it to normal.

Code snippet

int clickedPosition;
boolean clicked;

public void onBindView(ViewHolder holder,int position){
    //your code
    if(clicked){
    if(position == clickedPosition)
       holder.itemView.setBackgroundColor(...);
    else
       holder.itemView.setBackGroundColor(..your default color..);
    }
    holder.itemView.setOnClickListener(...){
        clickedPosition = position;
        clicked = true; 
        notifyDataSetChanged();
    }
}
Shivam Kumar
  • 1,892
  • 2
  • 21
  • 33
Ashwani
  • 1,294
  • 1
  • 11
  • 24