android:onClick warning: "Use databinding or explicit wiring of click listener in code"

Viewed 7426

Hello this is my first time using onClick in an xml instead of in code. This is the layout:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/reset"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:contentDescription="@string/reset"
        android:scaleType="fitCenter"
        android:scaleX="-1"
        android:onClick="reset"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/resetIcon" />

</androidx.constraintlayout.widget.ConstraintLayout>

And in the code:

public class SettingsActivity extends AppCompatActivity {

    public void reset(View view) {
        //Do things
    }

}

As the title says, android:onClick gives the warning

Use databinding or explicit wiring of click listener in code

Googling this statement gives no results.

2 Answers

onClick is kind of discouraged. You can use it, but it sets up some hard to follow magic in the code, and ties a particular layout to an activity implicitly. The preferred way to do it is the two they mentioned- either set an onClickListener in the code, or use databinding if you're using that technique throughout your codebase. There's also no way to compile time check that its actually wired up correctly. The only reason onclick in xml hasn't been removed is because databinding uses it, and to not break older apps.

So it'll work, but you probably just shouldn't use it unless using databinding and specifying the behavior in xml.

It is deprecated since Android API 31.

This constant was deprecated in API level 31. View actually traverses the Context hierarchy looking for the relevant method, which is fragile (an intermediate ContextWrapper adding a same-named method would change behavior) and restricts bytecode optimizers such as R8. Instead, use View.setOnClickListener.

Related