3

I've been trying to apply a backgroundTint to a ConstraintLayout element having a Drawable background. However, the tint is not applied and the layout has the same background color as the drawable (only in API 21; works fine from API 23 upwards). It doesn't work with LinearLayout and GridLayout either, so I think it might be something to do with ViewGroups. Here's a simplified version of the element.

 <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:background="@drawable/mybackground"
        android:backgroundTint="#ff0000">

        <!--Sub views here-->

 </LinearLayout>

And here's the background drawable.

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#ffffff"/>
    <corners android:radius="10dp"/>
</shape>

How do I fix this?

2 Answers2

2

I'm not quite sure what the problem is, but I've found a workaround which works for API 21.

view.getBackground().setColorFilter(tint_color, PorterDuff.Mode.SRC_OVER);

has the same effect as

view.setBackgroundTintList(ColorStateList.valueOf(tint_color));
0

I think it might be a problem with LinearLayout try to use LinearLayoutCompat to support older API.

<androidx.appcompat.widget.LinearLayoutCompat
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/mybackground"
    android:backgroundTint="#ff0000"
    android:orientation="vertical">

    <!--Sub views here-->

</androidx.appcompat.widget.LinearLayoutCompat>

What's the difference between LinearLayout and LinearLayoutCompat Here You can read a little about differences

iknow
  • 8,358
  • 12
  • 41
  • 68
  • This didn't work. backgroundTint was introduced in API 21, so it can't be a compatibility issue, right? Anyway, thanks for the help. – clifordjoshy Aug 08 '20 at 03:20
  • Yeah, maybe You just can't use `backgroundTint`. You should see a yellow warning in Android Studio: `Attribute backgroundTint is only used in API level 21 and higher (current min is 19)`, click `alt + Enter` ➡ `Override Resource in layout -v21`. You will have 2 layouts one for API lower than 21 and one for 21 or higher. So You will be able so use different layout look on old API. Also, based on [this](https://stackoverflow.com/questions/48825405/why-backgroundtint-requires-android-prefix-after-api-21-but-not-before/53826131) You can try to use `app:backgroundTint` with `LinearLayoutCompat` – iknow Aug 08 '20 at 12:42