Android: OnClickListener tutorial

Introduction

One of the most basic tasks you will run up against when starting programming for Android is how to implement onclick handlers. In this post I will show you the different way’s of creating onclick handlers for your app.

Onclick handlers are used to execute a part or code when a button or other part of the user interface is touched (clicked). These onclick handlers are a instance of a class that you need to specify. In short it’s a object with a piece of executable code that get’s triggered by a user interaction.

First thing to know is that an onclick handler implements the interface View.OnClickListener. You need to create a class that implements the interface because you need to add your code that get’s executed. Luckily for us this is very easy to do in Java.

Inline

Our first method of creating a onclick handler is by creating the class inline. This method is very quick but does leave a bit of a mess. I Would only recommend using this for small blocks of code.

findViewById(R.id.button1).setOnClickListener( new View.OnClickListener() {
	@Override
	public void onClick(View v) {
		//Inform the user the button has been clicked
		Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show();  
	}
});

Private variable

The second way of creating a onclick handler is by adding a private variable to our class. As I mentioned before an onclick handler is just a instance of a class, so it can be stored in a variable. This method is very suited for larger blocks of code.

public class MyActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.mylayout);
		findViewById(R.id.button1).setOnClickListener(mButton1_OnClickListener);
	}	
	
	//On click listener for button1
	final OnClickListener mButton1_OnClickListener = new OnClickListener() {
	    public void onClick(final View v) {
			//Inform the user the button has been clicked
			Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show();         		
	    }
	};
}

One of the benefits of using a private variable is that you can reuse it for other views. The onClick method passes the clicked view as an variable, you can use a switch statement to determine which view was clicked.

public class MyActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.mylayout);
		findViewById(R.id.button1).setOnClickListener(mGlobal_OnClickListener);
		findViewById(R.id.button2).setOnClickListener(mGlobal_OnClickListener);
	}	
	
	//Global On click listener for all views
	final OnClickListener mGlobal_OnClickListener = new OnClickListener() {
	    public void onClick(final View v) {
	        switch(v.getId()) {
				case R.id.button1:
					//Inform the user the button1 has been clicked
					Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show();         		
				break;
				case R.id.button2:
					//Inform the user the button2 has been clicked
					Toast.makeText(this, "Button2 clicked.", Toast.LENGTH_SHORT).show();         		
				break;
	        }
	    }
	};
}

Xml reference

The Android platform also comes with a binding method of binding onclick handlers to layout files. This might be the cleanest solution, but does come with a drawback that it can only be used for layouts that are inflated for an activity. Now a day’s it’s recommended to use fragments for parts of your user interface in your Android apps, this method can not be used with fragments. So it’s becoming less used. Still if you have activities that do not use fragments this can be a good solution.

In our activity class we add the onclick method.

//On click event for button1
public void button1OnClick(View v) {
	//Inform the user the button has been clicked
	Toast.makeText(this, "Button1 clicked.", Toast.LENGTH_SHORT).show();            	
}

In the layout file we add a reference to the onclick handler in the activity. The app will automatically bind the onclick method to the view (in this case button1)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button1"
            android:onClick="button1OnClick"/>
</LinearLayout>

Conclusion

And that’s it. Using onClickListeners is easy when you know how. By choosing the appropriate solution for each task you will find you can quickly write clean code.

For more information see the developer online reference:
http://developer.android.com/reference/android/view/View.OnClickListener.html

Edit note 06-apr-2013: This original post was written in November 2011 and I was just beginning to learn the Android framework. The post was only a redirect to an other tutorial I wanted to share. But that tutorial is now outdated and lacked some information, so I decided to write my own post on how to use onClickListeners. My original blog post is removed and what you are now reading is the newly written post. I Hope it will be useful to my readers.

avatar

About Martin

Martin van Zuilekom has 12 years experience working as a professional software developer. Main focus points are user interface design and framework architecture. Follow Martin on Google plus

3 comments on “Android: OnClickListener tutorial

  1. The code examples look good it the writing quality is atrocious. It’s hard to believe an article so littered with grammatical errors is a top search result.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>