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();


  }



}

20 Comments - Average Rating:4.5

Comments:
i want to handle two button activity with a third button , how can i solve my problem. plz help me...
like that
i have -- 1 button for web, 2nd for vedio
and third for search
when i clicked on web and after then clicked on search button it search web
Rating: 2
Date Posted: September 10th, 2013


Nice article on the different ways to handle a Button Click, you may also want to check this video that explains the same concept in the most fantastic way
http://martin.cubeactive.com/android-onclicklitener-tutorial/#comment-943
Rating: 5
Date Posted: July 17th, 2013


How does the method 4 work in a class in which View.OnClickListener is not implemented?
Rating: 4
Date Posted: August 29th, 2012


An inner class definition must still use the "class" declaration. Your method for btn 1 is, I believe, just an alternate implementation that makes use of an anonymous inner class.
Rating: 4
Date Posted: August 27th, 2012


itz rely vry helpful 4 me
it rely work well
thnx
Rating: 5
Date Posted: June 25th, 2012


I got it

Button bt6 = (Button) findViewById(R.id.btn6);
bt6.setOnClickListener(new Btn6());

:)

Rating: 5
Date Posted: June 19th, 2012


How do you call the Btn6 check the comments???
Rating: 5
Date Posted: June 19th, 2012


Thanks, this was very helpful! Now why is this article so much clearer than the Android SDK dev guide?
Rating: 5
Date Posted: May 30th, 2012



RECENT ARTICLES