0

What are the differences between applying "OnClickListener" and adding a function to related XML file to add an action for a button? Which way is more useful in what conditions?

antonv
  • 1,227
  • 13
  • 21
user2870
  • 477
  • 7
  • 18

2 Answers2

1

A great article about button click here: http://martin.cubeactive.com/android-onclicklitener-tutorial/ Its main idea is that you have two options:

  1. subscribe programatically

    1.1. Inline OnClickListener implementation with anonymous class.

    1.2 By implementing OnClickListener in your class (usually your Activity).

  2. set button onClick attribute in the xml with the name of the handler method.

What is more useful is debatable, but It seems better to use xml onClick attribute if you have many buttons and each needs its own handler.

Another good approach is to assign all buttons to use the same handler on click and then - in the handler method - make switch according to what button was clicked (the view parameter is a refference to the clicked button).

antonv
  • 1,227
  • 13
  • 21
0

When you add listener from xml, you could have diffrent actions for diffrent conditions (language, dimensions etc ) without writing conditional statements in ypur source code.

bongo
  • 733
  • 4
  • 12