«

»

Feb 14

Print this Post

Implementing Listeners in your Android/Java application

I’ve seen many people asking how to implement Listeners in their applications. Implementing a Listener is quite easy. There are 3 ways to implement an Listener and the have their advantages and disadvantages.

The tree way to implement Listeners are

  • Inline Implementation
  • Using the implements keyword
  • By using variables

We’ll use our good old LoginExample application, created in previous tutorial which can be found at Android: Your first Android Application.

 

Inline Implementation

The first way, to implement an listener is by using Inline Implementation. In Inline Implementations we create an anonymous listener, define and pass it the the setLisener functions in the same step.

We did this already in our First Android Application Tutorial.

package com.tseng.examples;

...

public class LoginExample extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

	...
        
        // Set Click Listener
        btnLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Check Login
				String username = etUsername.getText().toString();
				String password = etPassword.getText().toString();
				
				if(username.equals("guest") && password.equals("guest")){
					lblResult.setText("Login successful.");
				} else {
					lblResult.setText("Login failed. Username and/or password doesn't match.");
				}
			}
		});
        btnCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Close the application
				finish();
			}
		});
    }
}

As we see, we create an anonymous class there by adding { … code … } behind the new OnClickListener interface and implementing the necessary onClick(View v) method.

Advantages

  • Small and tidy
  • Easy to implement
  • Less overhead

Disadvantages

  • Inflexible
  • Can’t be reused
  • Can be a bit harder to maintain

Usage

Inline implementations are usually used for short 1-time methods, for example if you have a button which closes the application or which displays, you don’t need to add an implementation to your class or create a variable, making your code less readable.


Using the “implements” keyword

The second method to implement an Listener is by adding an interface to your base class. In java you can do this by adding “implements Interfacename” to the class declaration.

package com.tseng.examples;

...

public class LoginExampleImplements extends Activity implements OnClickListener {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

	...        

        // Set Click Listener
        btnLogin.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
    }

	@Override
	public void onClick(View v) {
		if(v==btnLogin) {
			// Check Login
			String username = etUsername.getText().toString();
			String password = etPassword.getText().toString();
			
			if(username.equals("guest") && password.equals("guest")){
				lblResult.setText("Login successful.");
			} else {
				lblResult.setText("Login failed. Username and/or password doesn't match.");
			}
		} else if(v==btnCancel) {
			// Close the application
			finish();
		}
	}
}

As we can see, the “onClick(View v)” is being declared inside our LoginExample class and additionally we set the listener by passing a reference to our class to by using btnLogin.setOnClickListener(this);. This works, because we implemented this interface within our class public class LoginExampleImplements extends Activity implements OnClickListener. You may also have noticed, that we add the same listener to both buttons. Because both of the buttons use the same listener, we need to differentiate which one was clicked. This can be done by comparing the View v reference with the Button btnLogin reference as seen below:

	if(v==btnLogin) {
		// Check Login
		...
	} else if(v==btnCancel) {
		// Close the application
		...
	}

Advantages

  • Methods/Listener can be reused in many different widgets
  • Code of multiple Listeners is located in the same section of code
  • Can be used to create one method for similar Listeners

Disadvantages

  • Can contain much unnecessary and untidily code, if the actions executed are to different and you have to add an if / elseif / else blocks, making the code hard to read
  • You can only have one implementation of this Listener per class

Usage

This method is best used, when you have multiple widgets/elements using same or similar listeners (i.E. doing a calculation or check on a click or key press). The example above is not the best example on the usage of the implement method. Let’s imagine, you have a calculator and have 14 buttons  and you want to update the formula you entered after every calculator button is pressed, you could implement it in the following way shown below.

package com.tseng.examples;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class CalculatorExample extends Activity implements OnClickListener {
	...

	@Override
	public void onClick(View v) {
		if(v==btnCalculate) {
			// Parse and calculate formula
			String formula = etFormula.getText().toString();
			Double result = performCalculation(formula);

			// Update the result TextView
			tvResult.setText(Strint.valueOf(result));

			// End it as we don't need or want to update the Formula field
			return;
		}

		// Get the button
		Button button = (Button)v;

		// Get the String/Button descritpion
		String strToAppend = button.getText().toString();

		// Update Formula
		etFormula.append(strToAppend);
	}
}

You could add this Listener to every of the calculators button and only need to define one Listener. When the buttons are clicked, the button text (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, +, –, /, * etc.) will be added to the TextView containing the formula. However, if you press the calculate button, it won’t add a = to the formula, but will instead perform the calculation.

Another very good implementation of this is, if you want to validate the input in a TextField altough there are other way in Android by using the TextView.setFilters(…) Method, but this is another topic.

This is best used when you’re creating your own widgets and want to to handle clicks (assuming there are only few clickable elements there)

By using Variables

This one is very similar to the previous one, with the difference that you don’t add the implementation to your class, but instead hold a reference to the Listener in a variable.

In our LoginExample it would look like this

package com.tseng.examples;

...

public class LoginExampleVariableImplementation extends Activity {
	...
	
	OnClickListener myClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if(v==btnLogin) {
				// Check Login
				String username = etUsername.getText().toString();
				String password = etPassword.getText().toString();
				
				if(username.equals("guest") && password.equals("guest")){
					lblResult.setText("Login successful.");
				} else {
					lblResult.setText("Login failed. Username and/or password doesn't match.");
				}
			} else if(v==btnCancel) {
				// Close the application
				finish();
			}
		}
	};
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

	...
        
        // Set Click Listener
        btnLogin.setOnClickListener(myClickListener);
        btnCancel.setOnClickListener(myClickListener);
    }

}

