Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Android Onclick Event: How To Handle Button Clicks

In this tutorial we will experiment top methods to handle button onclick events in Android by providing examples with code and explanation. We will also elaborate what is the best to handle an onclick listener event, and how you can make your ap

When developing android application, often we deal with buttons and other views to provide different sort interacting features to the android user. Most of the application-developers use button to navigate through the application. So it’s very important to learn how you can code, to perform different type of activity by clicking on a specific button in your application.

If you have some experience with Java, then you already have pretty much good idea of the onclick events. It will be quite easy for you to understand all these concepts.

Before we jump into coding let’s discuss some of the concepts related to the event handling in Android. Event works as a way through, which data of user interaction with interacting components of your application, such button clicks can be collected. The event queue is used by the Android framework to maintain the events in the order of first-in-first-out also called as FIFO. We can take specific action in respond to these events as per our application.


  • Event Listeners:Can be thought of an object that can receive notification when any event occurs. There are different even listeners for listening to different event notification. An example is a view class , that has number of event listeners different events.
  • Registration of Event Listeners:When an Event Handler is registered with an Event Listener this process is called Event Registration. This registration is done so that when an event is fired , it is handled by event handler since it has already been registered.
  • Event Handlers: Event Handler is basically the method that actually handles the event.

Event Handler

Event Listener & Description

onClick()

OnClickListener()
The onclicklistener will be called when any widget like button, text, image etc is either clicked or touched or focused upon by the user. we use onClick() event handler to handle such onclick event.

onLongClick()

OnLongClickListener()
As precepted from the name , when any widget is clicked for a little longer then normal click this listener is called. To handle such events we use onLongClick handler.

onFocusChange()

OnFocusChangeListener()
As its name describes when the focus is lost by an widget, this event listener is called, the onFocusChange() handler is used to handle such sort of events.

Table 1: Event handler table

As part view class you can find many more even listeners such as onTouch(),onKey(),onMenuItemClick(),OnDragListener, OnHoverListener, etc, that can be used in your application, if you are intending to make some sophisticated Android application. I would recommend you to visit official documentation of Android Application development to see the full details. Here in this tutorial we will be working upon OnClickListener() event listener, all the others are pretty much the same, you will only need to call their specified method.

We will be handling button clicks through following methods as mentioned below!


  • Activity Implementing OclickListener
  • Inner Class
  • Anonymous Inner Class
  • Handling Onclick Button With Xml

Android onclick example: Activity Implementing OnclickListener

In this method our main activity, that is MainActivity.java class implements Onclicklistener interface. The OnclickListener interface is used by object of mainActivityto call some method or perform some activity when button is clicked. We just need to register click event with buttons and then implement the onClickListener call back methods. That mean we can perform any action that we may need, depending on our application specifications.

In short what the button needs is an object that should respond when onclick event is triggered.

Listing 1: onclick event triggered

  public class MainActivity extends Activity implements OnClickListener {
  ....
  public void oncreate(){
  ...
  button.setOnClickListner(this);}
  public void onClick(View v){
  }
  

Explanation to the code


  • button.setOnClickListner(this);

Here, the setOclickListener() methods takes argument of class that implements the OnclickListener Interface, By passing “this”, it also save us some small amount of memory!.In other word we simply register click event with button.

Now you may be thinking, that for all button we have only one OnclickListener call back method (a method that is executed when a button with which click event is registered). Well you are probably right button, with in this one method, we can respond to different events from different buttons. The example is also given How to deal with multiple buttons in proceeding section.

Problem with this method:

If you carefully examine this, you will come to know if you have many onclick events, then you will need to do further programming to handle all these onclick events. One more thing to be noted you cannot pass argument to the listener. So therefore it is not the most recommended method to be used to handle the onclick button events.

What if you still want to use the same method?

You can also use switch case to respond to different button, clicks , you can also find a nice example below.

Listing 2: main_activity.xml

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:paddingBottom="@dimen/activity_vertical_margin"
      android:paddingLeft="@dimen/activity_horizontal_margin"
      android:paddingRight="@dimen/activity_horizontal_margin"
      android:paddingTop="@dimen/activity_vertical_margin"
      tools:context=".MainActivity" >
      <Button
          android:id="@+id/button1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_alignParentTop="true"
          android:layout_marginTop="67dp"
          android:text="Click Me Dude!"
          android:textAlignment="center"
          tools:ignore="HardcodedText" />
   
  </RelativeLayout>
  

Graphical Representation of the xml file.

The figure below shows you how your application will look, for the specified code of xml that is shown above. You can modify this according to needs of your own application.

OUTPUT OF XML

Below is the screenshot, which is the result of the xml file given above. It simply contains a button, with a text on it.

Figure 1: output of xml

Here is the complete to code, mainActivity.java file to give an idea how we can respond to onclickeventlistener(). You can perform an operation in the overridden function according to your application specification, such as calling other activity by clicking on the button, or any other operation that you can thought of , but for simplicity we simply print a message to locate when the button is clicked.

Listing 2: MainActivity.java

  package com.mrboolapp;
  import android.os.Bundle;
  import android.app.Activity;
  import android.content.Intent;
  import android.util.Log;
  import android.view.Menu;
  import android.view.View;
  import android.widget.Button;
  import android.view.View.OnClickListener;
   
  public class MainActivity extends Activity implements OnClickListener {
   
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                          super.onCreate(savedInstanceState);
                          setContentView(R.layout.activity_main);
                          Button button = (Button) findViewById(R.id.button1);
                          
                          button.setOnClickListener(this);
                 }
              @Override
              public void onClick(View v) {
                          Log.d("MR.bool", "Button1 was clicked ");                       
              }
              @Override
              public boolean onCreateOptionsMenu(Menu menu) {
                          // Inflate the menu; this adds items to the action bar if it is present.
                          getMenuInflater().inflate(R.menu.main, menu);
                          return true;
              }
  }
  

