2012-07-07 69 views
4

如何更改點擊選項卡主機上的顏色。我可以改變形象,但顏色不會改變。如何在Android中設置選項卡視圖指示器背景顏色

public class MainActivity extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 

     TabHost tabHost=(TabHost)findViewById(R.id.tabHost); 
     tabHost.setup(); 

     TabSpec spec1=tabHost.newTabSpec("Tab 1"); 
     spec1.setContent(R.id.tab1);`enter code here` 
     spec1.setIndicator("Tab 1", getResources().getDrawable(setBackgroundColor(Color.RED)); 

     TabSpec spec2=tabHost.newTabSpec("Tab 2"); 
     spec2.setIndicator("Tab 2", getResources().getDrawable(setBackgroundColor(Color.GREAN)); 
     spec2.setContent(R.id.tab2); 

     TabSpec spec3=tabHost.newTabSpec("Tab 3"); 
     spec3.setIndicator("Tab 3", getResources().getDrawable(setBackgroundColor(Color.BLACK)); 
     spec3.setContent(R.id.tab3); 

     tabHost.addTab(spec1); 
     tabHost.addTab(spec2); 
     tabHost.addTab(spec3); 
    } 
} 

回答

1
public class MainActivity extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 

     TabHost tabHost=(TabHost)findViewById(R.id.tabHost); 
     tabHost.setup(); 

     TabSpec spec1=tabHost.newTabSpec("Tab 1"); 
     spec1.setContent(R.id.tab1);`enter code here` 
     spec1.setIndicator("Tab 1", getResources().getDrawable(setBackgroundColor(view.Color.RED)); 

     TabSpec spec2=tabHost.newTabSpec("Tab 2"); 
     spec2.setIndicator("Tab 2", getResources().getDrawable(setBackgroundColor(view.Color.GREAN)); 
     spec2.setContent(R.id.tab2); 

     TabSpec spec3=tabHost.newTabSpec("Tab 3"); 
     spec3.setIndicator("Tab 3", getResources().getDrawable(setBackgroundColor(view.Color.BLACK)); 
     spec3.setContent(R.id.tab3); 

     tabHost.addTab(spec1); 
     tabHost.addTab(spec2); 
     tabHost.addTab(spec3); 
    } 
} 
1

//設置背景顏色標籤

for (int i = 1; i <= 3; i++) { 
    tabHost.getTabWidget().getChildTabViewAt(i).setBackgroundColor(getResources().getColor(R.color.gradient)); 

     } 
4

您可以使用此功能只是通過你的tabHost它

public static void setTabColor(TabHost tabhost) { 
     for(int i=0;i<tabhost.getTabWidget().getChildCount();i++) 
     { 
      tabhost.getTabWidget().getChildAt(i).setBackgroundResource(R.color.white); //unselected 
     } 
     tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundResource(R.color.tab_selected); // selected 
    } 
-3

對於您應該使用事件onTabChangedlistener並在裏面放入你想要的任何循環,就像在挑選的答案中一樣。

tabhost.setOnTabChangedListener(new TabHost.OnTabChangeListener() { 
     @Override 
     public void onTabChanged(String s) { 
      setTabColor(tabhost); 
     } 
    }); 

你可以閱讀這篇文章,這將幫助你,但它是西班牙文。

http://www.johnarij.ml/2017/04/19/cambio-de-color-de-tab-en-tabhost-android/

+0

的問題是,5歲,並具有公認的答案。鏈接到關於該主題的非英文的一般性文章幾乎沒有什麼價值。 – GertG 2017-04-19 15:00:47