Is it possible to change the color of the selected tab in android?

Hi, I have two tabs in my tab widgets, I want to apply two different colors for the two tabs.am that are searched everywhere, basically all the colors are the same when using the tab.

Update

first tab when choosing red

second tab when choosing blue

Here is my code

tabHost = (TabHost)findViewById(android.R.id.tabhost); TabSpec firstTabSpec = tabHost.newTabSpec("tid1");//these are color red TabSpec secondTabSpec = tabHost.newTabSpec("tid1");//these color blue firstTabSpec.setIndicator("Sales Info",getResources().getDrawable(R.drawable.sales)); Intent photosIntent = new Intent(this, a.class); firstTabSpec.setContent(photosIntent); secondTabSpec.setIndicator("Service Info",getResources().getDrawable(R.drawable.services)); Intent photosIntent1 = new Intent(this, b.class); secondTabSpec.setContent(photosIntent1); tabHost.addTab(firstTabSpec); tabHost.addTab(secondTabSpec); 
+7
source share
3 answers

Try the following:

 ...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 } 
+12
source

You can set the Listener for TabHost with 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 sets the color of the Selected and Unselected 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 the Selected and Unselected Tab, here for the same blog.

+7
source

Use setIndicator (View view) instead of setIndicator (CharSequence label, Drawable icon). The background setting for the view you are viewing (for example, if you are inflating the xml parent layout) should be a ColorStateList to handle clicks.

+2
source

All Articles