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?
Asked
Active
Viewed 1,588 times
1

khateeb
- 5,265
- 15
- 58
- 114
1 Answers
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
-
Isn't `onBindView` only called at the creation of the Recycler View? – khateeb Apr 23 '18 at 13:46
-
it will be called everytime...on notifyDataSetChanged – Ashwani Apr 23 '18 at 13:46
-
and i missed something....wait ..leme modify my answer a bit – Ashwani Apr 23 '18 at 13:47
-
You could call `notifyItemChanged(position)` on both the previous and new selected items to prevent having to redraw the entire list – Eselfar Apr 23 '18 at 13:48
-
yes @Eselfar i agree..one can... – Ashwani Apr 23 '18 at 13:50