Handling click events on Android

In this tutorial, we will learn about handling click events on Android.

There are 2 ways to handle click events of a button on Android –

  1. onClick in XML layout
  2. Using an onClickListener in Java

onClick in XML layout

We specify the onClick attribute in a button, in XML layout. To do this, we first create a button in the XML layout and then we add an attribute “android:onClick” to the button. The value given to this attribute is the name of the method that’s defined in the MainActivity.

Make sure there’s a button like this in XML –

    xmlns:android="http:// schemas.android.com/apk/res/android"

And also, make sure there’s a method named ‘calculate’ (or any other name that you have given to your method in MainActivity.
Something like this –

//Method in MainActivity
public void calculate(View view)
    //Do something when the button is clicked

Note – The method takes View as a parameter.

onClickListener in Java

This way is usually preferred by most developers. Because when we use onClickListener , it can be implemented in both Activity and Fragments. But when we use XML way, we can only implement it in Activity or MainActivity.
We have to override onClick method on our class that is created.
Then, we link the button from the XML part to the Java class by using findViewById() method. This method returns a View which can then be type-casted to whatever view is needed.
R.id.button1 refers to the button that we had created in our XML file.

The XML file will be something like this –

<?xml version="1.0" encoding="utf-8"?>
    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"
    tools:context="com.example.sample.MainActivity" > 
        android:id="@+id/button1" /> 

And the MainActivity will look something like this –

public class MainActivity extends AppCompatActivity { 
    private Button mButton; 
    protected void onCreate(Bundle savedInstanceState) 
        //Create a button
        Button button = (Button)findViewById(R.id.button_send); 
        button.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View view) 
                //Make something happen 
                //when the button is clicked

We pass an onClickListener object to the method setOnClickListener. We then override the onClick method inside the onClickListener object. And we input code of whatever has to be done inside the onClick method.

So, this was a tutorial on how to take action when a button is clicked in Android. If you have any doubts on Handling click events on Android, feel free to leave a comment and we’ll get back to you.

Read more similar articles –

Leave a Reply

Your email address will not be published. Required fields are marked *