如何使用一行布局更改ActionBar Tab文本颜色?

时间:2015-01-31 11:26:01

标签: android android-layout android-actionbar

有两种线条布局,请查看ActionBar标签,文字颜色为蓝色;

https://pbs.twimg.com/media/B8rKhm-CIAIGFiv.png

这是一行布局,texColor是白色,你怎么能做到?

enter image description here

1 个答案:

答案 0 :(得分:0)

1要更改标签样式,您无法使用actionBar.newTab().setText(xxx),因为您无法获取TextView,因此您必须创建TextView,然后使用actionBar.newTab().setCustomView(tabView);

private TextView createTab(int titleText) {
    TextView textView = new TextView(this,null,R.attr.actionBarTabTextStyle);
    textView.setGravity(Gravity.CENTER_VERTICAL);
    textView.setEllipsize(TextUtils.TruncateAt.END);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    textView.setLayoutParams(lp);
    textView.setText(titleText);
    return textView;
}

2查看R.attr.actionBarTabTextStyle属性,您必须在attrs.xml中写一行

//attrs.xml
<attr name="actionBarTabTextStyle" format="reference"/>

它是样式的参考,在styles / xml或theme.xml

<style name="MyTheme" parent="android:style/Theme.Holo.Light.DarkActionBar">
    <item name="android:actionBarTabTextStyle">@style/ActionBarTabTextStyle</item>
    <item name="actionBarTabTextStyle">@style/ActionBarTabTextStyle</item>
</style>

3创建一个Tab并将其添加到ActionBar:

// MainActivity
TextView tabView=createTab(tabTitle);
ActionBar.Tab actionBarTab=actionBar.newTab();
actionBarTab.setCustomView(tabView).setTabListener(this)
actionBar.addTab(actionBarTab);

4 ActionBar有一个私有字段:mHasEmbeddedTabs,当在一行中为true时,其他为false,所以只需获取该字段的值。

private boolean mHasEmbeddedTabs =true;
@Override
public void onCreate(Bundle savedInstanceState) {
    try {
        Field field = actionBar.getClass().getDeclaredField("mHasEmbeddedTabs");
        field.setAccessible(true);
        this.mHasEmbeddedTabs=field.getBoolean(actionBar);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

5现在,我可以在一行中的操作栏和选项卡中更改选项卡文本颜色

if(this.mHasEmbeddedTabs){
   tabView.setTextColor(getResources().getColor(R.color.white));
}