I am trying to use a RecyclerView
as a horizontal ListView
. I am trying to figure out how to highlight the selected item. When I click on one of the items, it gets selected and it is highlighted properly but when I click on another one, the second one gets highlighted with the older one.
Here is my onClick function:
@Override
public void onClick(View view) {
if(selectedListItem!=null){
Log.d(TAG, "selectedListItem " + getPosition() + " " + item);
selectedListItem.setBackgroundColor(Color.RED);
}
Log.d(TAG, "onClick " + getPosition() + " " + item);
viewHolderListener.onIndexChanged(getPosition());
selectedPosition = getPosition();
view.setBackgroundColor(Color.CYAN);
selectedListItem = view;
}
Here is the onBindViewHolder
:
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
viewHolder.setItem(fruitsData[position]);
if(selectedPosition == position)
viewHolder.itemView.setBackgroundColor(Color.CYAN);
else
viewHolder.itemView.setBackgroundColor(Color.RED);
}
Best Answer
This is much simple way to do it.
Have a
private int selectedPos = RecyclerView.NO_POSITION;
in the RecyclerView Adapter class, and under onBindViewHolder method try:And in your OnClick event modify:
Works like a charm for Navigtional Drawer and other RecyclerView Item Adapters.
Note: Be sure to use a background color in your layout using a selector like colabug clarified:
Otherwise setSelected(..) will do nothing, rendering this solution useless.