Set the state of an item in the RecyclerView selected when clicking on it
I think it will be very easy to implement, but after hours of searching, I couldn't find anything useful to get it to work. I want to set the selected item that the user clicks in the box, this list is a RecyclerView. In the ViewHolder of my adapter, I have an onClick event for elements:
@Override
public void onClick(View v) {
notifyItemChanged(selectedItem);
selectedItem = getPosition();
notifyItemChanged(selectedItem);
}
selectedItem is an int to keep track of the selected item.
Now in onBindViewHolder I do this:
holder.itemView.setSelected(position == selectedItem);
But it seems like the selected state is never called because I have an android: background set for a row of items with this content:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="@drawable/border_bottom_selected"
android:color="@color/backgroundToolbar"/>
<item android:drawable="@drawable/border_bottom" />
</selector>
The normal state works, so I know the background applies well.
So how can I set the selected state to an item in the RecyclerView?
source to share
Well, after digging a little more and trying to figure out how Android has to implement styles from xml, I found that in order to change the text color (something I didn't say in my question) on a specific TextView, you need to set the android:color="@drawable/bg_item"
(bg_item is file containing the selector and in each element the android: color property), something like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="@drawable/border_bottom_selected"
android:color="@color/backgroundToolbar" />
<item android:drawable="@drawable/border_bottom"
android:color="@color/colorTextTitleTab"/>
</selector>
source to share
Remove the onclick listener from the view holder.
In onBindViewHolder do the following:
viewHolder.itemView.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
notifyItemChanged(selectedItem);
selectedItem = position;
notifyItemChanged(selectedItem);
}
});
holder.itemView.setSelected(position == selectedItem);
I hope this can solve your problem.
source to share