Android - OnClick Listener in a separate class

Pztar picture Pztar · Nov 21, 2012 · Viewed 32.5k times · Source

Is it possible to make a secondary class to hold the OnClick Listener? Meaning not being created in the Activity class?

I just find that putting OnClick listeners in the main activity class is just messy and I would rather have them in separate classes. Thanks

Answer

MH. picture MH. · Nov 21, 2012

Sure, that's possible. Just create a class that implements View.OnClickListener and set that as listener to the View. For example:

public class ExternalOnClickListener implements View.OnClickListener {

    public ExternalOnClickListener(...) {
        // keep references for your onClick logic 
    }

    @Override public void onClick(View v) {
        // TODO: add code here
    }

}

And then set an instance of above class as listener:

view.setOnClickListener(new ExternalOnClickListener(...));

The parameterized constructor is optional, but it's very likely you'll need to pass something through to actually make your onClick(...) logic work on.

Implementing a class anonymously is generally easier to work with though. Just a thought.