Handling Click Events in Button in Java Android
Last Updated :
06 Jan, 2025
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.
Methods to Handle Click Events in a Button
There are 2 ways to handle the click event in the button
- Onclick in XML layout
- Using an OnClickListener
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.
Note: If you use this event handler in your code, make sure that you have that button in your MainActivity. It won’t work if you use this event handler in a fragment because the onClick attribute only works in Activity or MainActivity.
Example:
XML Button:
<Button xmlns:android="http:// schemas.android.com/apk/res/android"
android:id="@+id/button_sead"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"
/>
In MainActivity class
/** Called when the user touches the button */
public void sendMessage(View view)
{
// Do something in response to button click
}
Example Implementation of the above Method:
In this Example on Clicking the button the text will be displayed and we are using an extra empty text TextView created beforehand:
MainActivity.java
package com.example.handling_button_java;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendMessage(View view){
// All the Operations can be done Here.
final TextView text=findViewById(R.id.text_after);
text.setText("This is the after Result");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="160dp"
tools:layout_editor_absoluteY="44dp"
android:onClick="sendMessage"
android:layout_gravity="center"
/>
<TextView
android:id="@+id/text_after"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Make sure that your sendMessage method should have the following :
- Be public
- Return void
- Define a View as its only parameter (this will be the View that was clicked)
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.
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:

Similar Reads
Android Architecture
Android architecture contains a different number of components to support any Android device's needs. Android software contains an open-source Linux Kernel having a collection of a number of C/C++ libraries which are exposed through application framework services. Among all the components Linux Kern
5 min read
Architecture of 8085 microprocessor
A microprocessor is fabricated on a single integrated circuit (IC) or chip that is used as a central processing unit (CPU).The 8085 microprocessor is an 8-bit microprocessor that was developed by Intel in the mid-1970s. It was widely used in the early days of personal computing and was a popular cho
11 min read
States of a Process in Operating Systems
In an operating system, a process is a program that is being executed. During its execution, a process goes through different states. Understanding these states helps us see how the operating system manages processes, ensuring that the computer runs efficiently. Please refer Process in Operating Sys
11 min read
Android Tutorial
In this Android Tutorial, we cover both basic and advanced concepts. So whether you are a fresher (graduate) or an experienced candidate with several years of Android Development experience, you can follow this Android tutorial to kick-start your journey in Android app development. Our Android Tutor
15+ min read
Activity Lifecycle in Android with Demo App
In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when
9 min read
Introduction to Android Development
Android operating system is the largest installed base among various mobile platforms across the globe. Hundreds of millions of mobile devices are powered by Android in more than 190 countries of the world. It conquered around 71% of the global market share by the end of 2021, and this trend is grow
5 min read
Android UI Layouts
Layouts in Android define the user interface and hold UI controls or widgets that appear on the screen of an application. Every Android application consists of View and ViewGroup elements. Since an application contains multiple activitiesâeach representing a separate screenâevery activity has multip
5 min read
Top 50 Android Interview Questions and Answers - SDE I to SDE III
A Linux-based open-source OS, Android was created by Andy Rubin and became one of the most popular smartphone operating systems. With 71 percent of the market share worldwide, Android is on top. Because it is on top in the smartphone OS, Android development is always in demand. If you are seeking a
15+ min read
What is Intent in Android?
In Android, it is quite usual for users to witness a jump from one application to another as a part of the whole process, for example, searching for a location on the browser and witnessing a direct jump into Google Maps or receiving payment links in Messages Application (SMS) and on clicking jumpin
4 min read
Components of an Android Application
There are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file which contains the description of each component and how they interact. The manifest file also contains the appâs metadata, its hardware confi
3 min read