All 3 ways to implement onClickListener in Android | onClickListener example

Handling click events in android 

So you have started learning android app development and want to learn to implement click events. In this article, you are going to learn to implement onClickListener in Android.

It's most important to have a knowledge of handling click events while developing an android app.

In this article, we will create a simple android app and we will perform buttons clicks in it. So let's build it 🤟


3 Ways to implement onClickListener in Android button

There are 3 ways to implement click events in android and all those ways are listed below :


  • METHOD 1 - For a single button click

In this method, we can perform onclick with the help of the Anonymous inner class. You can use this method when you want to perform onclick event on a single button. And you should more use this method than any other method.

So let's see to implement this method in our java code.

Method 1 clickevent code 

   // initialize the button
        Button button1=findViewById(R.id.button1);

        //button click
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,"THIS IS BUTTON 1",Toast.LENGTH_SHORT).show();
            }
        });

Code explanation :

As you can see in the code, 

First, we have to initialize the button in our code.

Then, override the onClick(View v){ } method with the help of the Anonymous inner class.  And in the onClick(View v){ } method, you can write the logic which you want to perform when the button will be clicked.


  • METHOD 2 - Using XML tag attribute

You can use this method for both(single or multiple) button clicks. In this method, we set the value of the onclick attribute in the XML code of the button.

We have to give the value for the onclick attribute of the button as shown below :

    <Button
       
        android:onClick="btn2Click"
        
     />

Here btn2Click is the public method. we have to create that method in java code as shown below :

 // METHOD 2

    public void btn2Click(View view){
        Toast.makeText(MainActivity.this,"THIS IS BUTTON 2",Toast.LENGTH_SHORT).show();
    }

So add the code which you want to be performed when the button will be clicked in this method. But don't forget to pass the View as a parameter in this method.

Ok, Let's move on to the third method.


  • METHOD 3 - For a multiple  button click at a time

Use this method when you want code click events for multiple buttons at a time. In this method, we have to implement View.OnClickListener interface in java class.

Like this :

public class MainActivity extends AppCompatActivity implements View.OnClickListener{ 

And then override the onclick method as shown below :

@Override
    public void onClick(View v) {

    }

Now in this method, we can write our code to handle multiple buttons clicks. Suppose I want to set a click listener for two different buttons so I will use switch-case statements to handle click events like this :

 // METHOD 3
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.button3:
                Toast.makeText(MainActivity.this,"THIS IS BUTTON 3",Toast.LENGTH_SHORT).show();
                break;
            case R.id.button4:
                Toast.makeText(MainActivity.this,"THIS IS BUTTON 4",Toast.LENGTH_SHORT).show();
                break;
        }
    }

And then we have set click listener to that both button in the onCreate() method like this :

 // METHOD 3
        Button button3=findViewById(R.id.button3);
        Button button4=findViewById(R.id.button4);

        //click listener
        button3.setOnClickListener(this);
        button4.setOnClickListener(this);

So in this way, we can use method 3 to implement a click listener for multiple buttons with the help of the interface.


SOURCE CODE

In the above examples, I have used the code of the example app of button click. in this app, there are 4 buttons and each button displays a toast message when it is clicked.
  1. METHOD 1 is applied to the button1
  2. METHOD 2 is applied to the button2
  3. METHOD 3 is applied to the button3 and button4 
Here is the activity_main.xml code :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#292929"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BUTTON 1"
        android:textColor="#000000"
        app:backgroundTint="#FFFFFF"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.129" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BUTTON 2"

        android:onClick="btn2Click"

        android:textColor="#000000"
        app:backgroundTint="#FFFFFF"
        app:layout_constraintBottom_toTopOf="@+id/button3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button1"
        app:layout_constraintVertical_bias="0.304"
        tools:ignore="UsingOnClickInXml" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BUTTON 3"
        android:textColor="#000000"
        app:backgroundTint="#FFFFFF"
        app:layout_constraintBottom_toTopOf="@+id/button4"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button2"
        app:layout_constraintVertical_bias="0.515" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BUTTON 4"
        android:textColor="#000000"
        app:backgroundTint="#FFFFFF"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button3"
        app:layout_constraintVertical_bias="0.736" />
</androidx.constraintlayout.widget.ConstraintLayout>

And here is MainActivity.java :

package com.example.recyclearview;

import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // METHOD 1

        // initialize the button
        Button button1=findViewById(R.id.button1);

        //button click
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,"THIS IS BUTTON 1",Toast.LENGTH_SHORT).show();
            }
        });

        // METHOD 3
        Button button3=findViewById(R.id.button3);
        Button button4=findViewById(R.id.button4);

        //click listener
        button3.setOnClickListener(this);
        button4.setOnClickListener(this);

    }

    // METHOD 2

    public void btn2Click(View view){
        Toast.makeText(MainActivity.this,"THIS IS BUTTON 2",Toast.LENGTH_SHORT).show();
    }


    // METHOD 3
    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.button3:
                Toast.makeText(MainActivity.this,"THIS IS BUTTON 3",Toast.LENGTH_SHORT).show();
                break;
            case R.id.button4:
                Toast.makeText(MainActivity.this,"THIS IS BUTTON 4",Toast.LENGTH_SHORT).show();
                break;
        }
    }
}


Summery 

So there are 3 methods to perform button click in android. 
  • Use method 1 and method 2 for single button click
  • Use method 3 to perform multiple button click
  • Method 1 and method 3 is recommended way
So in that way you can perform button click in android.

Leave a comment if you had any queries regarding this post and I will reply as soon as possible. Anyway, if you enjoy reading my content, you can subscribe to my blog to receive all the latest updates. Happy Learning!

Don't forget to follow NP-X Coding on Instagram.