Different Ways To Handle Clicks

When I first started learning Android, I found it a little confusing because there are often many different ways to accomplish a single task.  In my case, I did not have a strong background in Java, otherwise it probably would have been easier for me to look at code samples an recognize these variations.

The most obvious example of alternative approaches to solving a single problem seems to be the various ways you can handle button clicks.  As far as I know, there are four different ways to add listeners for handling button clicks.  If you know of other ways, please post a comment and share them with us.

Here's a simple application that demonstrates four approaches to handling button clicks. When you click on any of the buttons, an alert will show up on the screen. There are two files of interest.  The first is the main xml layout file, which has four buttons in it.  This code should look familiar to you, except for the last button.  A new feature was added in Android 2.1 (API Level 7) which allows you to specify an onClick listener from within the xml layout file.

 

Here's the xml layout file for our sample application...

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <Button android:text="Inner Class (btn1)" android:id="@+id/Button01"

        android:layout_width="fill_parent" android:layout_height="wrap_content">

    </Button>
    <Button android:text="Anonymous Inner Class (btn2)"

        android:id="@+id/Button02" android:layout_width="fill_parent"

        android:layout_height="wrap_content">

    </Button>
    <Button android:text="Implementing an Interface (btn3)"

        android:id="@+id/Button03" android:layout_width="fill_parent"

        android:layout_height="wrap_content">

    </Button>
    <Button android:text="Calling From XML Layout (btn4)"

        android:id="@+id/Button04" android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:onClick="btn4Listener">

     </Button>
</LinearLayout>

 

And here's the main class for our application...

 

package com.remwebdevelopment.samples.eventhandlers;



import android.app.Activity;


import android.os.Bundle;


import android.view.View;


import android.widget.Button;


import android.widget.Toast;



public class Main extends Activity implements View.OnClickListener {


  @Override


  public void onCreate(Bundle savedInstanceState) {


      super.onCreate(savedInstanceState);


      setContentView(R.layout.main);


       


      //method 1 - uses an inner class named btn1Listener...


      Button btn1 = (Button)findViewById(R.id.Button01);


      btn1.setOnClickListener(btn1Listener);


       


      //method 2 - use an anonymous inner class as a listener...


      Button btn2 = (Button)findViewById(R.id.Button02);


      btn2.setOnClickListener(new View.OnClickListener() {


          @Override


          public void onClick(View v) {


              showToastMessage("You clicked btn2 - uses an anonymouse inner class");


          }


      });


       


      //method 3 - note that this class implements


      //the View.OnClickListener interface


      //which means that we must implement the onClick()


      //method (which you'll find below)..


      Button btn3 = (Button)findViewById(R.id.Button03);


      btn3.setOnClickListener(this);


       


      //method 4 - look at the method btn4Listener() below       


  }


   


  //here's the inner class used as a listener for btn1...


  private View.OnClickListener btn1Listener = new View.OnClickListener() {


      @Override


      public void onClick(View v) {


        showToastMessage("You clicked btn1 - uses an inner class named btn1Listener");


      }


  };


   


  //here's a method that you must have when your activity implements the


  //View.OnClickListener interface...


  @Override


  public void onClick(View v) {


      showToastMessage("you clicked on a btn3, which uses this Activity as the listener");


  }


   


  //here's the handler for btn4 (declared in the xml layout file)...


  //note: this method only works with android 2.1 (api level 7), it must be public and


  //must take a single parameter which is a View


  public void btn4Listener(View v) {


          showToastMessage("You clicked btn4 - listener was set up in the XML layout");


  }


     


  private void showToastMessage(String msg){


      Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);


      toast.show();


  }



}

10 Comments - Average Rating:4.6

Comments:
very good
Rating: 5
Date Posted: November 3rd, 2011


Do I understand this correct?
If you need backward compatibility then you implement method 2
else method 4 provides the bets readability?
Rating: 4
Date Posted: October 27th, 2011


There's actually a sixth way:

class Btn6 implements View.OnClickListener {

@Override
public void onClick(View v) {
showToastMessage("You clicked btn6 - uses a named class Btn6");

}

}

Rating: 4
Date Posted: October 8th, 2011


The posting for sure helped. But I was just wondering if you could shed some light so as to when to use which of these methods.
Rating: 4
Date Posted: June 20th, 2011


Actually you can do that since Android 1.6 :P
Look here : http://developer.android.com/reference/android/widget/Button.html
Rating: 4
Date Posted: February 25th, 2011


THANK YOU!!! It's taken me three days to figure this out, and you showed me EXACTLY what I needed to know. WELL DONE!
Rating: 5
Date Posted: December 7th, 2010


awesome???
i already said too.outstanding
Rating: 5
Date Posted: July 15th, 2010


The ability to add the android:onClick attribute to xml files was added in Android 1.6 (API lever 4).
Rating: 5
Date Posted: May 20th, 2010



RECENT ARTICLES