【问题标题】:Change background image using data binding (Kotlin)使用数据绑定 (Kotlin) 更改背景图像
【发布时间】:2022-01-08 22:10:37
【问题描述】:
<androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/gameConstraintLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="15dp"
        android:background="@{model.image}"
        tools:context=".ui.color_game.view.CakeFragment">

我使用这些代码,但它不起作用

【问题讨论】:

    标签: xml kotlin


    【解决方案1】:

    我假设(因为我们将模型的属性绑定到 backgroundmodel.image 不是可绘制的 image 可能是指向在线图像资源的 String URL。但是,即使两者都不是,解决方案的主体是相同的。

    我们需要一种方法将我们的String URL 转换为 Drawable 并将其设置为背景。 Android 无法知道如何做到这一点。因为,它甚至不知道传递的值是否是 URL(可能是十六进制颜色或其他任何东西)。

    Android 数据绑定为我们提供了一种方法@BindingAdapter

    您需要做的就是创建一个静态方法,如下所示:

    class BindingAdapter {
        @JvmStatic
        @BindingAdapter("app:background")
        fun bindsUrlImageAsBackground(view: View, url: String) {
            // Use your image loading library/mechanism to load the image
            // and then bind it to view's background by calling
            // view.setBackground.
        }
    }
    

    此方法中需要注意的几点。

    • String "app:background" 将是 xml 属性,它将替换布局文件中的 "android:background"
    • 该方法的第一个参数必须是layout中的View的类型或其父类。
    • 第二个参数必须是您在布局文件中传递的 URL,因此model.image 的类/类型必须与第二个参数匹配。

    【讨论】:

      猜你喜欢
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多