TabHost在很多應用都會使用到,有時候在TabHost添加的Tab中設置view不能滿足需求,因為在view中添加如PreferenceActivity相當困難.
之前在一個應用中需要實現使用TabHost中在多個Tab切換不同的Activity.一個是日志列表(ListActivity),一個是應用設置頁面( PreferenceActivity )
先上效果圖
上圖是日志列表頁面,是ListActivity
上圖是設置頁面,是一般的PreferenceActivity
開發流程 :
1, 編寫不同的Activity,用於在TabHost中點擊不同的Tab時進行切換(以下是兩個例子,因為不是該博文的主要內容所以省略)
1-1, 編寫LogActivity,該類是ListActivity,用於顯示日志內容
1-2, 編寫SettingActivity,該類是PreferenceActivity,應用的設置頁面,編寫方式與PreferenceActivity一樣.
2, 編寫主頁面(MainActivity),該類是應用的入口類,在該類定義TabHost並添加相應的Activity.
// 該類需要繼承ActivityGroup public class MainActivity extends ActivityGroup { private TabHost mTabHost; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); // 設置TabHost initTabs(); } private void initTabs() { mTabHost = (TabHost) findViewById(R.id.tabhost); mTabHost.setup(this.getLocalActivityManager()); // 添加日志列表的tab,注意下面的setContent中的代碼.是這個需求實現的關鍵 mTabHost.addTab(mTabHost.newTabSpec("tab_log") .setIndicator("日志",getResources().getDrawable(R.drawable.ic_tab_log)) .setContent(new Intent(this, LogActivity.class))); // 添加應用設置的tab,注意下面的setContent中的代碼.是這個需求實現的關鍵 mTabHost.addTab(mTabHost.newTabSpec("tab_setting") .setIndicator("設置",getResources().getDrawable(R.drawable.ic_tab_settings)) .setContent(new Intent(this, SettingActivity.class))); mTabHost.setCurrentTab(1); } }
3, 編寫main.xml,MainActivity的layout的xml配置文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" xmlns:app="http://schemas.android.com/apk/res/rbase.app.nowscore" android:layout_height="fill_parent" android:layout_above="@+id/adLayout"> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tabhost" android:layout_width="fill_parent" android:layout_height="wrap_content"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> </TabHost> </LinearLayout> </RelativeLayout>
補充:
當在不同的Tab中按下menu按鈕,會以當前的Activity為准,即在SettingActivity時按下menu按鈕后會觸發SettingActivity的事件,不是主頁面的事件.