如何为新的 TabLayout material 组件设置 Tab 背景颜色

How to set Tab background color the new TabLayout material components

我正在使用新的material components我想实现这个设计

我找到了旧 TabLayout 的这些答案

How do I change the color of icon of the selected tab of TabLayout?

我认为新的 TabLayout 有更简单的方法来设置选项卡的背景并处理文本和图标颜色的变化

设置选项卡背景色的步骤如下:

首先是代码,然后是一些简短的解释:

代码:

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toTopOf="parent"
    app:tabBackground="@drawable/tab_background_color_selector"
    app:tabIconTint="@color/tab_content_color_selector"
    app:tabIndicator="@null"
    app:tabSelectedTextColor="@color/md_white_1000"
    app:tabTextColor="@color/secondaryColor">

    <com.google.android.material.tabs.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:icon="@drawable/ic_list"
        android:text="list" />

    <com.google.android.material.tabs.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:icon="@drawable/ic_calender"
        android:text="calender" />
</com.google.android.material.tabs.TabLayout>

drawable/tab_background_color_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/secondaryColor" android:state_selected="true" />
    <item android:drawable="@color/md_white_1000" />
</selector>

颜色/tab_content_color_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/md_white_1000" android:state_selected="true" />
    <item android:color="@color/secondaryColor" />
</selector>

解释

tabBackground: 是选项卡背景,应该是 drawable 选择器。

tabIconTint:用于图标颜色,它必须是我的 color 选择器。

tabIndicator="@null" : 因为它在这种情况下没用。

tabSelectedTextColortabTextColor 不言自明。