Search code examples
androidandroid-recyclerviewselecteditem

Set the state of an item in a RecyclerView selected when click on it


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?


Solution

  • Well, after digging a little more and trying to understand the way that has android to implement the styles from an xml, I found that to change the text color (something I did not tell in my question) in the specific TextView you have to set the property android:color="@drawable/bg_item" (bg_item is the file that contains the selector and in each item the property android:color), 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>