【问题标题】:How we write raw string in a custom databinding attribute?我们如何在自定义数据绑定属性中编写原始字符串?
【发布时间】:2019-03-06 08:54:14
【问题描述】:

我为加载图像 url 编写了一个自定义属性,如下所示:

@BindingAdapter("srcCircleUrl")
fun loadCircleImage(view: ImageView, imageUrl: String) {
    loadImage(view.context, imageUrl, view, options = circleCropTransform())
}

当我想在 xml 中设置一个原始字符串时,它给了我srcCircleUrl attribute not found 错误。

例如,如果我写这样的东西,它就不起作用:

<ImageView
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:layout_marginBottom="16dp"
    app:srcCircleUrl="https://66.media.tumblr.com/97bcd9782631f8bef87bb30e830344a6/tumblr_owxu10zbPB1tl4ciuo4_250.png"
    android:scaleType="centerCrop"
    tools:srcCompat="@drawable/flag_iran" />

所以,问题是,如何将原始字符串作为自定义数据绑定属性的输入?


我也测试了这些方法:

app:srcCircleUrl="@{https://66.media.tumblr.com/97bcd9782631f8bef87bb30e830344a6/tumblr_owxu10zbPB1tl4ciuo4_250.png}"

app:srcCircleUrl="@{`https://66.media.tumblr.com/97bcd9782631f8bef87bb30e830344a6/tumblr_owxu10zbPB1tl4ciuo4_250.png`}"

【问题讨论】:

  • 没有图片库转换无法通过src Url加载图片
  • 试试这个样本,它会帮助你mobikul.com/data-binding-part-ii-image-binding
  • 当我从对象中获取字符串时,此方法也适用,例如@{item.imageUrl},我使用 Glide 在loadImage 方法中加载图像
  • 那是什么问题
  • @AravindV 问题是我们无法输入原始字符串,例如,链接作为此属性的输入

标签: android data-binding loadimage android-binding-adapter


【解决方案1】:

您需要用单引号和大括号将字符串括起来,例如app:something='@{"my string"}'

我认为这应该适合你:

<ImageView
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:layout_marginBottom="16dp"
    app:srcCircleUrl='@{"https://66.media.tumblr.com/image.png"}'
    android:scaleType="centerCrop"
    tools:srcCompat="@drawable/flag_iran" />

【讨论】:

    【解决方案2】:

    我认为你需要从数据绑定资源返回 url 格式你不能直接将 https url 传递给 app:srcUrl

    @BindingAdapter("imageUrl")
        public static void setImageUrl(ImageView view, String imageUrl) {
           Picasso.with(view.getContext())
                    .load(imageUrl)
                    .placeholder(R.drawable.placeholder)
                    .into(view); 0));
        }
    
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto">
        <data>
            <variable name="prod" type="com.webkul.example.Product"/>
        </data>
    <ImageView
      android:id="@+id/image"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:gravity="center"
      app:imageUrl="@{prod.img_url}"/>
    </layout>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-19
      • 2020-07-20
      • 1970-01-01
      相关资源
      最近更新 更多