Advanced onClick RecyclerView using Interface | RecyclerView item Click using Interface

In this tutorial, we’re going to create a recyclerView and apply on Click on the recyclerView using Interface. This the advanced way to apply items click on the recyclerView.

Before adding the interface first create recyclerView. Here I’m not going to explain how to create a recyclerView, if you don’t know how to create a recyclerView then go to my previous tutorial on recyclerView How to create RecyclerView in Android.

And if you’re familiar with it then just follow these steps to create recyclerView or we can create your own recyclerView.

Before applying the Interface callbacks

activity_main.xml

item_row.xml

RecyclerViewAdapter.java

MainActivity.java

After applying the Interface callbacks

You don’t need to change the main and item row XML files, they are same as it is. We need to make some change in the Adapter class and Main activity java files, also we need to implement the interface callbacks in our main activity for item clicks inside recyclerView.

  • For that first create an interface. Right-click on the java package and create a new java file, but make sure kind is to be an interface.
  • Inside here we create some methods that we would like to handle inside our main activity that when a person clicks on an item this method would be called.

RecyclerViewClickInterface.java

  • Now let’s go to our MainActivity.java and implement the interface that we just created which was the recyclerView click interface.
  • Let’s go to the top of our class that is the Main Activity class it extends from AppCompatActivity but also implements our interface which we have just created.
  • Now go to the RecyclerView Adapter class and create a variable for our interface and also change the constructor of the RecyclerAdapter.
  • Now inside our main java class where we called our adapter, it now needs one more argument that is the interface.

Here, this means the interface.

  • Now go to the adapter class where we set the item view set onClickListener, instead of passing it along with the item view now we pass the reference of the interface so that we can handle the on click from the main activity java file.
  • Make these changes in the Adapter class and Main Activity java file.

RecyclerViewAdapter.java

MainActivty.java

Output

The output is not different from regular on click. Here we just apply interface callbacks for the item clicks.

Hi everyone, myself Golap an Android app developer with UI/UX designer.