Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to show selection of the lst item in recycler view in android?

I have implemented the recycler view in navigation drawer in android.This is working fine.I am able to switch between item by clicking on recycler view item. but i am not able to change the background color for the selected item.please suggest me how to imeplement it.I have tried this so far.

1.Background Selector in RecyclerView Item Tried to make recycler view clickable,focusable but didn't work

2.http://innodroid.com/blog/post/tracking-selected-item-in-recyclerview

implemented but didn't understand where to write the code for changing background

Please help me out.

like image 297
Rahul Batra Avatar asked Nov 01 '22 04:11

Rahul Batra


1 Answers

What you really need to understand with RecyclerView is that it's not the same control as a Listview with a funky adapter.

RecyclerView does not exhibit many of the ListView's functionalities and whilst it's understandable to compare it to a ListView or a GridView (or event a StaggeredGridView), it shouldn't be confused with them.

With RecyclerView, the responsibilities of handling the "background change" selector relies on the underlying control that the RecyclerView is holding. It's also the same with onClick and many other perks you get for free in a ListView.

Why it is better (or worse) to use a RecyclerView to a ListView is a different matter that I won't go into but to fix your problem, in order to set a background selector on your RecyclerView, add this to the layout that you're inflating in your ViewHolder (i.e. the actual layout that's being used inside the RecyclerView, similar to your "list row item" that you would inflate inside an ArrayAdapter if it were a ListView):

android:clickable="true"
android:background="?android:selectableItemBackground" 

Which should set the background appropriately.

like image 116
kha Avatar answered Nov 09 '22 10:11

kha