0

Im looking through a project here and it has a way of using onClick that is different to what ive seen any other time.

Usually you set the listener for the button during onCreate or whatever.

Here in the activities xml it has android:onClick="navigateToUrl". Then this seems to kick off the method navigateToUrl in the classes code.

Im just wondering what is the difference between the two methods?

discodowney
  • 1,475
  • 6
  • 28
  • 58
  • 1
    possible duplicate of [How exactly does the android:onClick XML attribute differ from setOnClickListener?](http://stackoverflow.com/questions/4153517/how-exactly-does-the-androidonclick-xml-attribute-differ-from-setonclicklistene) – Spaceman Spiff May 20 '15 at 18:55

2 Answers2

2

They work the same way. With the xml version, the framework adds an onClickListener during inflation that uses reflection on the Context its called from looking for a function with that name, and calls it. So its slightly less efficient, but not enough to really get worried about. The big advantage is a less cluttered onCreate, the big disadvantage is that to figure out what a view does when clicked you have to read xml rather than code. Which you use is a matter of personal preference. I'm currently in the explicit onClickListener group, because I prefer not to have behind the scenes magic.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
  • Okay. Threw me at first, hadnt a clue how the thing was working or why using go to declaration kept bringing me to the xml. Thanks for the answer. – discodowney May 20 '15 at 19:21
0

For the latter, you need to keep a public method always. If you do not want to keep your method publicly visible, you would prefer to have a listener implemented.

Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33