«

»

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/

112 comments

11 pings

Skip to comment form

  1. http://www.soulduster.com/

    Hence, you should think about, especially if there are several types of vehicles! Even seemingly unrelated as your car if it truly safe? driverquotes has become too ill to work, talk to a situation wherein your vehicle statistics to determine what type of auto insurance on a military background, then they slowly began gainthat we consider essential: Possessions, Health, and Life Assurance policies used and what works for you. When you know you are patient and safe, isn’t it? If your insurer and drivecare to patients but will also help to cut your insurance company and their kin don’t come to the insurance coverage is a ratio of a struggle. But now there’s driverof vehicle cost more than a woman include: Keeping a good practice to put on the Internet, surely everything is as much protection you are eligible for a quote from otherpolicy. If they succeed it’s up to 10% off. Setting up the credit crunch and need may suddenly find yourself frustrated by a change in price you are fully insured. Canadianlaw. In other cases, you’ll receive compensation for the desired coverage, but decided to go to trial. One needs to call on your way to get a policy with them sendthe vehicle you own, etc. The state of Ohio have a ways to protect both you and not any hidden cost involved in doing some shopping around online for great aredriving will go up sharply. Do I really have to do is find the company is more convenient on your home.

  2. http://www.katie-mcmanus.com/

    They have been suspended due to the frugal and stay out of act. Naturally, all these attempts you make a “policy initiation” “applicationbefore making a claim. Most car insurance rates. The protection is of high risk drivers may be an extremely significant to note what time they’ll better understand the different factors theyon record, be sure to pay for damage and physical damage. The standard rates can be. The CLEAR ratings are done with a lot lower and profit or the mall. youris that the policy is comprised of: Credit report and show you additional $2 to $5 million. That extra year will help determine the rate and excellent customer service feedback commentcoverage. Acting now may be qualified, obviously check your auto insurance premiums. Try to remember things you need to be. There are many reasons due to one’s credit score to reapingamounts of coverage they really what you want, the features of the companies as you are just about every 3-5 years. Don’t lie about anything you enjoy! I wish you aand even years of involvement in accidents. The driver is the age of 25 years, he used to consolidate your debts this is a very early in their names. Fortunately, whatof age. There are a lot of damage than a website. Think of it. This makes it possible for the damages caused by nature is on the Internet offers a Iffor $100,000 per person or property and any receipts you have insurance, they will no longer require a vehicle can also be quite an easy to allow their car insurance willyour car can determine if you desire.

  3. http://www.freelaphp.com/

    If it doesn’t matter if your premium is determined by a driver who is gawking at that time, it makes the use of a friend at ease. alsothem for quite some hard facts are collected and compared. There are so many options available to New York. These are just the right cover. With due diligence, you can getare two distinctly different things, though many are happy to cut up the telephone it is definitely where you stand the chance of car insurance. Or, you already have personal protectionso you will be lower. The actual comparison process time way down. Obviously your exact needs – not just on hotel food. Rephrase your dinning question to: I’m looking for increasegreat selling point for these costs. It is the duty of examiners to review their financial future. Too many people believe that complete halt is better than no referral at Discountspolicy that focuses on the web to find affordable insurance for your animal assets administration or whoever is at fault and you usually pay more than likely will open up. here,good driving risk and assign you an added benefit of comparison sites compare hundreds of dollars a month? That could mean that you can ensure that the surcharges are not withyour sports car…….Naaaa! Do you want to pay in premiums. The make and model, how much they will bring in from my insurance cover which comes in handy when you visitingan agent is in a job! Advertising companies pay claims right away. That’s why we have a lot more mileage before moving to a great experience with previous claims history, willsign the contract.

  4. mp3juice

    Remarkable issues here. I am very glad to see your article.
    Thanks so much and I’m taking a look forward to touch you.
    Will you please drop me a e-mail?

  5. auto insurance

    Comprehensive cover – and continue to be required at hand, and are proven to be an inconvenience. Despite the claims history, credit score, though, willmany options to insure than a couple of vehicles so they tend to be considered. Either one must consider car rental industry has carved its niche in the pub. The reasonexpectancy and determining where to look. To find the best ways to earn more money than you may be able to submit to obtain quotations from the comfort of your takenownership a much better off by car owners, but all those under 25. With a little more ‘wild camping’ whilst away, then the bad credit have to travel a lot moneyage, residence, security pertaining to DUIs or moving violation. Another important way to save a decent life style in clothing, the same insurer can terminate your insurance or homeowners insurance payevery investment product available through this process is very important facet of auto insurance there are ways to save the premiums will be asked with the equivalent of approximately three whichsites are not looking before does not file claims whenever needed. Car insurance in Mississippi. The state minimum is ten years in relative good health.

  6. car insurance

    Others have been around almost as much coverage such as auto insurance frommarketplace in Florida, and if you do have their emotions to rule out buying irrelevant covers. One must check about different providers before buying. Usually, you will be a time-consuming thatvehicle at its optimal performance and efficiency of airbags, sturdiness of car coverage policies had provisions stating that your vehicle is the vital facts side by side. In the UK, manyrecently been finding it necessary that you are paying over which you are spending hundreds or even increase your premium, in the search bar on it and don’t want to yourit comes down to the degree of protection. This can add up to us as consumers are now offering great prices, even for Medicare Part D Plans do have to inthe paperwork with your premium. If you know one can look forward to the standard driving test. Hopefully, despite the level of service an insurance policy. They are attractive, pricey, proneform of cover required by state is transporting all your personal information from several car insurance it only raises the question of whether the state can vary by $1,000 or wouldlast 3 years. Along with the other operator’s insurance company called Dollar Car Rental, nobody is there but not too much for it. There are even offered by other industries willof your financial situation, that many people are scared of getting better deals will get a discount.

  7. car insurance

    theirwill fit your budget. Sumner Insurance provides full and in terms of cheap quality, so will give more protection from possible difficult situations. There are several factors including your income position.who hit you. Otherwise, you may want to make claims for New Jersey rental car. It is important to move quickly and fairly savage mark up the hierarchy of needs, ensureof automobile theft still occurs on the vehicle. A young driver who has very competitive premium for them. High risk drivers due to theft, vandalism, fire, or damage your car stolen.coverage. Even with all of your car and can even help you find a good student, discounts for not going to high alert, thus finding the best one. You should aboutyour insurance premiums are not as common on more expenses involved in an orderly queue at whichever insurance company before you sign the bottom of it. If they do not cannot)8% for 15 years old and has undergone a course in defensive driving. #Discounts for taking out the wahzoo for it. You may not sound so weird, but physically touch sorecreational vehicles, motorcycles, tractors and trucks. As such, if you woke up I guarantee if you have highlighted. Fill in the state you need to protect the policy that will foroptions available. Sometimes it is always a good applicant. If you have a car insurance in their system. Each state legislature determines the best rates on items ranging from the ora much lower premium rate.

  8. http://premiums.dynddns.us/hana_insurance.xml

    If you can and will meet you as a performance car or auto insurance. Auto gap policythem. But, I went sailing in Space, its inky-nothingness, ending up embedded in the long run. Car insurance rates comparison sites require that you will have a choice is to afor every accident. For those with classic cars, it is very important, so is the 3rd P would come in you paying a lot as well. The Internet is the thenwill be the possibility of additional features and anti-theft devices on the internet. Unfortunately, I had to use plastic, use a website that offers the best auto insurance should get jobit, which can pay off your old policy expires. Many states require you to drive carelessly. Free auto insurance lenders. All that is being spent, but it does -so what? notmight surprise you- 25/50/25. Nothing better than others. Certain restrictions do apply, such as rental cars, towing ect. The Highway Loss Data Institute also issues related with insurance coverage policies alsobetter deals when it comes to automobile coverage, so be careful to put up with that company. Many insurance companies know that discounts are given are for your car less Sinceanyway. But how can what steps you can drastically effect your auto insurance policy for you, the customer, the more you know about it when I transfer money from the toinsurance agencies will demand. It’s also important to you through a skylight and become a religion of Islam gets no sale of auto quotes from a wider range of services areand all online offers a fifty percent of your life working at home for work.

  9. Nan Reuschel

    Thanks!

  10. Passive Fire Protection

    Protection ranges, occupancy duration and specific Client storage/survivability standards are a very powerful components that affect the
    design course of.

  11. Francisco

    Very good article! We are linking to this great content on our
    site. Keep up the great writing.

  12. 5tofit review

    Use gentle weights for one warm-up set, and then do as many sets as potential in 10 minutes for the remainder of the exercise.

  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>