Result of Code:

Now by just clicking on the button we get a message “button1 was clicked” in the logcat. As shown in the figure below, for all other class we have no result, since all have the same result and behave almost the same.

Figure 2: Logcat output

How to deal with multiple buttons while handling button by Implementing OclickListener?

Now, suppose you have multiple buttons, and you want handle, by Implementing OnclickListener interface. In this situation we can use a function getID(), through this we can identify which button was clicked and we can respond to each button, with help of switch(). Let’s now jump to the code and see how we can achieve this.

Listing 3: main_activity.xml

In this example you only need to drag and drop two buttons, to your xml layout and give them some ids and text you want to be on the buttons, that’s set.

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:paddingBottom="@dimen/activity_vertical_margin"
      android:paddingLeft="@dimen/activity_horizontal_margin"
      android:paddingRight="@dimen/activity_horizontal_margin"
      android:paddingTop="@dimen/activity_vertical_margin"
      tools:context=".MainActivity" >
   
      <Button
          android:id="@+id/button1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_alignParentTop="true"
          android:layout_marginTop="67dp"
          android:text="Click Me button1!”
          tools:ignore="HardcodedText" />
  <Button
          android:id="@+id/button1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_alignParentTop="true"
          android:layout_marginTop="67dp"
          android:text="Click Me button2!"
          tools:ignore="HardcodedText" />
   
   
  </RelativeLayout>
  


Listing 4: MainActivity.java

  package com.mrboolapp;
  import android.os.Bundle;
  import android.app.Activity;
  import android.util.Log;
  import android.view.Menu;
  import android.view.View;
  import android.widget.Button;
  import android.view.View.OnClickListener;
   
  public class MainActivity extends Activity implements OnClickListener {
              Button buttonOne,buttonTwo;
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                          super.onCreate(savedInstanceState);
                          setContentView(R.layout.activity_main);
                          buttonOne = (Button) findViewById(R.id.button1);
                          buttonTwo = (Button) findViewById(R.id.button2);
                          buttonOne.setOnClickListener(this);
                          buttonTwo.setOnClickListener(this);
              } 
              @Override
              public void onClick(View v) {
                          // TODO Auto-generated method stub
                          switch (v.getId()) {
                          case R.id.button1:
                                      Log.d("MR.bool", "Button1 was clicked ");
                                      break;
  case R.id.button2:
              Log.d("MR.bool", "Button2 was clicked ");
                                      break;
   
                          default:
                                      break;
                          }
              }
  @Override
              public boolean onCreateOptionsMenu(Menu menu) {
                          // Inflate the menu; this adds items to the action bar if it is present.
                          getMenuInflater().inflate(R.menu.main, menu);
                          return true;
              }}
  


Explanation to code:

The code, given below, if analysed, will shows that v.getId() function receives the id of the button that is clicked, and we compare the id with ids of the buttons that are being used, in the application. When the id matches with the id of the button, its code is executed. So suppose the user clicks on button2 so the code .d("MR.bool", "Button2 was clicked "); will be executed, hence the message can be seen in the logcat.

