Set drawable resource ID in android:src for ImageView using data binding in Android

Answer as of Nov 10 2016

Splash’s comment below has highlighted that it is not necessary to use a custom property type (like imageResource), we can instead create multiple methods for android:src like so:

public class DataBindingAdapters {

    @BindingAdapter("android:src")
    public static void setImageUri(ImageView view, String imageUri) {
        if (imageUri == null) {
            view.setImageURI(null);
        } else {
            view.setImageURI(Uri.parse(imageUri));
        }
    }

    @BindingAdapter("android:src")
    public static void setImageUri(ImageView view, Uri imageUri) {
        view.setImageURI(imageUri);
    }

    @BindingAdapter("android:src")
    public static void setImageDrawable(ImageView view, Drawable drawable) {
        view.setImageDrawable(drawable);
    }

    @BindingAdapter("android:src")
    public static void setImageResource(ImageView imageView, int resource){
        imageView.setImageResource(resource);
    }
}

Old Answer

You could always try to use an adapter:

public class DataBindingAdapters {

    @BindingAdapter("imageResource")
    public static void setImageResource(ImageView imageView, int resource){
        imageView.setImageResource(resource);
    }
}

You can then use the adapter in your xml like so

<ImageView
    android:id="@+id/recipe_image_view"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:scaleType="centerCrop"
    imageResource="https://stackoverflow.com/questions/35809290/@{recipe.imageResource}" />

Be sure to notice that the name within the xml matches the BindingAdapter annotation (imageResource)

The DataBindingAdapters class doesn’t need to be declared anywhere in particular, the DataBinding mechanics will find it no matter (i believe)

Leave a Comment