How To Add Click Listener in Android

What is OnClickListener in Android?

In Android, OnClickListener is an interface that has a method OnClick(View v) that is called when a component or element is clicked. It is very easy to understand how click listener works. In today’s blog I will show you how can we add click listener to our Android application.

How To Add Click Listener In Android?

There are two ways of adding click listener in Android. Firstly, by adding the onClick attribute to the component in the XML layout. The value of the attribute must be the name of the method you want to call. For example, you have a method saySomething(), in the XML layout the attribute must be android:onClick=”saySomething”. Otherwise it wouldn’t work.

<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_send"
    android:onClick="saySomething" />

In the activity class, the code should be like this:

public void saySomething(View view) {
    //your codes
    //for example,
    System.out.println("Something");
}

Secondly, is by doing it programmatically. In the activity class, after you instantiated the component you can use the setOnClickListener and create an OnClickListener object. For example,

Button button = (Button) findViewById(R.id.button_send);
button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        System.out.println("Something");
    }
});

That’s it for this blog. For more information about Android development go here. I hope it helped, thank you!

Leave a Comment

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