Search code examples
androidandroid-tabhost

Change Tab bar selected tab colour in Android


I am using TabHost for tab bar. Here's the code that adds the tabs:

// Create  Intents to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, Tab1.class);

spec = tabHost.newTabSpec("First").setIndicator("",getResources().getDrawable(R.drawable.transaction_refno))
              .setContent(intent);

//Add intent to tab
tabHost.addTab(spec);

/************* TAB2 ************/
intent = new Intent().setClass(this, Tab2.class);
spec = tabHost.newTabSpec("Second").setIndicator("",getResources().getDrawable(R.drawable.transaction_refno))
              .setContent(intent);  
tabHost.addTab(spec);

/************* TAB3 ************/
intent = new Intent().setClass(this, Tab3.class);
spec = tabHost.newTabSpec("Third").setIndicator("",getResources().getDrawable(R.drawable.transaction_refno))
              .setContent(intent);
tabHost.addTab(spec);

intent = new Intent().setClass(this, Tab4.class);
spec = tabHost.newTabSpec("Fourth").setIndicator("",getResources().getDrawable(R.drawable.transaction_refno))
              .setContent(intent);
tabHost.addTab(spec);

tabHost.getTabWidget().setLeftStripDrawable(color.black);
tabHost.getTabWidget().setRightStripDrawable(color.black);
tabHost.getTabWidget().setStripEnabled(false);

tabHost.getTabWidget().setCurrentTab(0);
tabHost.getTabWidget().setDividerDrawable(null);

The selected tab is showing a blue underline, and I want to change its colour. How can I do this?


Solution

  • Instead of using the R.drawable.transaction_refno, you can use a drawable that uses a selector to show a different drawable depending on the state. You could write this in your drawable:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/tab_selected"
              android:state_selected="true"/>
        <item android:drawable="@drawable/tab_unselected"/>
    </selector>
    

    And create the tab_selected and tab_unselected drawables with each design. For more information on how to use TabHost, you can see the Android docs or check this walkthrough.