How to change ActionBarSherlock Tab Text color?

2019-05-15 01:09发布

问题:

adapter.addTab(getSupportActionBar().newTab().setText("Tab-1"),
                Tab1.class, null);
adapter.addTab(getSupportActionBar().newTab().setText("Tab-2"),
                Tab2.class, null);
adapter.addTab(getSupportActionBar().newTab().setText("Tab-3"),
                Tab3.class, null);

As of now every Tab has its TextColor as white. I want it to be grey when not selected and white on selected. So, how can i change the text color in onTabSelected or onTabUnselected.

Or should i go with setCustomView for the tab?? Here again the TextSize and all needs to be taken care of

<style name="my_ActionBarTabStyle" parent="@style/Widget.Sherlock.ActionBar.TabView">
    <item name="background">@drawable/tab_indicator_ab_wicfy</item>
    <item name="android:background">@drawable/tab_indicator_ab_wicfy</item>
    <item name="android:textColor">@color/black</item>
</style>

i tried to use

<item name="textColor">@color/black</item>

but it gives me error that textColor is not a valid attribute

Thank You

回答1:

You should not change text color from the code. Use color state list resource instead.

Define the color selector in resources. Define a xml file in res/color/ directory. The file will contain:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- use when selected -->
    <item android:state_selected="true" android:color="#fff" />

    <!-- otherwise use -->
    <item android:color="#888" />
</selector>

And then set the text color in a style:

<item name="android:textColor">@color/my_color_selector</item>

Edit:

You have to set the text color in the right place in the styles! Set the textColor in (android:)actionBarTabTextStyle. The theme has to contain:

<style name="MyTheme" parent="Theme.Sherlock.Light.DarkActionBar">
    ...
    <!-- define text style for tabs -->
    <item name="actionBarTabTextStyle">@style/MyTabTextStyle</item>
    <item name="android:actionBarTabTextStyle">@style/MyTabTextStyle</item>
    ...
</style>

Then set the text color in the tab text style:

<style name="MyTabTextStyle" parent="Widget.Sherlock.ActionBar.TabText" >
    <item name="android:textColor">@color/my_color_selector</item>
</style>