Skip to content Skip to sidebar Skip to footer

Is It Possible To Change The Color Of Selected Tab In Android?

Hi i have two tabs in my tab widget,i want to apply the two different color for two tabs.am searching everywhere,mostly all colors are same while applying the tab. update first tab

Solution 1:

Try this:

...onCreate(){

     ...
     tabHost.setOnTabChangedListener(new OnTabChangeListener() {

    @Override
    public void onTabChanged(String arg0) {

        setTabColor(tabHost);
    }
     });
     setTabColor(tabHost);
...
}

//Change The Backgournd Color of Tabs
public void setTabColor(TabHost tabhost) {

    for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
        tabhost.getTabWidget().getChildAt(i).setBackgroundColor(COLOR_CYAN); //unselected

    if(tabhost.getCurrentTab()==0)
           tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(COLOR_RED); //1st tab selected
    else
           tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(COLOR_BLUE); //2nd tab selected
}

Solution 2:

You can set Listener for your TabHost using setOnTabChangedListener and change it dynamically,

  public void onCreate(Bundle savedInstanceState){
   // add your tabs here

   // set the First Tab as selected Tab.
  setSelectedTabColor();
}

Create a method that will set the Selected and Unselected color of Tab.

 private void setSelectedTabColor() {
        for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)  
        {  
            tabHost.getTabWidget().getChildAt(i)
                                            .setBackgroundColor(Color.WHITE);  
        }  
        tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
                                              .setBackgroundColor(Color.RED); 
    }

Then inside your onTabChanged() you can dynamically change the Background.

@Override  
    public void onTabChanged(String tabId) {  
        setSelectedTabColor(); 
    } 

You can use the same for selected and unselected Tab, here is the Blog for the same.


Solution 3:

Use the setIndicator(View view) instead of setIndicator(CharSequence label, Drawable icon). The background setting of the view you'll pass (e.g. if you're inflating an xml the parent layout) should be a ColorStateList to handle the clicks.


Post a Comment for "Is It Possible To Change The Color Of Selected Tab In Android?"