To highlight the selected item in a RecyclerView
in Android, you can use the android:background
attribute in the layout file for the view holder.
Here's an example of how to do this:
First, create a selector
drawable resource file that defines the different states of the item's background. For example:
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_selected="true" android:drawable="@color/selected_color"/> <item android:drawable="@color/normal_color"/> </selector>Source:www.lautturi.com
Then, apply the selector
drawable as the android:background
attribute of the view holder's root layout in the layout file for the view holder:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/selector"> <!-- other layout elements go here --> </LinearLayout>
Finally, in your RecyclerView.Adapter
, set the selected state of the view holder by calling the setSelected()
method of the view holder when the item is selected:
@Override public void onBindViewHolder(MyViewHolder holder, int position) { holder.itemView.setSelected(selectedPos == position); }
This will cause the background color of the selected item to change to the color defined in the selected_color
state of the selector
drawable.