Joseph Woodward
Joseph Woodward

Reputation: 9281

What is the correct way to implement an OnClickListener

With so many ways of implementing an OnClickListener within Android, I'm wondering whether there's a best practice or a more recommended way of doing it over the others (ie: I remember reading certain ways require more memory than others)?

At the moment I know of four ways to implement the OnClickListener, these are:

  1. Make your Activity implement an OnClickListener interface.
  2. Inner Class OnClickListener.
  3. Inline Class OnClickListener.
  4. Use android:onClick attribute in XML definition of a Button.

Out of the four options I'm leaning towards the XML implementation as it seems cleaner, can anyone else give their opinion?

Upvotes: 2

Views: 370

Answers (2)

La bla bla
La bla bla

Reputation: 8708

I don't know regarding memory efficiency, but Here's my approach.

  1. I don't like it, It requires multiple if-else (or switch) inside your onClick if you have multiple buttons
  2. I use this if the 3rd option causes my method, for example onCreate() to be too big and messy
  3. My favorite. it allows you to find out what each button does very easily, but I use it usually if its onClick isn't too long, to keep the code readable
  4. I hardly use it, it keeps the code cleaner, but I'm not used to this one, since I don't use it in Java's SWING.

But in the bottom line, like @Lazy_Ninja said, it all comes down to taste. All 4 of them works.

I think what matters, when choosing, is keeping the code clean and readable.

Upvotes: 2

Lazy Ninja
Lazy Ninja

Reputation: 22527

Well it depends. At first I used to like the number 1(Make your Activity implement an OnClickListener interface) because the source look neat that way.
But at the end I settled with 2.Inner Class OnClickListener, because I found it more easier to read and more easier to implement, especially if you use eclipse and know the shortcuts of auto completion.
At the end I think it depends on taste.

Upvotes: 1

Related Questions