Tint does not work <21 version in DataBinding

Viewed 2575

I am using DataBinding to tint vector drawable of ImageView on basic of an boolean flag. This code works well for >=21 version. But fails in <21 version.

<androidx.appcompat.widget.AppCompatImageView
    android:tint="@{model.nextEnabled ? @color/primary : @color/silver}"
    app:srcCompat="@drawable/ic_right_blue_24dp"
    />

Here ic_right_blue_24dp is a vector drawable.

After checking binding class, I could see that code for <21 version is not getting generated.

       if(getBuildSdkInt() >= 21) {

            this.mboundView1.setImageTintList(androidx.databinding.adapters.Converters.convertColorToColorStateList(modelBackEnabledMboundView1AndroidColorPrimaryMboundView1AndroidColorSilver));
        }

I have tried all things I could think, and could find.

  • AppCompatImageView
  • ImageView
  • app:srcCompat
  • android:src
  • app:tint
  • vectorDrawables.useSupportLibrary = true
  • AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

Here I must tell you that all things work using regular tint without binding.

2 Answers

there still is custom data-binding. even exactly the method, as requested:

@BindingMethods({
    @BindingMethod(
        type = "androidx.appcompat.widget.AppCompatImageView",
        attribute = "android:tint",
        method = "setImageTintList"
    )
})

This BindingAdapter will set tint programmatically...and it worked for me

@BindingAdapter("android:tint")
fun AppCompatImageView.setImageTint(@ColorInt color: Int) {
    setColorFilter(color)
}

Usage

<androidx.appcompat.widget.AppCompatImageView
    android:tint="@color/primary"
    ...
    />
Related