I think this will be very easy to implement but after hours of searching I could not find something useful to get it working. I want to set selected the item that the user clicks in a Drawer, this list is an RecyclerView. In the ViewHolder of my adapter I have an onClick event for the items:
@Override
public void onClick(View v) {
notifyItemChanged(selectedItem);
selectedItem = getPosition();
notifyItemChanged(selectedItem);
}
selectedItem is an int to track the selected item.
Now in the onBindViewHolder I do this:
holder.itemView.setSelected(position == selectedItem);
But it seems that the selected state is never called because I have a android:background seted to the items row 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 is working so I know that the background is well applied.
So, how can I set the selected state to an item in a RecyclerView?
Remove the onclick listener from view holder.
In onBindViewHolder do this:
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 might solve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With