How to set Image resource to ImageView using DataBinding [duplicate]
I tried this, and it works for me (buildToolsVersion: 24.0.1):
<ImageView android:layout_width="50dp" android:layout_height="50dp" android:layout_margin="8dp" android:scaleType="centerInside" app:imageResource="@{item.avatarResId}"/>
just use app:imageResource
to replace android:src
, android:src="@{item.avatarResId}"
doesn't works else define a custom @BindAdapter("android:src")
for it.
but use app:imageResource
doesn't need define a @BindAdapter
additionally, because the ImageView has a method called setImageResource()
, when you use app:imageResource
, it will call setImageResource()
automatically.
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}"/>
set image like this,
<ImageView android:layout_width="28dp" android:layout_height="28dp" android:src="@{model.isActive ? @drawable/white_activated_icon :@drawable/activated_icon}" tools:src="@mipmap/white_activated_icon" />