How to Style ActionBar, tab background on selected tab

CocoNess picture CocoNess · Nov 8, 2012 · Viewed 23.1k times · Source

I'm struggling with styling the ActionBar. My app has an ActionBar with three tabs. I'm trying to get the selected tab to have a background color, and the unselected tabs to show a different color. I'm following this reference: Customizing Action Bar. But all the TABs are showing the Selected color.

My styles.xml file is as follows:

<style name="MyActionBarTabStyle" parent="android:style/Widget.Holo.Light.ActionBar.TabBar">
    <item name="android:background">@drawable/tab_background</item>
    <item name="android:paddingLeft">32dp</item>
    <item name="android:paddingRight">32dp</item>
</style> 

<style name="MyActionBarTabBarStyle" parent="android:style/Widget.Holo.Light.ActionBar.TabBar">

    <item name="android:background">@drawable/red</item>
</style> 


<style name="AppTheme.Light" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/ActionBar.Light</item>
    <item name="android:actionBarTabStyle">@style/MyActionBarTabStyle</item>
    <item name="android:actionBarTabBarStyle">@style/MyActionBarTabBarStyle</item>

</style>

tab_background is just a 9 patch. I'm also not sure if I'm inheriting the action bar tab from the correct parent (parent="android:style/Widget.Holo.Light.ActionBar.TabBar). I've looked through the references & find it very difficult to understand the style hierarchy

Why wont my tabs show selected or no? Thanks in advance for your assistance.

Answer

CocoNess picture CocoNess · Nov 8, 2012

I solved my problem. I didn't use State List Drawables initially. I used the background image directly instead of going via the StateListDrawable. Using StateListDrawable, you can set a different background based on whether the tag is selected or not.

So I added the file tab_background_select.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true"
        android:drawable="@drawable/tab_background" />

</selector>

and I referenced this from my styles.xml:

 <item name="android:background">@drawable/tab_background_select</item>