工具栏选定选项卡文本颜色 Android

Toolbar Selected Tab Text Color Android

我试图在我的一个 android 应用程序中为 Tab 文本设置自定义颜色,但改为更改它的设置白色。其他选项卡文本将更改,但仅针对所选选项卡不会更改。

我的标签样式如下

<style name="MineCustomTabText"
        parent="TextAppearance.Design.Tab">
       <item name="tabSelectedTextColor">#000</item>
       <item name="android:textColor">@color/TextColorLite</item>
        <item name="android:textSize">@dimen/textPageCount</item>
    </style>

我在我的布局中使用它XML如下所示

<android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            app:tabGravity="fill"
            app:tabTextAppearance="@style/MineCustomTabText"
            app:tabMode="fixed"
            android:layout_height="wrap_content" />

您可以看到我在样式中为选定的选项卡设置了黑色,但它只显示白色。让我知道我错过了什么。谢谢

试试下面的代码:

将此样式添加到您的 TabLayout

<android.support.design.widget.TabLayout
  style="@style/MyCustomTabLayout"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"/>

将此样式添加到您的 Style.xml

 <style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
        <!--<item name="tabMaxWidth">@dimen/tab_max_width</item>-->
        <item name="tabIndicatorColor">@color/appcolor</item>
        <item name="tabIndicatorHeight">2dp</item>
        <item name="tabPaddingStart">10dp</item>
        <item name="tabPaddingEnd">10dp</item>
        <item name="tabBackground">@color/lightblue</item>
        <item name="tabTextAppearance">@style/MyCustomTabTextAppearance</item>
        <item name="tabSelectedTextColor">@color/appcolor</item>
    </style>


    <style name="MyCustomTabTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">15sp</item>
        <item name="android:textColor">@color/black</item>
        <item name="textAllCaps">true</item>
    </style>

另一种以编程方式更改的方法:

 tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FF0000"));
    tabLayout.setSelectedTabIndicatorHeight((int) (5 * getResources().getDisplayMetrics().density));
    tabLayout.setTabTextColors(Color.parseColor("#727272"), Color.parseColor("#ffffff"));

希望对您有所帮助

在可绘制文件夹中添加 tab_text_color.xml,如下所示

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

然后在 style.xml 中执行此操作并检查

<style name="CustomTabPageIndicator.Text" parent="android:TextAppearance.Medium">
    <item name="android:textColor">@drawable/tab_text_color</item>
    ...
</style>