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
implements
We’ll use our good old LoginExample application, created in previous tutorial which can be found at Android: Your first Android Application.
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.
01
package
com.tseng.examples;
02
03
...
04
05
public
class
LoginExample
extends
Activity {
06
/** Called when the activity is first created. */
07
@Override
08
void
onCreate(Bundle savedInstanceState) {
09
super
.onCreate(savedInstanceState);
10
11
12
13
// Set Click Listener
14
btnLogin.setOnClickListener(
new
OnClickListener() {
15
16
onClick(View v) {
17
// Check Login
18
String username = etUsername.getText().toString();
19
String password = etPassword.getText().toString();
20
21
if
(username.equals(
"guest"
) && password.equals(
)){
22
lblResult.setText(
"Login successful."
);
23
}
else
{
24
"Login failed. Username and/or password doesn't match."
25
26
27
});
28
btnCancel.setOnClickListener(
29
30
31
// Close the application
32
finish();
33
34
35
36
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.
{ … code … }
onClick(View v)
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.
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.
implements Interfacename
LoginExampleImplements
Activity
OnClickListener {
this
(v==btnLogin) {
(v==btnCancel) {
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:
LoginExample class
btnLogin.setOnClickListener(this);
class public class LoginExampleImplements extends Activity implements OnClickListener
View v
Button btnLogin
1
2
3
4
5
6
7
if / elseif / else
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.
import
android.app.Activity;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.view.View.OnKeyListener;
android.widget.Button;
android.widget.EditText;
android.widget.TextView;
CalculatorExample
(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);
37
38
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)
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
LoginExampleVariableImplementation
OnClickListener myClickListener =
};
btnLogin.setOnClickListener(myClickListener);
btnCancel.setOnClickListener(myClickListener);
39
40
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.
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
MyWidget
View {
null
setOnClickListener(OnClickListener listener) {
myClickListener = listener;
private
// Check if Listener was set and call the onClick Method
(myClickListener!=
)
myClickListener.onClick(v);
handleEventsMethod() {
// handle clicks
onClick(
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.
So there are no “right” ways to implement a Listener. It all depends on the situation and/or your personal preferences.
Remember Me
a@href@title, b, blockquote@cite, em, i, strike, strong, u