Android - OnClick Listener in a separate class Android - OnClick Listener in a separate class android android

Android - OnClick Listener in a separate class


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.


Instead of putting the onCLicklistener in a separate class, why dont you try to define onClickListener outside onCreate()??

For e.g: like this

onCreate()

yourViewName.setOnClicklistener(listener):

Outside onCreate()

private OnClickListener listener    =   new OnClickListener() {        @Override        public void onClick(View v) {            // TODO Auto-generated method stub        }    };


Yes you can. However, making the listener an inner class has one advantage - it can access the fields and variables of your activity class directly. If you make it a separate class, and your listener actually need to access 5 views, your listener constructor might look like this:

MyListener listener = new MyListener(context, button, textView1, textView2, ratingBar, imageView);

Which is kinda bulky too. If your listener is simple, go ahead and make it a separate class. Otherwise, its up to you for readability.