FragmentTabHost是在android4.0之後出現的,需要support-v4包提供該類。
如圖,類似現在的新版QQ實現的功能,通過不同按鈕的點擊切換Activity。這裏需要FragmentTabHost,Fragment,TabSpec,FragmentActivity類,
FragmentTabHost:是xml中定義的組件,是最主要的類。
Fragment:是選項卡中的activity界面類,通過多個類繼承Fragment,並複寫onCreate方法,返回View,顯示在選項卡的界面上。
TabSpec:通過FragmentTabHost的newTabSpec方法得到,並要爲TabSpec指定Fragment的class對象完成 加入到TabHost中。
FragmentActivity:主界面必須繼承該類
/**
* 初始化組件,爲TabHost定義多個TabSpec,爲TabSpec定義Fragment的class對象
*/
private void initView(){
//實例化佈局對象
layoutInflater = LayoutInflater.from(this);
//實例化TabHost對象,得到TabHost
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
//R.id.realtabcontent決定了標籤是在上面還是下面顯示,FrameLayout在FragmentTabHost上面,標籤在上方顯示,否則在下方顯示。
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
//得到fragment的個數
int count = fragmentArray.length;
for(int i = 0; i < count; i++){
//爲每一個Tab按鈕設置圖標、文字和內容
TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));
//將Tab按鈕添加進Tab選項卡中
mTabHost.addTab(tabSpec, fragmentArray[i], null);
//設置Tab按鈕的背景
mTabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.selector_tab_background);
}
}
/**
* 給Tab按鈕設置圖標和文字
*/
private View getTabItemView(int index){
View view = layoutInflater.inflate(R.layout.tab_item_view, null);
ImageView imageView = (ImageView) view.findViewById(R.id.imageview);
imageView.setImageResource(mImageViewArray[index]);
TextView textView = (TextView) view.findViewById(R.id.textview);
textView.setText(mTextviewArray[index]);
return view;
}
上面代碼是主要關於FragmentTabHost類的使用和相關類的聯繫。
源碼地址:http://download.csdn.net/detail/qq602298560/7262071