2014-09-26 111 views
1

我有一个扩展TabActivity的MainActivity的应用程序(我知道它已被弃用,但要做更改整个应用程序太多)。更改选项卡的颜色取决于选择哪个选项卡

所以在我的应用我用tabhost创建3个标签是这样的:

TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost); 
TabSpec firstTabSpec = tabHost.newTabSpec("tid1"); 
TabSpec secondTabSpec = tabHost.newTabSpec("tid2"); 
TabSpec thirdTabSpec = tabHost.newTabSpec("tid3"); 

firstTabSpec.setIndicator("tab1").setContent(
      new Intent(this, tab1.class)); 
    secondTabSpec.setIndicator("tab2").setContent(
      new Intent(this, tab2.class)); 
    thirdTabSpec.setIndicator("tab3").setContent(
      new Intent(this, tab3.class)); 

    /* Add tabSpec to the TabHost to display. */ 

    tabHost.addTab(firstTabSpec); 
    tabHost.addTab(secondTabSpec); 
    tabHost.addTab(thirdTabSpec); 


    //Changing the tabs text color on the tabs 
    for(int i=0;i<tabHost.getTabWidget().getChildCount();i++) 
    { 
     TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title); 
     tv.setTextColor(Color.parseColor("#ffffff")); 
    } 

    // remove divider 
    tabHost.getTabWidget().setDividerDrawable(null); 

    tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#90a4ae")); 
    tabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.parseColor("#607d8b")); 
    tabHost.getTabWidget().getChildAt(2).setBackgroundColor(Color.parseColor("#607d8b")); 

所以我的代码创建了3个标签链接到3个不同的活动,并设置标签的颜色。第一个标签首先加载与另外两个不同的颜色。

我希望选项卡的颜色根据所选的颜色而改变。 所以,当我按下第二个标签时,我希望第一个获得#607d8b颜色,第二个获得#90a4ae。 第三个相同。

试图实现一个OnTabChangeListener,但无法让它工作。 试过这样:

tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#90a4ae")); 
    tabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.parseColor("#607d8b")); 
    tabHost.getTabWidget().getChildAt(2).setBackgroundColor(Color.parseColor("#607d8b")); 

与改变颜色的每一个载入标签活动里面,但我得到的错误,它无法解决tabhost(因为它应该的,因为它在MainActivity的已定义

回答

1
tabHost.setOnTabChangedListener(new OnTabChangeListener() { 

    @Override 
    public void onTabChanged(String tabId) { 
     // TODO Auto-generated method stub 
     for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) { 
       tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#54C4C6")); // unselected 
     } 

     tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#114C5A")); // selected 
    } 
}); 
+1

感谢名单。很多!它的功能就像一个魅力!修复了我喜欢的颜色,现在它是完美的! – duk3r 2014-09-26 08:36:59

+0

随时欢迎。 – 2014-09-26 09:14:41

相关问题