2012-11-06 161 views
0

如何为选项卡添加自定义布局?例如,我想在选项卡中添加图标和标题。和自定义主动/非主动颜色。代码:Android自定义选项卡布局

mTabHost = (TabHost) findViewById(android.R.id.tabhost); 
    mTabHost.setup(); 
    mViewPager = (ViewPager) findViewById(R.id.pager); 
    mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager); 
    TabSpec tab1spec = mTabHost.newTabSpec("tab1").setIndicator("Tab 1"); 
    TabSpec tab2spec = mTabHost.newTabSpec("tab2").setIndicator("Tab 2"); 
    mTabsAdapter.addTab(tab1spec, ConverterFragment.class, savedInstanceState); 
    mTabsAdapter.addTab(tab2spec, RatesFragment.class, savedInstanceState); 
    if (savedInstanceState != null) { 
     mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); 
    } 
+0

http://envyandroid.com/archives/326/align-tabhost-at-bottom –

回答

0
Resources res = getResources(); // Resource object to get Drawables 
TabHost tabHost = getTabHost(); // The activity TabHost 
TabHost.TabSpec spec; // Resusable TabSpec for each tab 
Intent intent = new Intent().setClass(this, YourClass.class); 
spec = tabHost.newTabSpec("home").setIndicator("Home", 
         res.getDrawable(R.drawable.tab_options_home)) 
        .setContent(intent); 
tabHost.addTab(spec); 

有了上面的代码,你应该能够以启动活动,并为标签的图标(5号线,“家”创建标签,关联意图将是标签的标题)。该图标将根据选项卡处于活动状态还是非活动状态而发生变化,但是您需要定义文件“tab_options_home.xml”(或任何您想要的名称,但请记住在代码中更改它)并将其保存到drawable夹。该文件应该是这样的:

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<!-- Icon used when selected --> 
<item android:drawable="@drawable/hover_icon" 
     android:state_selected="true" /> 
<!-- Icon used when not selected --> 
<item android:drawable="@drawable/regular_icon" /> 

与该XML定义当标签被激活(state_selected="true")或不活动应该使用哪个图标。我知道为时已晚,但希望它可以帮助任何人谁需要它
PS:记得延长TabActivity