In Android; is it better applying an OnClickListener or use android:onClick?

Will the performance be any better using onClick? If I use onClick I do not have to set an android:id (also avoid's a new View.OnClickListener), does this improve performance at all? Or is the same effect of a findViewById occuring behind the scenes?

This page gives both methods as an option but little guidance on any benifit.

http://developer.android.com/reference/android/widget/Button.html

Here's a blog post where they deem onClick as "easier" and an "improvement" for post 1.6 applications;

http://android-developers.blogspot.com/2009/10/ui-framework-changes-in-android-16.html

This new feature reduces both the amount of Java and XML you have to write, leaving you more time to concentrate on your application.

Answers


I believe that the inclusion of android:onClick has been a very bad idea.

  1. You are coupling presentation with logic
  2. Unless you are using a plugin that supports it, you will have to remember to refactor the xml file if you decide to change your method name
  3. It's just not clear the relationship between a button in your xml and a method in your activity that reacts to the click events unless you explicitly see it defined in your Java file. With the android:onClick approach you can even forget that you have a button in your layout or which is the method that is handling its onClick event.

I would suggest you stick to defining your OnClickListeners programatically and keep a strict separation of concerns, as Corey Sunwold pointed out in his comment.


I am trying to think about how to test this.... But I believe there is no performance difference between the two, they are just different interfaces for the same thing.


I use android:onClick when I just need my Button to be clickable.

If I need to do something else to the Button, for example enable/disable it, I would use setOnClickListener() as mgv said.

Also remember that android:onClick doesn't work in Android 1.5.


You might consider using an onTouchListener instead. I've found it to be faster, particularly if you want the action to occur on press as opposed to release.


Need Your Help

The incorrect localhost certificate is being served by IIS

iis ssl ssl-certificate

OK I have a SSL issue that I can't seem to get past on this 1 Win7 x64 machine. I have been using self-signed certs for years and even blogged about them before so I have experience. However someth...

Register a C#/VB.NET COM dll programmatically

c# vb.net com dll com-interop

Question: I have a .NET dll which I use from a C++ program.