Defining external Listener
suggest changeWhen should I use it
- When the code inside an inline listener is too big and your method / class becomes ugly and hard to read
- You want the same action on several views
To achieve this you need to create a class implementing one of the listeners in the View API.
For example, give help when long click on any element:
public class HelpLongClickListener implements View.OnLongClickListener
{
public HelpLongClickListener() {
}
@Override
public boolean onLongClick(View v) {
// show help toast or popup
return true;
}
}
Then you just need to have an attribute or variable in your Activity to use it:
HelpLongClickListener helpListener = new HelpLongClickListener();
button1.setOnLongClickListener(helpListener);
button2.setOnLongClickListener(helpListener);
label.setOnLongClickListener(helpListener);
A listener in a separate class cannot see the activity fields directly. Pass the context or the view through the constructor, or expose them with getters.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents