Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 530
xmarston Avatar asked Nov 01 '22 06:11

xmarston


1 Answers

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.

like image 177
Amrut Bidri Avatar answered Nov 09 '22 16:11

Amrut Bidri