Home » Android » Button setOnClickListener() vs android:onclick

Button setOnClickListener() vs android:onclick

Posted by: admin June 15, 2020 Leave a comment

Questions:

To register an OnClickListener I always call setOnClickListener(listener) on the Button. Now I have seen a piece of code where the click event is defined in the layout, by using android:onclick="nameOfMethod" and implement the method with a View parameter.

Are there any differences in these two ways of adding an OnClickListener? Which one is recommended?

How to&Answers:

The onClick with function binded in XML is a bind between onClick and the function that it calls. The function will have only one argument in order for onClick to function.

An OnClickListener is an interface that any class could implement. Since it is an interface that any class could implement, this is more flexible.

You could easily swap one listener implementation with another if you need to.

An OnClickListener enables 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

In other words –

XML onClick is good for one fixed implementation in your Java code.
OnClickListener is better for more complex codes and multiple buttons. But as for the basic function – they both do the exact same thing.

Answer:

Are there any differences in these two ways of adding an OnClickListener? Which one is recommended?

No they are not different and both will work, but from my experience I don’t recommend you to use the xml onClick option for one simple reason xml layout files were created as their name to represent layouts and represent the visual aspect of what ever you design.

Leave the java part, to the java files : )

Answer:

I had

I activity layout I could define method to call

    <TextView
        android:id="@+id/search_hot_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:onClick="onClickHotWords"
        android:text="@string/search_hot"
        />

then in Java

// defined in layout/search.xml
public void onClickHotWords(View v){
    FSLogcat.d(TAG, "onClickHotWords");
    requestHotWords();
}

but I had to rewrite that to with
mSearchHotWordsLabel.setOnClickListener(new OnClickListener() {
when using that layout inside fragment.

Also there is proguard related problem with mSearchHotWordsLabel
see android:onClick not working with ProGuard