如何使用 DataBinding 将图像资源设置为 ImageView

How to set Image resource to ImageView using DataBinding

我们如何使用android中的数据绑定将图像资源放入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" />

如果 pending 为 true,我想要一个图像;如果 pending 为 false,我想要另一个图像。但是显示 error.How 我可以实现这个功能吗?

更多详细信息请参阅此处 Details 使用数据绑定和 Picasso 加载图像

public class ProfileViewModel {
// The URL will usually come from a model (i.e Profile)
static final String IMAGE_URL = "http://cdn.meme.am/instances/60677654.jpg";
public ObservableField<Drawable> profileImage;
private BindableFieldTarget bindableFieldTarget;

public ProfileViewModel(Context context) {
    profileImage = new ObservableField<>();
    // Picasso keeps a weak reference to the target so it needs to be stored in a field
    bindableFieldTarget = new BindableFieldTarget(profileImage, context.getResources());
    Picasso.with(context)
            .load(IMAGE_URL)
            .placeholder(R.drawable.placeholder)
            .into(bindableFieldTarget);
}

public class BindableFieldTarget implements Target {

    private ObservableField<Drawable> observableField;
    private Resources resources;

    public BindableFieldTarget(ObservableField<Drawable> observableField, Resources resources) {
        this.observableField = observableField;
        this.resources = resources;
    }

    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        observableField.set(new BitmapDrawable(resources, bitmap));
    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) {
        observableField.set(errorDrawable);
    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {
        observableField.set(placeHolderDrawable);
    }
}
}

根据这篇很棒的文章:Loading images with Data Binding and Picasso

有两种方法:

  1. 使用@BindingAdapter
  2. ObservableField & 自定义毕加索目标

在 Android 开发人员参考 Data Binding Guide 中,您只会找到第一个。

请阅读这两篇文章。

更多信息:

希望对您有所帮助。

像这样设置图像,

  <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" />

:

定义:

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

使用:

<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}"/>

我试过了,对我有用 (buildToolsVersion: 24.0.1):

<ImageView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_margin="8dp"
    android:scaleType="centerInside"
    app:imageResource="@{item.avatarResId}"/>

只需使用 app:imageResource 替换 android:srcandroid:src="@{item.avatarResId}" 不起作用,否则为其定义自定义 @BindAdapter("android:src")

但是使用app:imageResource不需要另外定义一个@BindAdapter,因为ImageView有一个方法叫做setImageResource(),当你使用app:imageResource时,它会调用setImageResource() 自动。

<ImageView ...
        app:svg="@{@drawable/ic_car_placeholder}" />

然后

@BindingAdapter({"app:svg"})
public static void setImageViewResource(ImageView imageView, Drawable resource) {
    imageView.setBackgroundDrawable(resource);
}

问题在于所有具有相同名称的设置器的属性。例如android:x 如果 setX() 方法不在该视图中,则将无法工作同样,如果我们在 ImageView 上使用 setSrc() 方法,您的代码将在没有自定义绑定适配器的情况下工作

如果您的数据模型包含图像的资源 ID,则无需以编程方式执行任何操作即可执行此操作。

示例:

<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>

只需将以下行添加到您的 imageView(我在添加它时无法格式化代码):

android:src="@{ContextCompat.getDrawable(context,roomInfoItem.resId)}"

其中 resId 包含 R.drawable.your_image_name

如果您想像 @IdRes 一样将参数传递给方法,您可以使用

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>

代码

@BindingAdapter("load_image")
public static void loadImage(ImageView view, @IdRes int imageId) {
    //Logic
}