How to set Image resource to ImageView using DataBinding

George Thomas picture George Thomas · Jan 5, 2016 · Viewed 64.2k times · Source

How can we use data binding in android to put image resource in an ImageView?

  <ImageView
            android:id="@+id/is_synced"
            android:src="@{model.pending ? @mipmap/pending: @mipmap/synced}"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

I want an image if pending is true and another image if pending is false. But it's showing error.How can I achieve this functionality?

Answer

qinmiao picture qinmiao · Jun 7, 2016

The answer:

define:

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

use:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:scaleType="center"
    android:src="@{viewModel.imageRes, default=@drawable/guide_1}"/>