You may come across a situation when you need to mark visually the item that the user clicked in your RecyclerView. In our user scenario we need to change the background of the item in the RecyclerView on click by the user and then when the user clicks on a different item in the RecyclerView we need change the background of the newly selected item and restore the previous background on the previously clicked item, because we have no use of multiple selected items in our scenario.

If you need help on how to implement RecyclerView you can check how to do it here

We will create new project. We will need one activity, adapter and a model for our dummy data object and layout for our activity and our item for the RecyclerView.

You can find the whole project on GitHub here.

After the initial setup we will need to create an interface in the adapter to catch the on click event so that we can handle the on click logic in our activity instead of the adapter.

When we click we will get the item and the items position. In our bind function in the adapter we will set the on click listener:

Our activity will then implement this interface:

In the activity we will setup the RecyclerView and populate it with dummy data list:

Next we need to implement the background changing logic on item click. The logic is this: when the user clicks on an item, we check if the background on the clicked item is white (the item is not previously clicked) and if this condition is true, we change the background on all of the items in the RecyclerView to white (to invalidate previously clicked and marked items if there are any) and then change the background color of the clicked item to teal to mark it. And if the background of the clicked item is teal (which means the user clicks again on the same previously marked item), we change the background color on all of the items to white. First we will need to get our item background color as a ColorDrawable. We will use an iterator function to go through all of the items (children) of the RecyclerView and forEach() function to change the background on everyone of them. The code in our overriden onItemClickListener function will look like this:

And that’s it. The result will look like this:

You can find the whole project here: https://github.com/AleksandarGulevski/RecyclerViewExercises/tree/ChangeBackgroundOnClik

Happy coding!

 

Spread the love

Leave a Reply

Your email address will not be published.