xmarston
xmarston

Reputation: 883

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?

Upvotes: 5

Views: 5810

Answers (3)

JCarlosR
JCarlosR

Reputation: 1663

For those who use a RecyclerView with items that contain a TextView.

This will allow the TextView to get the focus state:

android:duplicateParentState="true"

Upvotes: 0

xmarston
xmarston

Reputation: 883

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>

Upvotes: 0

Amrut Bidri
Amrut Bidri

Reputation: 6360

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.

Upvotes: 2

Related Questions