How to handle events in Android

27 Oct 2013, 04:04 PM

Introduction

There are several ways to handle event in android mobile application development. Events handling is used for interaction with users. In this blog I will explain how you can register your event handler for different controls. I am using Button click event as a use case in this blog and you can apply same technique for different events. Java provides a different ways to handle event and I will explain all these ways one by one.

Handle event in Layout

It is a very simple way to set event listener of the button from the layout xml file. A View class is the basic building block of user interface in android. It is the base class for widgets that are used to create UI. A Button is also a sub class of View. The View class has different properties and we can use OnClick property to bind with click event hanlder.

 <Button
   android:id="@+id/btnType2"
   android:onClick="onBtnSaveClick"
   android:text="Save" />
    

The android:onClick="onBtnSaveClick" property is used to bind event handler for click event. The method must correspond the public method that take View as a parameter in the class that is using that layout xml file.

Let’s add the public method in your class.

 public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);

    }

    public void onBtnSaveClick(View v) {
		    Toast.makeText( getApplicationContext(), "Clicked on save Button", 
                            Toast.LENGTH_SHORT ).show();
	}
 }
    

This approach uses the “delegation pattern” that allows multiple buttons to have their own handlers or share a one handler. The bigger problem with this approach is that you can only register click event and if you want to register any other event listener then you will have to go with other approaches.

Inline Event Listener

You can also use the inline event handler for your events. Write inline anonymous method for handling the event. This approach will need to register separate inline handler for each control. Create a button is the layout and write inline handler in the class that is using this layout.

 <Button
    android:id="@+id/button1"
    android:text="Save" />

Now after creating button in layout write code to find the button in the layout and then add click listener for it.

 public class InlineEventActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inline_event);
		
        Button button = (Button)findViewById(R.id.button1);

        button.setOnClickListener(new View.OnClickListener() {
	
            @Override
            public void onClick(View v) {
                Toast.makeText( getApplicationContext(), "Clicked on save Button", 
                    Toast.LENGTH_SHORT ).show();
			}
		});
		
	}
        
 }

The method setOnClickListener method is used to register handler for it. Pass View.OnClickListener as an parameter in this method.

Implements OnClickListener Interface

There is another way to register the event handler by implementing the appropriate interface for it. For registering click events of the activity implement the OnClickListener interface. Add two buttons in the layout and check how we will handle click event for multiple controls.

 <Button
     android:id="@+id/button1"
     android:text="Button 1" />

 <Button
     android:id="@+id/button2"
     android:text="Button 2" />
    
    

Override your class with the OnClickListener interface using “implements OnClickListener” statement that is the way to implement interface in java.

 
 import android.view.View.OnClickListener;

 public class UsingInterfaceActivity extends Activity implements OnClickListener {

    Button button1;
    Button button2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_using_interface);
		
        button1 = (Button)findViewById(R.id.button1);
        button2 = (Button)findViewById(R.id.button2);
		
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);

    }
        
    @Override
    public void onClick(View v) {
        
        if(v == button1){
            
            Toast.makeText( getApplicationContext(), "Clicked on Button 1", 
								Toast.LENGTH_SHORT ).show();
        
        }
        else if(v == button2){

            Toast.makeText( getApplicationContext(), "Clicked on Button 2", 
								Toast.LENGTH_SHORT ).show();
        
        }
    }

 }
    
    

Find all your controls using findViewById() method and set the click listener using setOnClickListener(this) statement. Pass this as parameter to the setOnClickListener method means current class will handle the click event. When user clicks on the Button1 or Button2 the controls pass to onClick(View v) method of the current class where you can perform action of each button.

Event Listener using Variable

It is the variation of the other technique. Create the variable of the OnClickListener class and handler the click event in it. Then assign that variable to the click listener of the button.

 <Button
        android:id="@+id/btnType4"
        android:text="Button" />
    

In your activity class simply declare the variable OnClickListener buttonClickEvent and assign that variable to button that’s event you want to handle here. You can assign the same variable to multiple buttons event listener.

        
 public class VariableActivity extends Activity {
        
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_variable);
        
        Button button = (Button)findViewById( R.id.btnType4);
        
        button.setOnClickListener(buttonClickEvent);
    }
        
    OnClickListener buttonClickEvent = new OnClickListener() {
        
        @Override
        public void onClick(View v) {

			Toast.makeText(getApplicationContext(),"Click on Buttom", 
							Toast.LENGTH_SHORT).show();
        
        }
        
    };

 }
    

Handle through Listener Class

There is another variation for handling event is to create a class for the Event handler and Implement it with OnClickListener interface as we did in previous technique.

public class VariableActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
        
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_variable);

    Button button = (Button)findViewById( R.id.btnType4);

    button.setOnClickListener(new MyButtonListener());
        
  }
        
  class MyButtonListener implements OnClickListener {
        
    public void onClick(View v) {
        
        Toast.makeText( getApplicationContext(), "Clicked on My Button", 
		    		  					Toast.LENGTH_SHORT ).show();
    }
  }

}

Create a class MyButtonListener implements OnClickListener and handle click event in it. Then assign that class to the button click listener using statement like this button.setOnClickListener(new MyButtonListener()).

Handle using override performClick method

There is another way to handle the event form the code. If you are dynamically adding controls in your UI, you can also use this approach for handling the event. Suppose you have Linear Layout in your UI in which you will add the controller dynamically from code.

   <LinearLayout
        android:id="@+id/linearLayout1"
        android:orientation="vertical" >

    </LinearLayout>

Create button variable in the code file and override the performClick() method to handle the click event using inline extension. Add this button into the Linear layout using layout.addView(button) method.

 @Override
 protected void onCreate(Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
	    	
        Button button = new Button(this){
        
            @Override
            public boolean performClick() {

                Toast.makeText(getApplicationContext(), "Clicked on Button", Toast.LENGTH_SHORT).show();

                return false;
        
            }
        
        };

        button.setText("Auto button");

        LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout1);

        layout.addView(button);

 }

    

These are the different techniques that you can use for handling the events in Android development. You can also add some more variation in these techniques as per your design requirement. But these are more than enough to use.

About Blog
This blog explains the different ways for registering event in android application development.

Date 27 Oct 2013, 04:04 PM
Views 3,468
;