如何更改ActionBarSherlock选项卡文本颜色?

3
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);

目前每个选项卡的文字颜色都为白色。我希望未被选择时变成灰色,选择后变成白色。那么,在 onTabSelectedonTabUnselected 中如何更改文本颜色?

或者我应该使用 setCustomView 来设置选项卡?这里也需要注意文本大小和其他细节。

<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>

我尝试使用了

标签


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

但是它给我报错,说textColor不是一个有效的属性。
谢谢。
1个回答

15
您不应该通过代码更改文本颜色。相反,应使用颜色状态列表资源

在资源中定义颜色选择器。在res/color/目录中定义一个xml文件。该文件将包含:

<?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>

接着,在样式中设置文字颜色:

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

编辑:

你需要在样式中正确设置文本颜色!将textColor设置在(android:)actionBarTabTextStyle中。主题必须包含:

<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>

接下来,在选项卡文字样式中设置文字颜色:

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

像问题中的1一样吗? - Archie.bpgc
你需要将它添加到 res/color 并将其引用为 @color/tab_text_indicator。当期望颜色时,不能使用可绘制对象。 - Tomik
但是想法是改变颜色。所以我必须使用选择器,对吧?这将是一个可绘制的对象。如果我使用的是一种颜色,那么无论状态如何都会出现。 - Archie.bpgc
除了可绘制选择器之外,Android 还有颜色选择器。textColor 项需要颜色或颜色选择器。在文档中阅读有关颜色选择器的内容。 - Tomik
不使用颜色选择器,我只是使用了 @color/black,如问题中所编辑的,但选项卡文本颜色仍然是 白色 - Archie.bpgc
呼。要设置选项卡文本颜色,您必须在(android:)actionBarTabTextStyle中设置android:textColor。您一直把它放错地方。 - Tomik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接