Listing 5: Message seen in the logcat

  switch (v.getId()) {
                          case R.id.button1:
                                      Log.d("MR.bool", "Button1 was clicked ");
                                      break;
  case R.id.button2:
              Log.d("MR.bool", "Button2 was clicked ");
                                      break;
   
                          default:
                                      break;
                          
  }}
  

Android onclick example: By Using Anonymous Inner Class

In this method our MainActivity.java class does not need to implement Onclicklistener interface. The OnclickListener interface is used by object of mainActivity, to call some method or perform some activity when button is clicked but, now this all will be done by using Inner class as you can see in the code below. Now we need our anonymous inner class (MrBoolHandler) to implement the OnClickListener Interface.

Listing 6: Inner Class

  public class MainActivity extends Activity {
  ....
  public void oncreate(){
  ...
  button.setOnClickListner(new MrBoolHandler());
  }
  class MrBoolHandler implements OnClickListener{
  } 
  public void onClick(View v){
  }
  

Explanation to the code

button.setOnClickListner(new MrBoolHandler());

As already discussed setOclickListener() methods takes argument of class that implements the OclickListner Interface. But in this method our inner class, which is MrBoolHandler implements the interface, so we need to pass the object of Mrboolhandler class.

When to use inner class onclick handler method:

When you want one class to handle all of yours button clicks, then you can simply make an inner class that is with in your main activity class to keep it private from other android class etc.

Listing 7: main_activity.xml

   
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:paddingBottom="@dimen/activity_vertical_margin"
      android:paddingLeft="@dimen/activity_horizontal_margin"
      android:paddingRight="@dimen/activity_horizontal_margin"
      android:paddingTop="@dimen/activity_vertical_margin"
      tools:context=".MainActivity" >
   
      <Button
          android:id="@+id/button1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_alignParentTop="true"
          android:layout_marginTop="67dp"
          android:text="Click Me Dude!"
          android:textAlignment="center"
          tools:ignore="HardcodedText" />
   
  </RelativeLayout>
  

Listing 8: MainActivity.java

  package com.mrboolapp;
  import android.os.Bundle;
  import android.app.Activity;
  import android.util.Log;
  import android.view.Menu;
  import android.view.View;
  import android.widget.Button;
  import android.view.View.OnClickListener;
   
  public class MainActivity extends Activity  {
              Button button;
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                          super.onCreate(savedInstanceState);
                          setContentView(R.layout.activity_main);
                          button = (Button) findViewById(R.id.button1);
                          
                          button.setOnClickListener(new MrBoolHandler());
              }
              class MrBoolHandler implements OnClickListener{
   
                          @Override
                          public void onClick(View v) {
                                      // TODO Auto-generated method stub
                                      Log.d("MR.bool", "Button1 was clicked ");
                                                  
                          }
              } 
   
              @Override
              public boolean onCreateOptionsMenu(Menu menu) {
                          // Inflate the menu; this adds items to the action bar if it is present.
                          getMenuInflater().inflate(R.menu.main, menu);
                          return true;
              }
  }
   

Handling Button Clicks Using Anonymous Inner Class:

In this method, we don’t need any class to be created, we simply create anonymous inner class, which cannot be referred, but the class is created and we can use the overloading methods easily with this, making our coding a bit quicker. It goes well with application that have single control, in case you have multiple button, then using Anonymous Inner Class would not be a good choice, you would be either make use of copy/paste or may use inner class method as discussed above. The advantage with Anonymous Inner Class is that you can pass argument to the event handler and can directly access the other data of the activity class.

Lets have a look at the code of the Anonymous Inner Class now.

Listing 9: Anonymous Inner Class code

  public class MainActivity extends Activity {
  ....
  public void oncreate(){
  ...
  button.setOnClickListner(new OnClikcListener(){
  @Overrides
  public void onClick(View v){
  }
  });
  }
  

The xml file still remains the same as we have used for the other examples. One thing to be noted here is that we haven’t mentioned anything about the mainifiest.xml file. It is because we have not made any changes to that file. The file remains as it is at the time we’ve created our application. So therefore we have not mentioned, the coding for you develop your own custom application, you may have different needs and essentials due to which you will need to deal with your mainifiest.xml file.

Listing 10: main_activity.xml

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:paddingBottom="@dimen/activity_vertical_margin"
      android:paddingLeft="@dimen/activity_horizontal_margin"
      android:paddingRight="@dimen/activity_horizontal_margin"
      android:paddingTop="@dimen/activity_vertical_margin"
      tools:context=".MainActivity" >
   
      <Button
          android:id="@+id/button1"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_alignParentTop="true"
          android:layout_marginTop="67dp"
          android:text="Click Me Dude!"
          android:textAlignment="center"
          tools:ignore="HardcodedText" />
   
  </RelativeLayout>
   
  

Listing 11: MainActivity.java

  package com.mrboolapp;
  import android.os.Bundle;
  import android.app.Activity;
  import android.util.Log;
  import android.view.Menu;
  import android.view.View;
  import android.widget.Button;
  import android.view.View.OnClickListener;
  public class MainActivity extends Activity  {
              Button button;
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                          super.onCreate(savedInstanceState);
                          setContentView(R.layout.activity_main);
                          button = (Button) findViewById(R.id.button1);
                          
                          button.setOnClickListener(new OnClickListener() {
                                      
                                      @Override
                                      public void onClick(View v) {
                                                  // TODO Auto-generated method stub
                                                  Log.d("MR.bool", "Button1 was clicked ");
                                      }
                          });
              } 
   
              @Override
              public boolean onCreateOptionsMenu(Menu menu) {
                          // Inflate the menu; this adds items to the action bar if it is present.
                          getMenuInflater().inflate(R.menu.main, menu);
                          return true;
              }
   
  }
  



