How exactly does the android:onClick XML attribute differ from setOnClickListener?

Solution 1:

No, that is not possible via code. Android just implements the OnClickListener for you when you define the android:onClick="someMethod" attribute.

Those two code snippets are equal, just implemented in two different ways.

Code Implementation

Button btn = (Button) findViewById(R.id.mybutton);

btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        myFancyMethod(v);
    }
});

// some more code

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

Above is a code implementation of an OnClickListener. And this is the XML implementation.

XML Implementation

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

In the background, Android does nothing else than the Java code, calling your method on a click event.

Note that with the XML above, Android will look for the onClick method myFancyMethod() only in the current Activity. This is important to remember if you are using fragments, since even if you add the XML above using a fragment, Android will not look for the onClick method in the .java file of the fragment used to add the XML.

Another important thing I noticed. You mentioned you don't prefer anonymous methods. You meant to say you don't like anonymous classes.

Solution 2:

When I saw the top answer, it made me realize that my problem was not putting the parameter (View v) on the fancy method:

public void myFancyMethod(View v) {}

When trying to access it from the xml, one should use

android:onClick="myFancyMethod"/>

Hope that helps someone.

Solution 3:

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

Solution 4:

Check if you forgot to put the method public!