Basically we create it anonymous Listener with the difference that we hold a reference to it. This allows us to add this Listener to more than only one widget. The main difference to the implements keyword method is, that we can have more than one Listener inside our class declared and use them more than once.

Advantages

  • Can be reused
  • You can have more than one Listener of the same kind in your class
  • You can keep your listeners organized in one place, making your code easier to read

Disadvantages

  • Too many listeners can make the code rather complicated to read

Usage

This is best to use if you have different Listeners for the same action i.e. 2 different OnClickListener which do a completely different task.

Another very important usage for this variant is if you’re implementing your own Listeners to your widgets, you could have a variable which can be assigned by the users of your widgets

package com.tseng.examples;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MyWidget extends View {
	...
	
	OnClickListener myClickListener = null;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		...
	
	}

	public void setOnClickListener(OnClickListener listener) {
		myClickListener = listener;
	}

	private onClick(View v) {
		// Check if Listener was set and call the onClick Method
		if(myClickListener!=null)
			myClickListener.onClick(v);
	}
	private void handleEventsMethod() {
		...
		// handle clicks
		onClick(this);
	}
}

This allows us to dynamically set the Listener to our widget without knowing what the listener will actually do with the click, as it can be implemented in any way the user or programmer wants it to be.

Summary

So there are no “right” ways to implement a Listener. It all depends on the situation and/or your personal preferences.

Method Recommended usage
Inline Best to use for short and one time only listeners, like closing an application or displaying an message or call another Activity/Dialog
implements-keyword If you have only one listener in your class (i.e. your own widget) or the listeners shares a fairly similar code/task, like the Calculator Example above
Variables If you have many Listeners with very different codebases and tasks or creating your own widget and want to allow your users to handle the events (i.e. click or key press events).
 

Permanent link to this article: http://tseng-blog.nge-web.net/blog/2009/02/14/implementing-listeners-in-your-android-java-application/

58 comments

11 pings

Skip to comment form

  1. http://www.scribd.com/Doc/217898887

    On voit direct que vous connaissez superbement bien ce que vous avancez

  2. http://Issuu.com

    Ce poste est vraiment plein de vérités

  3. turlutte hardcore épicurienne

    Je vois directement que vous connaissez très bien ce que vous avancez

  4. clash of clans ultimate hack tool android ios

    I think that is among the such a lott sighificant information for me.
    And i am glad studying your article. But should commentary on some normql things, The website style is
    great, the articles is really excellent : D. Just
    right process, cheers

    my web site: clash of clans ultimate hack tool android ios

  5. Hotel Razvan Bucuresti

    Sucevita Cazare

    Can you tell us more about this? I’d care to find out more details.

  6. Cheap Louis Vuitton Women Handbags

    Fundamentally, Daniel helps make the situation (accurately I might add) that:self-assurance Plus the actual level of excellent of the web application inside the context of web safety will proceed to get an escalating impact within the bottom line (revenue) from the companies behind the web applications in the Internet vNext
    Cheap Louis Vuitton Women Handbags http://www.shophandbagsoutlet.net/louis-vuitton-women-handbags-sale-1_2.html

  7. Despicable Me Minion Rush Hack Tool No Survey

    Whats up this is somewhat of off topic but I
    was wanting to know if blogs use WYSIWYG editors or if you have
    to manually code with HTML. I’m starting a blog soon but have no coding skills so I wanted to get advice from someone with
    experience. Any help would be enormously appreciated!

    My website – Despicable Me Minion Rush Hack Tool No Survey

  8. Francesco

    I see a lot of interesting posts on your page. You have to spend a lot of time
    writing, i know how to save you a lot of time, there is a tool that creates unique,
    SEO friendly articles in couple of seconds, just search in google – laranita’s free content source

  1. RxRick’s Blog

    [...] I finally stumbled upon a brilliant blog which explains all the different methods, and lists the pros and cons of each: Implementing listeners in your Android application [...]

  2. How to implement your own Listener in Android/Java | Tseng's dev blog

    [...] dev blog A developers blog « Implementing Listeners in your Android/Java application SavedState: Preserve data when your Activity is recreated – Part 1 [...]

  3. Android: Your first Android Application | Tseng's dev blog

    [...] listeners only gets used once and their code is pretty small. If you want to know more check out my Implementing Listeners in Android/Java [...]

  4. SavedState: Preserve data when your Activity is recreated – Part 1 | Tseng's dev blog

    [...] item from the auto-complete list. Implementing Listeners is already explain in my previous post “Implementing Listeners in Android/Java” and “How to implement your own Listeners in [...]

  5. Caught By .Net!

    Implementing Listeners in your Android/Java application…

  6. Verwendung von Listener - Android-Hilfe.de

    [...] [...]

  7. смотрите новости mmorpg

    смотрите новости mmorpg…

    [...]Implementing Listeners in your Android/Java application | Tseng’s dev blog[...]…

  8. Activity! Criando Interfaces Gráficas no Android! | Android On Board

    [...] Link que demonstra outras formas de tratar eventos de componentes Button no Android: [...]

  9. aListView – Displaying and using a ListView | Breinbaas Blog

    [...] line 5: definition of the itemclicked listener, I like to put these functions in variables instead of implemting the directly, there is a great blog about the ways to implement listeners here. [...]

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>