android - 如何使用 DataBinding 将 Image 资源设置为 ImageView

标签 android xml android-databinding

我们如何在android中使用数据绑定(bind)将图像资源放入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,我想要一张图片。但它显示错误。我怎样才能实现这个功能?

最佳答案

我试过这个,它对我有用(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()

关于android - 如何使用 DataBinding 将 Image 资源设置为 ImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34607028/

相关文章:

android - 适用于 Android 和 iOS 的 MQTT over websocket

java - 如何通过socket InputStream发送XML数据

xml - 寻找 Excel 的 .xlsx XML 格式的清晰描述

android - 如何在 DataBinding 中包含 XML 绑定(bind)

android - 如何使用 DataBinding Framework MVVM 在 EditText 上设置错误

Android Studio完全找不到新的资源文件夹

android - 使用 Android Volley 发出 HTTPS 请求

android - 如何使用 Android 数据绑定(bind)库制作粗体文本

android - 解析 xml 时出错 : Unbound prefix with the Facebook SDK

php - 如何存储(在 php 中)和使用(在 javascript 中)大量数据