Android Studio "UsingOnClickInXml" warning

Viewed 2116

Recently Android Studio shows me a warning in the onClick element of my xml views.

Use databinding or explicit wiring of click listener in code

Suppress Add tools:ignore="UsingOnClickInXml" attribute

This is my View:

<ImageView
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:layout_gravity="center"
    android:scaleType="fitCenter"
    android:src="@drawable/ic_web_white_24dp"
    android:clickable="true"
    android:focusable="true"
    android:onClick="openSite" />

What is the meaning of the warning? What's wrong in using android:onClick?

Edit: I know the difference between setting the onClick on xml and declaring the onClickListener in the Activity but I want to know why the last one is preferable.

1 Answers

Android will set the onClick Listener as if you did it yourself. The difference is that you have to implement the method you put in android:onClick in the current Activity, which might be a problem if you're using fragments.

If you have many buttons, you can litter the Activity with methods that do not belong there. The most common use case where that would be a problem is a single-activity application. If you use 40-50 fragments and only set listeners on the XML (which isn't always possible, I don't think you can do it on a RecyclerView for example), then you have to implement all the listeners in the only Activity your app has. I don't want to imagine how messy that would be.

It has been extensively discussed in this answer's comments

It's not an error, it is a warning so you can ignore it if you like but it's best if you don't.

Related