0

用例有一个 DatabindingAdapter,它相应地更改 viewHolder 项的 Drawable 颜色。

@BindingAdapter("setBackgroundColor")
fun setColor(imageView: ImageView, id: String) {
imageView.background =
    (ContextCompat.getDrawable(
        imageView.context,
        R.drawable.background_corner_right
    ) as LayerDrawable?)?.run {
        imageViewBackground =
            (findDrawableByLayerId(R.id.corneredDrawable) as GradientDrawable)
                .apply {
                    mutate()
                }
        this
    }
imageViewBackground?.setColor(Color.parseColor(id))
}

在 XML 部分:

     <ImageView
        android:id="@+id/iv_color"
        android:layout_width="50dp"
        android:layout_height="30dp"
        setBackgroundColor="@{contractType.color}"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintHorizontal_bias="0.0"/>

这工作得很好,但我想通过不明确调用findDrawableByLayerId来优化更多,R.drawable.background_corner_right

无论如何我可以将这些在 Xml 中作为参数传递到 BindingAdapter 中吗?这将使 BindingAdapter 更加通用和可重用

4

1 回答 1

0

事实证明,我可以在其索引列出的图层中访问我的 DrawableLayer,因此(findDrawableByLayerId(R.id.corneredDrawable) as GradientDrawable)(findDrawableByLayerId(getId(0)) as GradientDrawable)替换

至于背景本身,我将它添加到 XML 并由(imageView.background as LayerDrawable)调用它

解决。

于 2020-04-15T12:57:57.363 回答