KG6ZVP KG6ZVP - 6 months ago 80
Android Question

Android onClick in XML vs. OnClickListener

I realize that a similarly-worded question has been asked before, but this is different. I am pretty new at developing android apps and I have three questions regarding the difference(s) between the

XML attribute and the

  1. What are the differences between the two? Is the difference between the two implementations found at compile time or run time or both?

  2. What use cases are favorable to which implementation?

  3. What difference(s) does the use of fragments in Android make in implementation choice?


Difference Between OnClickListener vs OnClick:

  • OnClickListener is the interface you need to implement and can be set to a view in java code.
  • OnClickListener is what waits for someone to actually click, onclick determines what happens when someone clicks.
  • Lately android added a xml attribute to views called android:onclick, that can be used to handle clicks directly in the view's activity without need to implement any interface.
  • You could easily swap one listener implementation with another if you need to.
  • An OnClickListener enable you to separate the action/behavior of the click event from the View that triggers the event. While for simple cases this is not such a big deal, for complex event handling, this could mean better readability and maintainability of the code
  • Since OnClickListener is an interface, the class that implements it has flexibilities in determining the instance variables and methods that it needs in order to handle the event. Again, this is not a big deal in simple cases, but for complex cases, we don't want to necessary mix up the variables/methods that related to event handling with the code of the View that triggers the event.
  • The onClick with function binding in XML Layout is a binding between onClick and the function that it will call. The function have to have one argument (the View) in order for onClick to function.

Both function the same way, just that one gets set through java code and the other through xml code.

setOnClickListener Code Implementation:

Button btn = (Button) findViewById(;

btn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {

// some more code

public void myFancyMethod(View v) {
    // does something very interesting

XML Implementation:

<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="@+id/mybutton"
    android:text="Click me!"
    android:onClick="myFancyMethod" />
<!-- even more layout elements -->


Both are the same in performance. Xml is pre-parsed into binary code while compiling. so there is no over-head in Xml.


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