Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
Event Handling in Android
Next article icon

Handling Click Events in Button in Java Android

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:



Button_ClickListener



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

After_Clicking_Button




Next Article
Event Handling in Android

V

Vijayaraghavan
Improve
Article Tags :
  • Android
  • Java-Android

Similar Reads

  • Event Handling in Android
    Events are the actions performed by the user in order to interact with the application, for e.g. pressing a button or touching the screen. The events are managed by the android framework in the FIFO manner i.e. First In - First Out. Handling such actions or events by performing the desired task is c
    5 min read
  • How to Handle IME Options on Action Button Click in Android?
    We often observe that a keyboard pops up when we try to enter input in editable fields. These inputs are generally accepted by the application for performing specific functions and display desired results. One of the most common editable fields, that we can see in most of the applications in daily u
    3 min read
  • How to Change Button Font in Android?
    A Button in Android is a UI element provided to a user to click to perform a certain action. A text can be set inside the button to name it. However, this text can be seen in a particular font only which is set by default. So in this article, we will show you how you could change the Button text fon
    2 min read
  • How to Center a Button in a Linear Layout in Android?
    LinearLayout is a view group that aligns all children vertically or horizontally in a single direction. The "android:orientation" parameter allows you to define the layout direction. A button is a component of the user interface that can be tapped or clicked to carry out an action. Nowadays while de
    2 min read
  • Double-Tap on a Button in Android
    Detecting a Double Tap on Button in Android i.e. whenever the user double taps on any Button how it is detected and according to the Button a response can be added corresponding to it. Here an example is shown in which the double tap on the Button is detected and the corresponding to it response is
    3 min read
  • How to Create New ImageView Dynamically on Button Click in Android?
    In this article, we are going to implement a very important feature related to ImageView. Here we are going to add ImageView dynamically. We will be just changing the background color. Whenever we click on a button a new ImageView will be created. So here we are going to learn how to implement that
    3 min read
  • How to Change Background Image by Button Clicking Event in Android?
    Background Images play an important role in the beautification of any application. Hence, most social media applications like WhatsApp, Messenger provides this as a part of their feature to their users. So, keeping this in mind we will be going to develop an android application in which background i
    3 min read
  • How to Enable/Disable Button in Android?
    The Enable/Disable Feature is used in many Android apps so the basic use of that feature is to prevent the user from clicking on a button until they will add all the required fields that have been asked. We are considering an example of email and password if the user has entered the email and passwo
    3 min read
  • Android Floating Action Button in Kotlin
    Floating action buttons are used in android applications to indicate the user for some priority-based task. Generally floating action buttons in the android applications are found aligned to the bottom end of the application. In this article, we will take a look at How to implement the Floating Acti
    4 min read
  • How to Draw Border on Event of Click in Android with Kotlin?
    Sometimes we want to display to the users that they have clicked an item by showing a border on the item. So, for this, we need to create two drawable resource files, one for the normal background of the item and another for the border. A sample video is given below to get an idea about what we are
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences