Tseng’s dev blog

A developers blog



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).
 
Bookmark and Share

No related posts.







42 Responses to 'Implementing Listeners in your Android/Java application'

  1. toveantinee - March 9th, 2009 at 13:53

    Hello, I can’t understand how to add your blog in my rss reader

  2. Tseng - March 9th, 2009 at 14:31

    Hi,
    the links for the feeds are on the right side of the navigation under Resources -> Subscribe.

    What RSS Reader are you using? Webbased or a real one?

    The links for the feeds are
    RSS 2.0: http://tseng-blog.nge-web.net/blog/feed/
    RSS 2.0 (Comments): http://tseng-blog.nge-web.net/blog/comments/feed/
    RSS 0.92: http://tseng-blog.nge-web.net/blog/feed/rss/
    Atom 0.3: http://tseng-blog.nge-web.net/blog/feed/atom/

    Depending on what format your feed reader requires, you have to choose the correct URL yourself. i.e. if your Reader is supporting RSS 2.0, then pick the first one, if not try atom or RSS 0.92 feed

  3. Vince Delmonte - April 15th, 2009 at 07:56

    I can tell that this is not the first time at all that you mention this topic. Why have you decided to touch it again?

  4. Miplobinobeby - April 15th, 2009 at 10:52

    Why don’t my username and password work?

  5. Tseng - April 18th, 2009 at 12:05

    For the example the username and password is hardcoded to username guest and password guest.

    You can see it in this line
    f(username.equals(“guest”) && password.equals(“guest”)){
    // …
    }

    In a real application you have to use a database or website to do the verification of the login data. Maybe post a piece of code, if you have altered it or built it in your application?

  6. Arianabura - May 13th, 2009 at 10:47

    I really liked this post. Can I copy it to my site? Thank you in advance.

  7. Tseng - May 13th, 2009 at 22:17

    Sure, if you post a backlink to the original post, it’s fine for me.

  8. fxmen - May 22nd, 2009 at 14:58

    I just want to let you know that I have benefited from the information here. Thanks a lot.

  9. KeHoeff - May 28th, 2009 at 21:12

    hey this is a very interesting article!

  10. PypePilky - June 5th, 2009 at 22:16

    Very nice collection of information on that question. Thanks to the author. I have been looking for such an article since January! Thank you again!

  11. Felix-Tiez - August 29th, 2009 at 14:39

    I cannot believe this will work!

  12. Bill Bartmann - September 2nd, 2009 at 14:05

    Great site…keep up the good work.

  13. Elcorin - September 5th, 2009 at 20:50

    Thank you! I would now go on this blog every day!

  14. Zoran - September 10th, 2009 at 07:23

    Hi, Thank you! I would now go on this blog every day!
    Thank you

  15. Zoran - September 14th, 2009 at 10:43

    Hi,
    Onload of page my antivirus put alert, check pls.

  16. Tseng - September 14th, 2009 at 16:25

    It does? Where? You could try to post a picture, to see if it happend on one of the ads (on which I don’t really have influence which is displayed). But I doubt Google would allow malicious ads to be displayed

  17. Robor - September 17th, 2009 at 20:10

    Hi,
    Super post, Need to mark it on Digg
    Have a nice day
    Robor

  18. Bodyc - September 20th, 2009 at 07:39

    Hi, Amazing! Not clear for me, how offen you updating your tseng-blog.nge-web.net.
    Thank you
    Bodyc

  19. nintendost - November 18th, 2009 at 05:54

    Article very interesting, I will necessarily add it in the selected works and I will visit this site

  20. Miato - November 18th, 2009 at 08:39

    Completely I share your opinion. I think, what is it good idea.
    Have a nice day

  21. RxRick’s Blog - December 8th, 2009 at 16:43

    [...] 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 [...]

  22. Adam - April 8th, 2010 at 09:24

    A better alternative to using

    if(v==buttonx) {}
    else if(v==buttony) {}

    would be to use a switch statement.

    switch(v) {
    case buttonx:
    //events
    break;
    case buttony:
    //events
    break;
    default:
    //else
    }

    This approach is much easier on the eyes.

  23. Adam - April 8th, 2010 at 22:46

    Disregard the above. The switch statement argument cannot be type view…

  24. How to implement your own Listener in Android/Java | Tseng's dev blog - April 29th, 2010 at 16:51

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

  25. Android: Your first Android Application | Tseng's dev blog - April 29th, 2010 at 18:39

    [...] 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 [...]

  26. SavedState: Preserve data when your Activity is recreated – Part 1 | Tseng's dev blog - April 29th, 2010 at 19:38

    [...] 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 [...]

  27. extends view + onDraw() + listener - Android-Hilfe.de - May 19th, 2010 at 10:47

    [...] [...]

  28. Caught By .Net! - May 27th, 2010 at 21:26

    Implementing Listeners in your Android/Java application…

  29. Verwendung von Listener - Android-Hilfe.de - June 2nd, 2010 at 12:47

    [...] [...]

  30. Doccie - June 23rd, 2010 at 09:22

    Great post… Coming from an AS3 background, I had some trouble wrapping my head around this approach when reading the android docs, but your post was very clear and precise, thanks!

  31. Ways to Implement an OnClick Listener in Android - October 7th, 2010 at 05:29

    [...] http://tseng-blog.nge-web.net/blog/2009/02/14/implementing-listeners-in-your-android-java-applicatio... [...]

  32. Sachin - November 19th, 2010 at 07:35

    Great post,thanks!

  33. PeruFess - November 24th, 2010 at 23:01

    Well I do not know as whom, and such surprises like me!!!!))))
    [url=http://buy-erectalis.male-edrx.info][size=1][color=white]erectalis
    [url=http://cheap-intagra.male-edrx.info][size=1][color=white]intagra
    freeorder online
    [/color][/size][/url][url=http://order-suhagra.male-edrx.info][size=1][color=white]suhagra
    [url=http://cheap-tadalis.male-edrx.info][size=1][color=white]tadalis
    female use
    [/color][/size][/url]

  34. ZWNicholas - January 23rd, 2011 at 07:17

    [url=http://digestforum.com/search.php?q=adult][img]http://mikardia.com/porno_pictures/cum-porno-7.jpg[/img][/url]

    Sex headaches can occur around either masturbation or any kind of sex. Sex headaches are usually felt at the base of the skull, but can be all over. [url=http://biotemasi.ru/engl/index.php?n=24140]winks porn[/url] Men with high blood pressure were also more likely to have optic nerve damage if they had taken these drugs, although this was not statistically significant.
    Sex Pistols the definitive history and latest news of the finest Punk Rock band ever; Sex Pistols. Updated continually for over 10 years. Contains over 1,500 pages. [url=http://biotemasi.ru/sex/index.php?n=26192]forced sex slavery s[/url] also x rated porn videos watch free celebirties animated cartoon pamela anderson porn movie free kaleya eurotik porn black porn star name farklД± porn video free pinoy porn movies free srbian porn muvie ravemaster porn free porn videos for razor mobile phones
    Survey questions and tests focused on participants’ sex-linked cognitive abilities, personality traits, interests, sexual attitudes and behavior… [url=http://biotemasi.ru/porn/index.php?n=22409]free virgin porn movies[/url] also softcore porn torrents south indian porn movie xxx porno rusia indian hot porn old mom
    Virgin Islands, Saint Thomas and Saint Croix maintain separate sex offender determine the number of sex offenders per 100,000 total population in that state [url=http://biotemasi.ru/gay/index.php?n=11920]red vs blue season 5 torrent[/url] also 10 minute porn trailers al capone and porn free porn video tiere free gay jamaican porn video clips brazil wild porn
    14 Aug 2008 Everyone knows that sex sells. And hundreds, if not thousands, of films have been marketed with sex. But here I’ve selected ten interesting [url=http://biotemasi.ru/teen/index.php?n=4644]teen insertion free 3gp[/url] Lottery winner is a 3-time sex offender. Alec Ahsoak collected his $500,000 winnings to benefit a sex abuse victims charity is a three-time sex offender.

  35. sony ericsson w580i - January 23rd, 2011 at 10:23

    This is the best email in a browser that I’ve read in a while.

  36. mERLINjuulez - March 29th, 2011 at 02:43

    Good day

    You pall monotonous sex, You bored own second half or wife you’re tired of ownsecond half, a lover can not You bring, you want diversity in Personal Life? if [url=http://www.callvipgirls.com]massage[/url] on our site – it it what you required! [url=http://www.callvipgirls.com]erotic massage[/url] open You what true naughty [url=http://www.callvipgirls.com]femmes bruxelles[/url].

    Sincerely, your friend Lorik

  37. links of london in london - April 4th, 2011 at 20:50

    I am new on this website and simply immediately i plan to would say hi there to everyone

  38. WhorpopPhossy - April 8th, 2011 at 05:21

    [url=http://tolipan.if.ua]Должностные обязанности водителя
    [/url]

  39. habaqwe - October 28th, 2011 at 01:06

    please remove this post.
    i’m sorry.

  40. miritavyalova - November 28th, 2011 at 06:46

    Раскрутка сайтов в поисковых системах Яндекс и Google является важной составляющей комплексной интернет рекламы Вашего бизнеса. Мы поможем вам продвинуть сайт в поисковых системах по ключевым запросам, которые могут набирать пользователи в сети Интернет. Поэтому прежде чем выбрать компанию и заказать у нее эту услугу, необходимо как можно подробнее узнать о ее опыте и преимуществах перед конкурентами.
    Только качественное и эффективное продвижение сайта будет способствовать росту Ваших продаж. Мы рады тому, что Вы готовы воспользоваться услугами нашего агентства и предлагаем ознакомиться с нашими основными конкурентными преимуществами.
    Как выяснилось, рекламировать сайт оказывается нужно не только для пользователей. В настоящее время сеть Ин%

  41. tovawincino - January 6th, 2012 at 04:26

    Website Development, Promotion and Advertising, Design – KeyBridge Studio | Design and website promotion

  42. смотрите новости mmorpg - January 11th, 2012 at 03:18

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

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


Leave a Reply