Q:

How do I change the background of an Android tab widget?

My class extends extends TabActivity
TabHost mTabHost =  getTabHost();

TabHost.TabSpec tab1 =mTabHost.newTabSpec("tab1");
TabHost.TabSpec tab2 =mTabHost.newTabSpec("tab2");

tab1 .setIndicator("title tab1");
tab2 .setIndicator("title tab2");
mTabHost.addTab(tab1);mTabHost.addTab(tab2);

TabHost.setCurrentTab(0 or 1)

Can anybody guide me how do I change the background image or color of selected tab?

A:

This will set your tab colors:
public static void setTabColor(TabHost tabhost) {
    for(int i=0;i<tabhost.getTabWidget().getChildCount();i++) {
        tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#FF0000")); //unselected
    }
    tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.parseColor("#0000FF")); // selected
}

and if you put it within the onTabChangedListener(), it will keep the correct color for selected tabs.

A:

As mbaird mentioned, the better solution is to use background with selector, so you don't have to check onTabChanged and do manual update. The minimal code is here:
private void initTabsAppearance(TabWidget tabWidget) {
    // Change background
    for(int i=0; i < tabWidget.getChildCount(); i++)
        tabWidget.getChildAt(i).setBackgroundResource(R.drawable.tab_bg);
}

Where tab_bg is an xml drawable with selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">    
    <item android:state_selected="true" android:drawable="@drawable/tab_bg_selected" />
    <item android:drawable="@drawable/tab_bg_normal" />
</selector>

For the full Tab customization I will add the code for changing tab text style using custom theme. Add this to styles.xml:
<resources>

    <style name="MyCustomTheme" parent="@android:style/Theme.Light.NoTitleBar">
        <item name="android:tabWidgetStyle">@style/CustomTabWidget</item>
    </style>

    <style name="CustomTabWidget" parent="@android:style/Widget.TabWidget">
        <item name="android:textAppearance">@style/CustomTabWidgetText</item>
    </style>

    <style name="CustomTabWidgetText" parent="@android:style/TextAppearance.Widget.TabWidget">
        <item name="android:textSize">12sp</item>
        <item name="android:textStyle">bold</item>
    </style>

</resources>

To use this theme, define it in AndroidManifest.xml:
<application android:theme="@style/MyCustomTheme">

And now you have tab widgets with custom background and custom text style.

A:

What if you register for TabHost.OnTabChanged events and call mTabHost.getCurrentTabView() to get the View, then view.setBackgroundResource()?

