更改所选选项卡的颜色

Changing the color of selected tab

我正在使用 tabLayout 在我的应用程序中使用选项卡。我想更改所选选项卡的背景颜色和文本颜色。我正在通过这样做

来改变整个 tabLayout 的背景颜色
 android:background="@color/colorAccent"

并更改文本颜色和选定的文本颜色

app:tabTextColor="#000000"
app:tabSelectedTextColor="@color/colorAccent"

但我现在只想更改选中该特定选项卡时的背景颜色?怎么做 ? 提前致谢:)

Change the background colour of tab in TabLayout is fairly simple using the design support library that Android provides. You can simply change the background of the whole TabLayout using the app:tabBackground property and you can change the tab indicator colour using the app:tabIndicatorColor property, but there are better ways if you want more functionality. A better way to change the tab-layout colour is using selectors, using selectors you can have different background for different sates of tab i.e selected, unselected etc.

请按照以下步骤操作:

1.创建一个可绘制对象 tab_selected_background,它将用作所选选项卡的背景

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorPrimary" />
    <corners android:radius="4dp" />
</shape>

2。创建一个选择器,tab_selector 将用作选项卡布局的背景:

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

3。现在终于创建标签布局并使用我们刚刚创建的选择器作为标签布局的背景。

  <android.support.design.widget.TabLayout
        android:id="@+id/subChordTabs"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        app:tabGravity="center"
        app:tabMode="scrollable"
        app:tabBackground="@drawable/tab_selector"
        app:tabIndicatorColor="@color/tabIndicator"
        android:padding="8dp"
        app:tabIndicatorHeight="2dp"/>

你得到如下结果,

您可以在选项卡布局小部件中这样做

<android.support.design.widget.TabLayout

    app:tabBackground="@drawable/selector"

    />

并在可绘制文件夹

中定义您的selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item 
     android:drawable="@color/tab_selected_color" 
     android:state_selected="true"/>
    <item 
     android:drawable="@color/tab_unselected_color"
     android:state_selected="false"/>
</selector>