Android Basics – Learn how to handle the user clicks in a RecyclerView

You are familiar with how to respond to user clicks in a ListView using an OnItemClickListener. RecyclerView does not have a similar set of built in functionality so you will have to write some code to handle user clicks.

The code you will add will be in the Adapter’s onBindViewHolder. You will also add an interface, similar to the ay you did for Fragment interaction.

Follow the steps below:

Add a Listener interface to the Adapter.

public static interface Listener{
    public void onClick(int position);

Add a setListener method. This method will be called from the Activity.

public void setListener(Listener listener) {
    mListener = listener;

Add setOnClickListener

cardView.setOnClickListener(new View.OnClickListener(){
    public void onClick(View view){
        if(mListener != null){

In Activity class set the Listener defined in Adapter.

SampleAdapter adapter = new SampleAdapter(inputData);
adapter.setListener(new SampleAdapter.Listener() {
    public void onClick(int position) {
        //Add code here

Source code is available here

Android Basics : Why an onClickListener is better than android:onClick

In your App you might be having UI elements like buttons on click of which some action happens in the background.

Let’s take a button for example.


There are two ways to handle events on Button click. One is to define an android:onClick attribute in the layout xml file and specify the method in the Java class.


The problem with this approach is Рif you have buttons defined in a Fragment then you need to define corresponding methods in the Activity class. This will lead to tight coupling between Activity and Fragment.

To avoid this use a onClickListener.

For this you need to implement an onClickListener and bind the Button to this.

Follow the video and refer to the source code here to understand this better.

Android Basics – Add a Button and display a Toast on click

Time for some Action. Let’s add a Button to the Layout XML file and on click of button let’s display a message to the user.

Simple Steps

Add a Button component to the XML file.

    android:text="Click Me"

Add a method to the MainActivity class.

public void clickMe(View view){
    Toast.makeText(MainActivity.this, "Button Clicked !!", Toast.LENGTH_SHORT).show();

You are all set. Test your app now.

Source Code