Android Tutorial: How to implement an OnClickListener

How to implement an onclicklistener

Introduction to OnClickListeners

One of the most basic tasks you will run up against when starting programming for Android is how to implement an OnClickListener. In this post I will show you the different ways of creating OnClickListeners for your app.

Onclick handlers are used to execute a part of code when a button or other part of the user interface is touched (clicked). These onclick handlers are an instance of a class that you need to specify. In short it’s an 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 so you can add your code that get’s executed. Luckily for us this is very easy to do in Java.

Inline

Our first method of creating an OnClickListener 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 an OnClickListener is by adding a private variable to our class. As I mentioned before an OnClickListener is just an 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 a 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 OnClickListeners 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.

Example project

An example project for this article can be found on Github.
https://github.com/MartinvanZ/OnClickExample

More information

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

Leave a Reply

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