Recycler View Item Event Handling With Data Binding

Samet Kemal Ozdemir
2 min readFeb 14, 2022

Hi Guys !! In this article, we will increase or decrease the numerical value of the element of a list in the Recycler View. While doing this, we will do the click event using an Interface. In this way, you will be able to implement your onClick operations into the Fragment or Activity you want.

Scenario

Let’s say we are developing an e-commerce app. The user adds the selected product to the basket. When the last basket was completed, the customer wanted to change the quantity of some products. In this case, we will both get rid of the code redundancy by writing our click events abstractly, and we will see how we can do this through Data Binding.

Preparation

Enable Data Binding from Gradle scripts, by adding the following piece of code inside the android block of the module-level build. Gradle file.

android {
buildFeatures {
dataBinding true
}
...
}

if you are using Kotlin you need to add this too

plugins {
...

id 'kotlin-kapt'
}

Now let’s create an Order Model in line with the first scenario.

Let’s create an Order Click Listener Interface. Here we will send the entire order object as a parameter. If you want, you can send only the attributes of the order, it’s completely up to you.

We will create a recycler Row where each basket list element will be displayed. First of all, we wrap the entire Row view with <layout> Tags for Data Binding. We open a <data> Tag and write which classes we will use in this layout with Data Binding and their Paths.

Let’s write an onClick method in the plus Image View. We call the onPlusClicked function in the orderClickListener interface within the expression “@{() -> orderListener.onPlusItemClicked(order)}” you see here. Our purpose in calling this function like this is that we can write the body of this function in every Fragment or Activity that implements the OrderClickListener Interface.

We have created the Recycler Row, we can start writing the Recycler Adapter Class. Here we want the OrderClickListener interface as a parameter. Because we can set the OrderClickListener functions from within the Fragment or Activity that will use the BasketRecyclerAdapter. We also bind Order and Listener Objects with DataBinding

Finally, we implement the OrderClickListener in the BasketFragment. You can now perform your request within the incoming functions.

TA Da !! that’s it

If you want to review the whole project, you can go to my GitHub repository. I hope it was useful. See you again in another article !!

--

--