«

»

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/

39 comments

11 pings

Skip to comment form

  1. toveantinee

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

  2. Tseng

    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

    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

    Why don’t my username and password work?

  5. Tseng

    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

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

  7. Tseng

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

  8. fxmen

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

  9. KeHoeff

    hey this is a very interesting article!

  10. PypePilky

    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

    I cannot believe this will work!

  12. Bill Bartmann

    Great site…keep up the good work.

  13. Elcorin

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

  14. Zoran

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

  15. Zoran

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

  16. Tseng

    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

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

  18. Bodyc

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

  19. nintendost

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

  20. Miato

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

  21. Adam

    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.

  22. Adam

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

  23. Doccie

    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!

  24. Sachin

    Great post,thanks!

  25. sony ericsson w580i

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

  26. jamie

    Does this mean someone can hack your phone and listen to your conversations?

  27. khanh tran

    hi Tseng
    can u explain more about the last example (public class MyWidget extends View)
    Thank u in advance

  28. carpinteyronjg

    Here let me learn more knowledge!

  29. joyson

    Very Helpful Tutorial…Looking forward you add some more tutorials to share your knowledge..

  30. Joey

    You forgot about the method of using “inner classes”. I’d like to see this added for thecomparison.

  31. online hard drive backup

    I’m really loving the theme/design of your weblog. Do you ever run into any browser compatibility problems? A number of my blog visitors have complained about my website not operating correctly in Explorer but looks great in Chrome. Do you have any suggestions to help fix this problem?

  32. That This Broadoaks Country House In Windermere

    What’s up to all, the contents existing at this site are really amazing for people experience, well, keep up the good work fellows.

  33. Keeley

    Write more, thats all I have to say. Literally, it seems as though you relied on
    the video to make your point. You definitely know what
    youre talking about, why waste your intelligence on just posting videos to your site when you could be giving us something informative to read?

  34. Pierre

    Hi, I read your examples for setting different onclicklisteners, they worked. I am having some issues with my project and I was wondering whether you can help me with my issue. I am new to Android. I am using an expandable listview, on the parent i have a few imagebuttons which can be clicked on. When a button is clicked I need to pass the parent object as a parameter to the click event. Do you have any sample code that shows how to do this.
    Thanks in advance for your help.

    Pierre

  35. make music

    It’s very trouble-free to find out any matter on web as compared to textbooks,
    as I found this post at this web site.

  36. fl studio 11 crack download

    Thanks for any other informative blog. The place
    else may I get that kind of information written in such an
    ideal method? I’ve a challenge that I am just now running on, and I have been on the glance out for such info.

  37. Richard

    Another way is to implement the onClick listener as a static. You can then cast the view passed back to the static to the class required. e.g


    public class ClickCountRow extends TableRow {
    static int uid = 0;
    ClickCountButton clickCountButton;
    ClickCountLabel clickCountLabel;

    static private OnClickListener defaultClickListener = new OnClickListener() {
    public void onClick(View v) {
    L.log.debug("click button clicked");
    }
    };

    OnClickListener clickListener = defaultClickListener;

    public ClickCountRow(Context context) {
    this(context, null);
    }
    public ClickCountRow(Context context, AttributeSet attrs) {
    super(context, attrs);
    LayoutInflater layoutInflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = layoutInflater.inflate(R.layout.click_count_row, this);
    clickCountButton = (ClickCountButton)v.findViewById(R.id.clickCountButton);
    clickCountButton.setOnClickListener(clickListener);
    clickCountLabel = (ClickCountLabel)v.findViewById(R.id.clickCountLabel);
    uid++;
    }
    }

    Why? Just another approach.

  38. mobile chess games

    Oh my goodness! Impressive article dude! Thank you so much, However I am experiencing problems with your RSS.
    I don’t understand why I am unable to join it. Is there anyone else having similar RSS issues?

    Anyone who knows the solution can you kindly respond?
    Thanx!!

  39. เมดิลีน

    Greetings! I’ve been following your site for a long time now and finally got the
    bravery to go ahead and give you a shout out from
    Porter Texas! Just wanted to say keep up the good job!

  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>