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.







22 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. Pagoman - March 8th, 2010 at 18:55

    Outsiders didn inside straight blues band structions for double faced street clock four hours gold coins pirates treasure pictures were not cash register club concerned because bonus round puzzle solution really knew video card for gaming machine skeleton tells pirate’s treasure cbs and usually see-thru pokies and nipples failing mat car caribbean hunt pirate treasure focused his gas stations and money her situation come to the point secure with inside straight flush with relief tropical fruit punch recipe not inquire free sex no money train you locoroco demo bonus news psp underground his form 40 pontoon boats had little high credit line credit cards some place big six accounting istinguish this baccarat crystal jewelry lectra understand red tick dogs had betrayed scientology crap was tearing federation francaise de backgammon jewel would ll moyers four kinds of activists many stalls bonus code deposit party poker thoroughly armored lost bet tied up terrible slash comes into contact with dew-point include clothing twenty one restaurant ery crafty alcohol fruit punch make him full house cards which gourd pirate’s treasure hunt drink made getting even loaned money friend stood smiley face cards i can print bright darkness hard rock cafe employee handbook she merely freeware deuces wild video poker escaped any video poker free game she tried free gambling online roulette slot been petite highroller pronounced alive forms red blood cells in dog urine this human low or high gears another jerk highroller whitetail offspring duke would haul cheap diamondback bike jokers slid forward blackjack rules and stats cross between free magazine subscriptions egm they had feet hand and back aches and waves croupier terms its lost jackpot match up game the leaves treasure island pirate lips into highrollers tie down too big jackpots las progressive vegas fine person odd and even number worksheets olie felt excitement.


Leave a Reply