1

I haven't quite figured out the preferred way to setup listeners in android. I tend to set up my listeners like this:

(First way)

myButton.setOnClickListener(this);

as opposed to

(Second Way)

myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //handle clicks
            }
        });

However I recently came across this question where one of the comments said:

...use of a smaller class to act as the listener interface vs passing the whole adapter to act as the interface.

To my understanding, inner classes have an implicit reference to the outer one so depending on how you set up the listener should have no affect on what object is passed in/referred.

Can some one clarify which is the better way and why? Is using this (First Way) more expensive than having an anonymous inner class (Second Way)?

Community
  • 1
  • 1
Naveed
  • 2,942
  • 2
  • 25
  • 58
  • I never noticed any difference of any kind. I choose first method if I need to add listeners to multiple views; second otherwise. – Rohit5k2 Feb 05 '15 at 18:10
  • Option three: Use an (non-anonymous) inner class. – nhaarman Feb 05 '15 at 22:43
  • I don't understand why @323go, eckes, Tom, Niek Harman, klossus are voting close as opinionated question? I am not asking for opinion on this. I just wanted to know which is more expensive and why as far as performance – Naveed Feb 06 '15 at 04:51

1 Answers1

0

It doesn't really matter which one do you use. But there are situations where one method is "better" then other. For example:

-If you have only a few clickable Views, then there is no need that the entire Activity implements OnClickListener interface. So in that case i would prefer your "second way".

-Otherwise if you have more clickable Views or if your Activity mostly contains clickable Views then your "first way" is preferred. It doesn't really make a big difference, but your code is more organized.

Also, you can read this post and find out what are the differences between those 2 methods.

Community
  • 1
  • 1
633kM
  • 300
  • 1
  • 9