How to apply backgroundTint to a ViewGroup for API 21?

Viewed 493

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 Answers

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));

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

Related