In Android; is it better applying an OnClickListener or use android:onClick?
Will the performance be any better using onClick? 开发者_StackOverflowIf 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.
I believe that the inclusion of android:onClick
has been a very bad idea.
- You are coupling presentation with logic
- 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
- 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 itsonClick
event.
I would suggest you stick to defining your OnClickListener
s 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.
精彩评论