2012-02-20 78 views
7

嗨,我有兩個選項卡在我的標籤小部件,我想申請兩個不同的顏色爲兩個tabs.am到處搜索,大多數顏色都是相同的,同時應用選項卡。是否有可能在android中更改所選Tab的顏色?

更新

第一片選擇時紅色

第二個選項卡選擇時藍色

這裏我的代碼

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); 

回答

12

試試這個:

...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 
} 
+0

請更新我的問題 – Mercy 2012-02-20 05:43:32

+0

@micro:請參閱我的更新回答。 – Hiral 2012-02-20 05:50:46

+0

謝謝你的工作,但我應用顏色代碼Color.green(0xCFEB5D)而不是(color.GREEN)。它不工作爲什麼? – Mercy 2012-02-20 06:04:59

7

可以設置Listener爲您TabHost使用setOnTabChangedListener和動態地改變它,

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

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

創建將設置TabSelectedUnselected顏色的方法。

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); 
    } 

然後在你的onTabChanged()裏面,你可以動態地改變背景。

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

您可以使用相同的selectedunselected標籤,here是相同的博客。

+0

謝謝,類型不匹配:不能從空轉變爲看我得到錯誤查看視圖= myTabHost.getTabWidget()getChildAt(標籤) .setBackgroundColor(Color.CYAN)。 這一行 – Mercy 2012-02-20 05:38:14

+0

好起來....想怎麼樣未選中的標籤? – 2012-02-20 05:43:39

+0

@lalit請更新我的問題 – Mercy 2012-02-20 05:43:43

2

使用setIndicator(查看視圖),而不是setIndicator(CharSequence的標籤,可繪製圖標)。您要傳遞的視圖的背景設置(例如,如果您正在對xml進行父級佈局膨脹)應該是一個ColorStateList來處理點擊。

相關問題