Android Button Defining external Listener

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

When 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 to perform same action in various elements (view) of your app

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 void onLongClick(View v) {
        // show help toast or popup
    }
}

Then you just need to have an attribute or variable in your Activity to use it:

HelpLongClickListener helpListener = new HelpLongClickListener(...);

button1.setOnClickListener(helpListener);
button2.setOnClickListener(helpListener);
label.setOnClickListener(helpListener);
button1.setOnClickListener(helpListener);

NOTE: defining listeners in separated class has one disadvantage, it cannot access class fields directly, so you need to pass data (context, view) through constructor unless you make attributes public or define geters.



Got any Android Question?