TabHost是整個Tab的容器,包含TabWidget和FrameLayout兩個部分,TabWidget是每個Tab的表情,FrameLayout是Tab內容。
實現方式有兩種:
1、繼承TabActivity
2、繼承Activity類
方法一:繼承TabActivity
從TabActivity中用getTabHost()方法獲取TabHost,然后設置標簽內容
布局:
1、TabHost 必須設置android:id為@android:id/tabhost
2、TabWidget 必須設置android:id為@android:id/tabs
3、FrameLayout 必須設置android:id為@android:id/tabcontent
否則將出現類似報錯:

<?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@android:id/tabhost" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TabWidget android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@android:id/tabs" ></TabWidget> <FrameLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@android:id/tabcontent" > <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/widget_layout_red" android:background="#ff0000" android:orientation="vertical" ></LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/widget_layout_yellow" android:background="#FCD209" android:orientation="vertical" ></LinearLayout> </FrameLayout> </LinearLayout> </TabHost>
繼承TabActivity
public class MainActivity extends TabActivity { private TabHost tabhost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo); //從TabActivity上面獲取放置Tab的TabHost tabhost = getTabHost(); tabhost.addTab(tabhost //創建新標簽one .newTabSpec("one") //設置標簽標題 .setIndicator("紅色") //設置該標簽的布局內容 .setContent(R.id.widget_layout_red)); tabhost.addTab(tabhost.newTabSpec("two").setIndicator("黃色").setContent(R.id.widget_layout_yellow)); } }
其中創建標簽的方法:
tabhost.addTab(tabhost
.newTabSpec("one")
.setIndicator("紅色")
.setContent(R.id.widget_layout_red));
也可以拆分寫成:
TabHost.TabSpec tab1 = tabhost.newTabSpec("one");
tab1.setIndicator("紅色");
tab1.setContent(R.id.widget_layout_red);
tabhost.addTab(tab1);
預覽:
點擊"黃色"標簽
點擊"紅色"標簽

方法二:繼承Activity類
布局:
1、TabHost 可自定義id
2、TabWidget 必須設置android:id為@android:id/tabs
3、FrameLayout 必須設置android:id為@android:id/tabcontent
public class MainActivity extends Activity{ private TabHost tabhost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo); //得到TabHost對象實例 tabhost =(TabHost) findViewById(R.id.mytab); //調用 TabHost.setup() tabhost.setup(); //創建Tab標簽 tabhost.addTab(tabhost.newTabSpec("one").setIndicator("紅色").setContent(R.id.widget_layout_red)); tabhost.addTab(tabhost.newTabSpec("two").setIndicator("黃色").setContent(R.id.widget_layout_yellow)); } }
注意的是:
在使用TabHost切換activity時出現Did you forget to call 'public void setup..
改用第一種方法吧
其他實例:
