2012-11-06 158 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