Set the tint of an ImageView using databinding
Asked Answered
H

5

14

I use databinding to set the tint of my ImageView. And this is working well :

android:tint="@{plantEntity.isFavorite ? @color/favorite : @color/favorite_none}" />

The problem is android:tint is deprecated. When I try to use app:tint instead, I have this error :

Cannot find a setter for <android.widget.ImageView app:color> that accepts parameter type 'int'

If a binding adapter provides the setter, check that the adapter is annotated correctly and that the parameter type matches.

Why and what I have to do ? Create a BindingAdapter ?

Hamforrd answered 29/11, 2020 at 9:1 Comment(0)
B
16

similar to what has been discussed on Tint does not work <21 version in DataBinding

add a binding adapter:

@JvmStatic
@BindingAdapter("app:tint")
fun ImageView.setImageTint(@ColorInt color: Int) {
  setColorFilter(color)
}

and you don't have to use any compat if your minSdk is > 21 (which is a good deal anyway in 2021 you should not support anything below 26)

anyhow .. this seems to be a fug on the androidx.databinding expression https://issuetracker.google.com/issues/152953070

Budbudapest answered 8/3, 2021 at 19:23 Comment(1)
No need for the app: prefix in the Binding Adapter annotation.Yila
H
9

It's working and using androidx.appcompat.widget.AppCompatImageView.

And app:tint is no more deprecated.

Hamforrd answered 29/11, 2020 at 9:15 Comment(3)
android:tint is deprecated. but is not deprecated if you use androidx.appcompat.widget.AppCompatImageView instead of ImageViewKlinges
Must use app:tint instead of android:tintMcquoid
Quite the opposite - use android:tintElzaelzevir
E
5

Use androidx.appcompat.widget.AppCompatImageView with android:tint.

Elzaelzevir answered 23/3, 2022 at 11:35 Comment(0)
C
2

Just to complement @Jéwôm's answer with a clear example, use AppCompatImageView with android:tint

<androidx.appcompat.widget.AppCompatImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:tint="@{data.yourImageTintColorRes}"
    android:src="@drawable/yourDrawable"/>
Church answered 6/6, 2023 at 15:10 Comment(0)
C
0

Add variable

<variable name="color" type="Integer" />

and...

android:background="@{color == 0 ? @color/black : color == 1 ? @color/red: @color/purple_200 }"

On the code, set the value

 binding.color = 0
Charlatanism answered 17/6, 2022 at 14:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.