How to set Image resource to ImageView using DataBinding [duplicate]
Solution 1:
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.
Solution 2:
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}"/>
Solution 3:
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" />
Solution 4:
If you would like to pass an argument into the method like an @IdRes
you can use
XML:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import type="<package_name>.R" />
</data>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:load_image="@{R.drawable.image}" />
</layout>
Code
@BindingAdapter("load_image")
public static void loadImage(ImageView view, @IdRes int imageId) {
//Logic
}
Solution 5:
You can do this without doing anything programmatically if your data model contains the resource ID of the image.
Example:
<layout>
<data>
<import type="android.support.v4.content.ContextCompat" />
<variable
name="roomInfoItem"
type="com.example......model.RoomInfoModel" /> </data>
<RelativeLayout>
<ImageView
android:id="@+id/iv_room_info_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
</layout>
Just add the following line to your imageView (I wasn't able to format the code when I was adding it there):
android:src="@{ContextCompat.getDrawable(context,roomInfoItem.resId)}"
where resId
contains R.drawable.your_image_name