更改支持 ActionBar 选项卡指示器颜色

Change support ActionBar tabs indicator color

这是这个问题的后续问题:

ActionBar AppCompat change Tab indicator color

我正在使用支持操作栏并向其添加选项卡。我想更改指示器颜色。我尝试做的是:

 <style name="CustomActivityTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
            <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/MyActionBar</item>
        <item name="android:actionBarTabStyle">@style/MyActionBarTabViewStyle</item>
        <item name="actionBarTabStyle">@style/MyActionBarTabViewStyle</item>
    </style>

<style name="MyActionBarTabViewStyle" parent="@android:style/Widget.Holo.Light.ActionBar.TabView">
        <item name="android:background">@color/White</item>
    </style>

这会更改整个选项卡的颜色,但我只想更改指示器的颜色。我在这里做错了什么?

试试这个:

  1. 为应用、操作栏和选项卡创建主题。我们需要 将选项卡的背景设置为 “tab_bar_background” 可绘制。

    res/values/styles.xml

    <style name="FindMyTrain" parent="Theme.Sherlock">
        <item name="android:actionBarTabStyle">@style/FindMyTrain.ActionBar.Tab</item>
        <item name="actionBarTabStyle">@style/FindMyTrain.ActionBar.Tab</item>
    </style>
    
    <style name="FindMyTrain.ActionBar.Tab">
        <item name="android:background">@drawable/tab_bar_background</item>
    </style>
    
  2. res/drawable/tab_bar_background中添加颜色状态列表

     <?xml version="1.0" encoding="utf-8"?>
    
    <selector
    xmlns:android="http://schemas.android.com/apk/res/android">   <item
    android:state_focused="false" android:state_selected="false"
    android:state_pressed="false"
    android:drawable="@color/transparent"/>   <item
    android:state_focused="false" android:state_selected="true"
    android:state_pressed="false"
    android:drawable="@drawable/tab_bar_background_selected"/>   <item
    android:state_selected="false" android:state_pressed="true"
    android:drawable="@color/tab_highlight"/>   <item
    android:state_selected="true" android:state_pressed="true"
    android:drawable="@drawable/tab_bar_background_selected_pressed"/>
    </selector>
    

    这里可以自定义标签栏按下和选中状态的颜色。

  3. res/drawable/tab_bar_background_selected

     <?xml version="1.0" encoding="utf-8"?>
     <layer-list
        xmlns:android="http://schemas.android.com/apk/res/android">
            <item android:top="-5dp" android:left="-5dp" android:right="-5dp">
                <shape android:shape="rectangle">
                    <stroke android:color="#ff4ba587" android:width="5dp"/>
                </shape>
            </item> </layer-list>
    
  4. 现在应用主题:

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/FindMyTrain"
        android:name=".FindMyTrainApplication" >
    

输出:

有关详细文档,请参阅此 Link

您可以使用它来更改指示器颜色。

TabLayout.setSelectedTabIndicatorColor(int color)