How to highlight or change background of a selected item in Android RecyclerView

change background of a selected RecyclerView Item, AndroidMkab

In this post I will show you how to highlight or change background of selected item in Android RecyclerView.

This post is continuation for my previous post about Android RecyclerView With CardView Example All variables and views I use in this post are related to above project. If you are implementing this on your own project, make sure you handle variables and views as per your project.

Implementation Method:

Open your Android Studio project and open your cloros.xml file. Then add below color values(You can change the color values as per your requirement) to it.

Next Create a drawable file with name gradient_background.xml inside drawable folder and below code to it

Next Create a drawable file with name gradient_background_thick.xml inside drawable folder and below code to it

Next create another drawable file with name rv_highlight.xml and add below code to it.

No add rv_highlight.xml as background to any view you want to highlight inside recyclerview item design. I am adding it to Parent layout of my items_home.xml as below

Now we have to handle our implementation in RecyclerView Adapter. I am creating an integer variable in Adapter file for assigning RecyclerView item position. You can add variable two ways.

First one:

Second one:

Next in

method of your adapter add below line

lyt_parent is variable of my parent RelativeLayout in my items_home.xml if your using in different project make sure you replace it with your variable name.

next in onClick Listner of your view add below like below

Now run the code in your emulator or Android device and test it. You can download source code of this project from download button below.

Karthik M

0 Reviews

Write a Review