Here the line of the code that needs to be discussed is given below:


  button.setOnClickListener(new OnClickListener() {
                                      @Override
                                      public void onClick(View v) {
                                                  // TODO Auto-generated method stub
                                                  Log.d("MR.bool", "Button1 was clicked ");
                                      }
                          });
  

The code shows that we neither need to implement the onclicklistener interface, nor we need to create separate class, all these is simply done by the use of Anonymous Inner Class. And then by the help of onclick() method, we can perform any operation when the event is fired. In other words the onclick event is handled. One thing to be noted, that is if your application as more then one buttons, you will every time need to use this method, in this case, you will need to do extra coding. So keep in mind the features of the application, you can make use of any of these methods for onclick listeners.

Xml Androd:oclick attribute: To Handling Onclick Button Events

To handle onlclick button event with xml, we simple use the andorid:OnClick attribute that directly handles the button events without the need of implementing the OnClickListener Interface.The andorid:OnClick was added to android views for the API level 4.0. This method is more often used, in simple cases, where as in complex cases would not want to mix the code, the view that trigger the button event with variables and methods that handles the event.

Let’s now look at the example code, to get some better understanding of the concept. Below is the sample code for button view that uses android:OnClick attribute.

Listing 12: code of android:OnClick Attribute

  <Button android:id="@+id/button3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Click me!"
      android:onClick="mrBool" />
  

Now when the button with id button3 is clicked, the specified function in MainActivity.java will be executed.

Let’s look at the MainActivity.java file and see how we implement this.

Listing 13: MainActivity.java

  package com.mrboolapp;
  import android.os.Bundle;
  import android.app.Activity;
  import android.util.Log;
  import android.view.Menu;
  import android.view.View;
  import android.widget.Button;
  import android.view.View.OnClickListener;
   
  public class MainActivity extends Activity  {
              Button button;
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                          super.onCreate(savedInstanceState);
                          setContentView(R.layout.activity_main);
                          button = (Button) findViewById(R.id.button1);  
              } 
              
                                      public void mrBool(View v) {
                                                  
  Log.d("MR.bool", "Button1 was clicked ");
                                      }
                          
              @Override
              public boolean onCreateOptionsMenu(Menu menu) {
                          getMenuInflater().inflate(R.menu.main, menu);
                          return true;
              }
   
  }
  


Explanation to the code:

While using android:OnClick attribute, one should be kept in mind, that is the function, we use to handle the onclick button, event must have an object of View class as an argument , only then we can respond to onclick events. This is because we are dealing with views and listeners of the view class so with accessing the object of view class we can not handle the onlclick events. The line of code, shown below:

  public void mrBool(View v) {  
  Log.d("MR.bool", "Button1 was clicked ");
                                      }
  

Conclusion:

Although there are different types of event listeners for different widgets, each one has its own specifications, but the basic concept of all of the event listeners remains the same. Learning onclick button listeners and other topics related to this is very essential for the beginners to be considered, as these servers as controllers of the application that you are building. Once you’ve learnt the above examples and understood them, it will not be hard for you to apply it on the event listeners. Some of the events that are related to pickers, menus and spinner widgets are little different than what we have described, but the also follow the basic rules that we have mentioned in this article. Hope this will help you in your android development. Go ahead and use all the event listeners to get a hands on practice too.



computer science Graduate :Ceo at www.gigsclerk.com (Best Marketplace to Buy and sell service online from 2$-100$ ) and www.trustingeeks.com. Interested in programming, online buissiness. Android development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login