2

I have got a RecyclerView item looking like thisitem

I want to achieve that when I click on item the ImageView will get overlay over it and TextView will become bold. I know how to use adapter and where to handle item clicks. I also know how to make overlay or bold text. I only want to know how to make this item selectable to get the behavior I described above. Because I found only tutorials to change background of item when clicked.

Matej Košút
  • 590
  • 2
  • 10
  • 27
  • Possible duplicate of [Highlight selected item inside a RecyclerView](http://stackoverflow.com/questions/27390682/highlight-selected-item-inside-a-recyclerview) – Hamid Reza Mar 05 '17 at 07:37
  • just add click listener on each item's of your RecyclerView that you need and make them clickable in xml – Hamid Reza Mar 05 '17 at 07:38

2 Answers2

3

Based on this

I only want to know how to make this item selectable to get the behavior I described above.

So basically you need a way to tell the ViewHolder that the current item is selected, such that in onBindViewHolder() the items are rendered as per need.

I can think of this: Make a model of the item youre adding to the RecyclerView. Add a key as boolean isSelected = false in it.

And inside your onBindViewHolder where youre implementing the onClick()interface. do this:

... new OnClickListener({
    ... onClick(){
        // take the item and set the isSelected flag
        list.get(position).setIsSelected(true):
        notifyDataSetChanged();
        // alternatively you can also toggle this flag. 
    }
});

and while loading inside onBindViewHolder to this:

if (list.get(position).isSelected()) {
    // highlight aka set overlay and bold text to view
} else {
    // as per recyclerview doc, reset the views. 
}
MadScientist
  • 2,134
  • 14
  • 27
2

All you need is having a variable to hold the selected index. Then decorating the selected item in onBindViewHolder() method.

int selectedIndex = 0;
...
public void onBindViewHolder(ViewHolder viewHolder, int position) {
    if (selectedIndex == position) {
        // Do things you want
    }
}
Tuyen Nguyen
  • 19
  • 1
  • 4