How to use an OnClickListener In Java

You can also declare the click event handler programmatically rather than in an XML layout. This event handler code is mostly preferred because it can be used in both Activities and Fragments.

There are two ways to do this event handler programmatically :

  • Implementing View.OnClickListener in your Activity or fragment.
  • Creating new anonymous View.OnClickListener.


Layout for all the cases will be same which is mentioned below as acitivity_main.xml file:

activity_main.xml
<RelativeLayout
    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"
    tools:context="com.example.sample.MainActivity" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button_send" />
</RelativeLayout>


1. Implementing View.OnClickListener in your Activity or fragment

To implement View.OnClickListener in your Activity or Fragment, you have to override onClick method on your class.

  • Firstly, link the button in xml layout to java by calling findViewById() method. R.id.button_send refers the button in XML.

mButton.setOnClickListener(this); means that you want to assign listener for your Button “on this instance” this instance represents OnClickListener and for this reason your class have to implement that interface.

MainActivity code:

MainActivity.java
package com.example.handling_button_java;

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


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button mButton;
    private TextView mTextView;

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

        mButton = findViewById(R.id.button_send);
        mButton.setOnClickListener(this);

        mTextView = findViewById(R.id.text_after);
    }

  
      // Override the onClick Method and return the result 
      // Accordingly
    @Override
    public void onClick(View view) {
       if (view.getId()==R.id.button_send) {
         if (mTextView != null) {
           mTextView.setText("This is the after Result");
         }
       }
    }
}


If you have more than one button click event, you can use switch case to identify which button is clicked.

2. Creating Anonymous View.OnClickListener

Link the button from the XML by calling findViewById() method and set the onClick listener by using setOnClickListener() method.

MainActivity code:

MainAcitvity.java
package com.example.handling_button_java;

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


public class MainActivity extends AppCompatActivity {

    private Button mButton;
    private TextView mTextView;

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

        // Putting vaules in mButton and mTextView
        mButton = findViewById(R.id.button_send);
        mTextView = findViewById(R.id.text_after);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view)
            {    
                  // Operations Performed On Clicking the Button 
                  // Are Done Here
                mTextView.setText("This is the after Result");
            }
        });
    }
}


setOnClickListener takes an OnClickListener object as the parameter. Basically it’s creating an anonymous subclass OnClickListener in the parameter. It’s like the same in java when you can create a new thread with an anonymous subclass.

Output of the Programs:



After Clicking the Button the Result Will be as mentioned below:




Handling Click Events in Button in Java Android

Click Events are one of the basic operations often used in Java Android Development to create Java Android Applications. In this article, we will learn about how to Handle Click Events in Button in Android Java.

Similar Reads

Methods to Handle Click Events in a Button

There are 2 ways to handle the click event in the button...

Onclick in XML layout

When the user clicks a button, the Button object receives an on-click event. To make click event work add android:onClick attribute to the Button element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method....

Using an OnClickListener

You can also declare the click event handler programmatically rather than in an XML layout. This event handler code is mostly preferred because it can be used in both Activities and Fragments....

Contact Us