androidkotlindata-bindingandroid-databindingandroid-binding-adapter

How to avoid explicitly call findDrawableByLayerId and getDrawable in a BindingAdapter


The use case is having a DatabindingAdapter that changes the Drawable color of a viewHolder item accordingly.

@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))
}

and in the XML part :

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

This works just fine ,but i want optimise more by not explicitly call findDrawableByLayerId,neither R.drawable.background_corner_right

is there anyway i can pass those in Xml and into the BindingAdapter as parameters ? this would make the BindingAdapter more generic and reusable


Solution

  • Turns out that i can access my DrawableLayer in the layer listed by its index ,so (findDrawableByLayerId(R.id.corneredDrawable) as GradientDrawable) get replaced by (findDrawableByLayerId(getId(0)) as GradientDrawable)

    as for the background itself, i added it to the XML and called it by (imageView.background as LayerDrawable)

    resolved.