1. 範例說明
- TabHost是Android系統中提供的一個視圖容器組件,它可以通過分頁顯示一組子組件,把程式中的多個Activity組織起來。建立一個TabHost還需要引入TabWidget組件和TabHost.TabSpec組件,TabWidget代表選項卡的位置,Tabhost.Spec則表示每個選項卡中的內容。
- 在本範例的布局檔案中,TabWidget的ID必需設定為”@android:id/tabs”,FrameLayout的ID必需設定為”@android:id/tabcontent”。另外,如果MainActivity不是繼承於TabActivity,那麼在代碼中,通過findViewById()方法找到TabHost後,應該先執行一次setup()方法以完成TabHost的載入;如果MainActivity是繼承於TabActivity,那麼TabHost的ID就必需設定為”@android:id/tabhost”
2. 運行結果
3. 核心代碼
@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);Resources res = getResources();TabHost host = (TabHost)findViewById(R.id.tabhost);host.setup();TabSpec spec;spec = host.newTabSpec(res.getString(R.string.tab_01)).setIndicator(res.getString(R.string.tab_01),res.getDrawable(android.R.drawable.star_big_on)).setContent(R.id.txt1);host.addTab(spec);spec = host.newTabSpec(res.getString(R.string.tab_02)).setIndicator(res.getString(R.string.tab_02),res.getDrawable(android.R.drawable.arrow_up_float)).setContent(R.id.txt2);host.addTab(spec);spec = host.newTabSpec(res.getString(R.string.tab_03)).setIndicator(res.getString(R.string.tab_03),res.getDrawable(android.R.drawable.star_big_on)).setContent(R.id.txt3);host.addTab(spec);host.setCurrentTab(1);host.setOnTabChangedListener(new OnTabChangeListener() {@Overridepublic void onTabChanged(String tabId) {Toast.makeText(MainActivity.this, tabId, Toast.LENGTH_SHORT).show();}});
}
5. 視頻講解
http://www.eyeandroid.com/thread-11497-1-1.html