以编程方式更改ActionBar选项卡颜色

时间:2013-08-02 14:54:13

标签: java android android-actionbar android-tabhost

我的应用中有以下ActionBar标签。我想知道改变颜色的最佳方法是什么,以匹配我的应用程序。

enter image description here

  1. 每个标签的内容背景都不同。我该如何添加 每个标签的单独背景颜色?
  2. 如何将浅蓝色条纹颜色更改为白色以使其成为3D 看吗
  3. 我看到了以下代码:

    ActionBar ab = getActionBar();
    //ab.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff")));
    

    但该行将所有标签的颜色更改为仅一种颜色。

    我的应用中的标签代码是:

    ActionBar ab = getActionBar();
            //ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff"))); not changing the tab color
            //ab.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#0000ff")));
            ab.setNavigationMode( ActionBar.NAVIGATION_MODE_TABS );
    
            Tab tab = ab.newTab()
                    .setText( "TY1" )
                    .setTabListener( 
                            new MyTabListener( this, TY1.class.getName() ) );
            ab.addTab( tab );
    
            tab = ab.newTab()
                    .setText( "TY2" )
                    .setTabListener( 
                            new MyTabListener( this, TY2.class.getName() ) );
            ab.addTab( tab );
    
            tab = ab.newTab()
                    .setText( "ty3" )
                    .setTabListener( 
                            new MyTabListener( this, TY3.class.getName() ) );
            ab.addTab( tab );
    

    感谢任何和所有帮助。如果有人指出我正确的方向,我也可以使用XML。

3 个答案:

答案 0 :(得分:2)

您可以为每个标签设置自定义视图。为选项卡创建一个新的布局资源(它可以只是一个TextView)。将其背景留空,并为选择指示器绘制九个补丁。使用

获取LayoutInflater
LayoutInflater inflater = getSystemService(LAYOUT_INFLATER_SERVICE);

然后,对于每个标签,您可以执行以下操作:

Tab tab = ab.newTab()
        .setText("TY1")
        .setTabListener(new MyTabListener(this, TY1.class.getName()));
View tabView = inflater.inflate(R.layout.my_tab_layout, null);
tabView.setBackgroundColor(...); // set custom color
tab.setCustomView(tabView);
ab.addTab(tab);

答案 1 :(得分:1)

您可以通过定义自定义样式来更改ActionBar的背景颜色:

<resources>
    <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>
    <style name="MyActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">ANY_HEX_COLOR_CODE</item>
    </style>
</resources>

转到:http://jgilfelt.github.io/android-actionbarstylegenerator/#name=example&compat=holo&theme=light&actionbarstyle=solid&texture=0&hairline=0&backColor=E4E4E4%2C100&secondaryColor=D6D6D6%2C100&tabColor=33B5E5%2C100&tertiaryColor=F2F2F2%2C100&accentColor=33B5E5%2C100&cabBackColor=FFFFFF%2C100&cabHighlightColor=33B5E5%2C100

然后创建操作栏然后下载它。下载后,您可以在项目中使用它。

答案 2 :(得分:1)

对于那些寻找有关如何创建自定义标签视图然后更改标签格式的更详细示例代码的人,您可以在https://stackoverflow.com/a/28389366/3268329看到我的回答。该问题与选择特定选项卡时更改选项卡文本颜色有关,但您可以轻松修改代码以更改背景或执行您需要的任何其他操作。

https://stackoverflow.com/a/18491600/3268329(S.Thiongane的回答)还展示了如何设置不同的背景资源。