Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 444
RandomNickName42 Avatar asked Mar 23 '11 02:03

RandomNickName42


People also ask

What is the purpose of using OnClickListener?

In Android, the OnClickListener() interface has an onClick(View v) method that is called when the view (component) is clicked. The code for a component's functionality is written inside this method, and the listener is set using the setOnClickListener() method.

What is the difference between Ontouch and onClick Android?

Use OnTouchListener when you want to receive events from someone's finger on the screen. Use OnClickListener when you want to detect clicks.

Which are the ways to set OnClickListener for button in Android?

To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

What does onClick mean in Android Studio?

OnClickListener, you can defined your click of each button in method public void onClick(View v) . Keyword this refer to the method onclick. It is good to use this way when there are a lot of button in your class file.


1 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.

like image 113
mgv Avatar answered Sep 21 '22 14:09

mgv