Data Binding with srcCompat

Ishaan Garg picture Ishaan Garg · Mar 3, 2016 · Viewed 12.7k times · Source

I'm using the new vector drawable support in Support Lib v23.2 with app:srcCompat & trying to set its drawable via data binding.

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

<data>
    <variable
        name="mediaPojo"
        type="in.ishaan.pika.data_binding.MediaPojo"/>
</data>

<RelativeLayout
    android:background="@color/black"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <VideoView
        ... />

    <ImageView
        ...
        app:srcCompat="@{mediaPojo.isPlaying ? @drawable/ic_pause_24dp : @drawable/ic_play_arrow_24dp}"
    />

    <ProgressBar
        .../>
</RelativeLayout>
</layout>

On trying to build, studio throws:

Error:(33, 30) Cannot find the setter for attribute 'app:srcCompat' with parameter type android.graphics.drawable.Drawable.

Answer

lukjar picture lukjar · Mar 10, 2016

You can simply use android:src attribute instead compat attribute when you set vector resource by DataBinding.

DataBinding library generates class that execute setImageResource method at runtime.

<ImageView
        ...
        android:src="@{@drawable/your_drawable}"
/>

According to http://android-developers.blogspot.com/2016/02/android-support-library-232.html setImageResource method can be used at runtime on older system versions without any additional changes.

If you would like to use app:srcCompat attribute. You must define @BindingMethods annotation which connects attribute with appropriate setter from ImageView. For example in your Activity or Fragment add.

@BindingMethods({
    @BindingMethod(type = android.widget.ImageView.class,
            attribute = "app:srcCompat",
            method = "setImageDrawable") })
public class MainActivity extends AppCompatActivity {
   // your activity body here

}