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
implementskeyword - 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 / elseblocks, 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.
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). |
No related posts.






Hello, I can’t understand how to add your blog in my rss reader
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
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?
Why don’t my username and password work?
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?
I really liked this post. Can I copy it to my site? Thank you in advance.
Sure, if you post a backlink to the original post, it’s fine for me.
I just want to let you know that I have benefited from the information here. Thanks a lot.
hey this is a very interesting article!
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!
I cannot believe this will work!
Great site…keep up the good work.
Thank you! I would now go on this blog every day!
Hi, Thank you! I would now go on this blog every day!
Thank you
Hi,
Onload of page my antivirus put alert, check pls.
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
Hi,
Super post, Need to mark it on Digg
Have a nice day
Robor
Hi, Amazing! Not clear for me, how offen you updating your tseng-blog.nge-web.net.
Thank you
Bodyc
Article very interesting, I will necessarily add it in the selected works and I will visit this site
Completely I share your opinion. I think, what is it good idea.
Have a nice day
[...] 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 [...]
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.
Disregard the above. The switch statement argument cannot be type view…
[...] dev blog A developers blog « Implementing Listeners in your Android/Java application SavedState: Preserve data when your Activity is recreated – Part 1 [...]
[...] 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 [...]
[...] 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 [...]
[...] [...]
Implementing Listeners in your Android/Java application…
…
[...] [...]
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!
[...] http://tseng-blog.nge-web.net/blog/2009/02/14/implementing-listeners-in-your-android-java-applicatio... [...]
Great post,thanks!
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]
[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.
This is the best email in a browser that I’ve read in a while.
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
I am new on this website and simply immediately i plan to would say hi there to everyone
[url=http://tolipan.if.ua]Должностные обязанности водителя
[/url]
please remove this post.
i’m sorry.
Раскрутка сайтов в поисковых системах Яндекс и Google является важной составляющей комплексной интернет рекламы Вашего бизнеса. Мы поможем вам продвинуть сайт в поисковых системах по ключевым запросам, которые могут набирать пользователи в сети Интернет. Поэтому прежде чем выбрать компанию и заказать у нее эту услугу, необходимо как можно подробнее узнать о ее опыте и преимуществах перед конкурентами.
Только качественное и эффективное продвижение сайта будет способствовать росту Ваших продаж. Мы рады тому, что Вы готовы воспользоваться услугами нашего агентства и предлагаем ознакомиться с нашими основными конкурентными преимуществами.
Как выяснилось, рекламировать сайт оказывается нужно не только для пользователей. В настоящее время сеть Ин%
Website Development, Promotion and Advertising, Design – KeyBridge Studio | Design and website promotion
смотрите новости mmorpg…
[...]Implementing Listeners in your Android/Java application | Tseng’s dev blog[...]…