CookieMonster
CookieMonster

Reputation: 502

What are the differences in using onClick in the xml and button.setOnClickListener in the activity?

As far as I can tell, there are two ways to implement a button click in android. One is by defining android:onClick="someFunction" and another is by having a listener in the activity. What I want to know is:

  1. Are they the same and if I can use them interchangeably.
  2. Are there things I can do with one and not the other? Any limitations?
  3. Is it just up to opinion which is better practice?

Upvotes: 0

Views: 57

Answers (2)

CommonsWare
CommonsWare

Reputation: 1006724

One is by defining android:onClick="someFunction" and another is by having a listener in the activity.

Not exactly. Your choices are:

  1. Use android:onClick, pointing to a method in the activity that hosts this widget, using the native implementation of this (what we have had since Android 1.6)

  2. Call setOnClickListener() on the View, passing in an implementation of an OnClickListener

  3. Use the data binding framework to tie android:onClick to an arbitrary method or an arbitrary lambda expression

Are they the same and if I can use them interchangeably.

They are the same, insofar as both define behaviors to be invoked if the user clicks the widget.

Are there things I can do with one and not the other? Any limitations?

Option #1 is limited to methods implemented on the hosting activity. Option #2 and Option #3 are not. With those, you can implement the logic to be invoked on a click event as part of some UI controller or presenter, such as a fragment.

Is it just up to opinion which is better practice?

Well, pretty much everything is up to opinion.

IMHO, Option #1 is fine for trivial apps, such as book examples. Option #3 is new but powerful, and I anticipate that this will be the long-term solution.

Upvotes: 2

Neh
Neh

Reputation: 452

android:onclick can be used to handle clicks directly in the view's activity without need to implement any interface.

android:onClick is for API level 4 onward, so if you're targeting < 1.6, then you can't use it.

An OnClickListener enables you to separate the action of the click event from the View that triggers the event.

You can refer this thread for more details Android onClick in XML vs. OnClickListener

Hope this helps

Upvotes: 0

Related Questions