FragmentTabHost的应用
原創(chuàng))FragmentTabHost的應(yīng)用(fragment學(xué)習(xí)系列文章之二)
?CSDN博客 原文??http://blog.csdn.net/flyingfox023/article/details/23626045 主題?安卓開發(fā)接著研究,在實際項目中我們我們事實上常常看到上面(或者以下)是一個類似于tab標(biāo)簽的東西,以下是真正的內(nèi)容區(qū)域。點擊不同標(biāo)簽內(nèi)容區(qū)域會顯示不同的內(nèi)容。曾經(jīng)用過一個TabHost的組件,如今貌似過時了,大概是由于有了fragment,被FragmentTabHost代替了。閑言少敘,先看一下官方文檔的描寫敘述,了解一個類的使用方法,看官方文檔,是最快和最準(zhǔn)確的
原來這個家伙來自于android.support.v4.app這個包下,繼承自?TabHost?,而且實現(xiàn)了?TabHost.OnTabChangeListener?接口。文檔上也直接放了兩個樣例。一個是在Activity下包括多個fragment。注意這個activity是v4包下的?FragmentActivity。
public class FragmentTabs extends FragmentActivity {private FragmentTabHost mTabHost;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_tabs); mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost); mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"), FragmentStackSupport.CountingFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"), LoaderCursorSupport.CursorLoaderListFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"), LoaderCustomSupport.AppListFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"), LoaderThrottleSupport.ThrottledLoaderListFragment.class, null);} } 還有就是在fragment內(nèi)部包括fragment的時候也能夠使用FragmentTabHost。官方給出的栗子例如以下:
public class FragmentTabsFragmentSupport extends Fragment {private FragmentTabHost mTabHost;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mTabHost = new FragmentTabHost(getActivity()); mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.fragment1); mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"), FragmentStackSupport.CountingFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"), LoaderCursorSupport.CursorLoaderListFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"), LoaderCustomSupport.AppListFragment.class, null); mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"), LoaderThrottleSupport.ThrottledLoaderListFragment.class, null); return mTabHost;}@Overridepublic void onDestroyView() { super.onDestroyView(); mTabHost = null;} 注意這個fragment必須是v4包下的fragment。
tabhost的XML布局文件例如以下:
<android.support.v4.app.FragmentTabHost android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/line" > <TabWidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > </TabWidget> </android.support.v4.app.FragmentTabHost> <RelativeLayout android:id="@+id/fragment_multi" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@android:id/tabhost" android:background="#FFFFFF" /> 注意:?FragmentTabHost是v4包下的類。一定要寫全包名和類名。寫完了布局文件。接著研究java代碼。
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost); 先把tabhost找到,也能夠把context傳進(jìn)去直接new出來。?
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),FragmentStackSupport.CountingFragment.class, null);
然后加入4個Tab,當(dāng)中?mTabHost.newTabSpec("simple")這個simple是該Tab的tag。?setIndicator("Simple")是標(biāo)簽顯示的label,有三個重載方法,
setIndicator(CharSequence label);
setIndicator(CharSequence label, Drawable icon);
setIndicator(View view)
從參數(shù)名字就能夠看出來。就不多做解釋,當(dāng)中一和二是系統(tǒng)提供的布局,第三種能夠自己定義自己想要的view。
FragmentStackSupport.CountingFragment.class 是要加入的fragment字節(jié)碼,最后一個參數(shù)是一個bundle類型的tag。
事實上到這個地方已經(jīng)大功告成。我們不須要add。replace等等一切對fragment的操作,FragmentTabHost很強(qiáng)大,他會對所加入的fragment進(jìn)行管理,保存棧信息和恢復(fù)棧信息等一切操作,比方我的fragment內(nèi)部有三個子fragment,我退出該fragment的時候開啟的是第二個子fragment,下次我再進(jìn)入該fragment的時候依舊會開啟第二個子fragment。且看?FragmentTabHost源代碼中對保存,和恢復(fù)的操作:
@Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState); ss.curTab = getCurrentTabTag(); return ss; } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState)state; super.onRestoreInstanceState(ss.getSuperState()); setCurrentTabByTag(ss.curTab); } 在該fragment退出的時候會自己主動運行?onSaveInstanceState()方法。把當(dāng)前打開的fragment的TabTag通過?Parcelable的方式?記錄下來,然后當(dāng)再次進(jìn)入到該fragment的時候會自己主動運行OnRestoreInstanceState(Parcelable state)方法,把之前保存的狀態(tài)恢復(fù),打開記錄的TabTag相應(yīng)的fragment通過代碼實際檢驗。即使退出的時候是打開的第二個fragment??墒窃俅芜M(jìn)來的時候也會運行一遍第一個fragment的生命周期方法。主要是由于tabhost要有一個默認(rèn)的打開界面。
且看他的addTab方法
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) { tabSpec.setContent(new DummyTabFactory(mContext)); String tag = tabSpec.getTag(); TabInfo info = new TabInfo(tag, clss, args); if (mAttached) { // If we are already attached to the window, then check to make // sure this tab's fragment is inactive if it exists. This shouldn't // normally happen. info.fragment = mFragmentManager.findFragmentByTag(tag); if (info.fragment != null && !info.fragment.isDetached()) { FragmentTransaction ft = mFragmentManager.beginTransaction(); ft.detach(info.fragment); ft.commit(); } } mTabs.add(info); addTab(tabSpec); } 最后一句是addTab(tabSpec)。這是他的父類TabHost的方法,跟蹤一下addTab方法,發(fā)現(xiàn)他有這樣一句代碼: if (mCurrentTab == -1) {setCurrentTab(0);} 也就是當(dāng)前沒有Tab的時候,會指定第0個元素為當(dāng)前的Tab。所以會運行他的生命周期方法。另外FragmentTabHost另一個重要的方法就是?setOnTabChangedListener?(TabHost.OnTabChangeListener??l)
就是當(dāng)頁面發(fā)生變化的時候,設(shè)置回調(diào)監(jiān)聽接口,這個接口僅僅有一個方法?public void onTabChanged(String tabId),事實上參數(shù)就是Tab的Tag。
各位看官,事實上這是一個非常實用的方法。比方你在給你自己定義的Tab設(shè)置背景的時候。這個就能夠派上用途了。
最后。我們在項目中事實上是有一個個性化的需求的,比方說我想直接跳到fragment的第三個子fragment而不是按之間棧里保存的狀態(tài),經(jīng)過研究
有一個比較笨的方法。希望大家批評指正并提出更好的解決方式。
寫一個自己的類并繼承FragmentTabHost:
package com.example.myfragment;import android.content.Context; import android.os.Parcelable; import android.support.v4.app.FragmentTabHost; import android.util.AttributeSet;public class MyTabHost extends FragmentTabHost { public MyTabHost(Context context) { super(context); } public MyTabHost(Context context, AttributeSet attrs) { super(context, attrs); } String tag = null; public void setTag(String tag) { this.tag = tag; } public String getTag() { return tag; } @Override protected void onRestoreInstanceState(Parcelable state) { super.onRestoreInstanceState(state); if (tag != null) setCurrentTabByTag(tag); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (tag != null) { onTabChanged("alwaysContact"); setCurrentTabByTag("alwaysContact"); } } } 當(dāng)你想跳到fragment下的哪個子標(biāo)簽的時候,在代碼中調(diào)用setTag方法,就可以。如: public static Fragment3 getInstance(Bundle bundle) { Fragment3 instance = new Fragment3(); arg = bundle; if (bundle != null) instance.setArguments(bundle); return instance; } View v = inflater.inflate(R.layout.fragment3, container, false); tabhost = (FragmentTabHost) v.findViewById(android.R.id.tabhost); if (arg != null) { tabhost.setTag(arg.getString("currentTag")); } 齊活。在上一篇文章中,我們花了大量的篇幅來解說Fragment這個新引進(jìn)類的使用,目的就是為了讓大家可以牢牢的掌握它的用法,以便讀者在今后的開發(fā)中可以熟練的使用它。
一、實現(xiàn)效果圖
二、項目project結(jié)構(gòu)
三、具體代碼編寫
1、主tab布局界面,main_tab_layout:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <FrameLayout android:id="@+id/realtabcontent" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" /> <android.support.v4.app.FragmentTabHost android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/maintab_toolbar_bg"> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="0" /> </android.support.v4.app.FragmentTabHost> </LinearLayout>
2、Tabbutton選項布局,tab_item_view.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="wrap_content"android:layout_height="wrap_content"android:gravity="center"android:orientation="vertical" ><ImageViewandroid:id="@+id/imageview"android:layout_width="wrap_content"android:layout_height="wrap_content"android:focusable="false"android:padding="3dp" android:src="@drawable/tab_home_btn"></ImageView><TextViewandroid:id="@+id/textview" android:layout_width="wrap_content"android:layout_height="wrap_content" android:text="首頁"android:textSize="10sp"android:textColor="#ffffff"></TextView></LinearLayout>3、fragment布局界面。這里僅僅列出一個,fragment_1.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent" ><ImageViewandroid:id="@+id/imageview"android:layout_width="fill_parent"android:layout_height="fill_parent"android:scaleType="fitCenter"android:src="@drawable/xianjian01" ></ImageView></LinearLayout>4、Tab選項的自己定義button資源文件。列出當(dāng)中一個button,tab_home_btn:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:drawable="@drawable/icon_home_sel" android:state_selected="true"/><item android:drawable="@drawable/icon_home_nor"/></selector>5、Tab選項button背景資源文件。selector_tab_background.xml:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:drawable="@drawable/home_btn_bg" android:state_pressed="true"/><item android:drawable="@drawable/home_btn_bg" android:state_selected="true"/></selector>6、主Activity類,MainTabActivity.Java:
package com.yangyu.mycustomtab02;import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTabHost; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TabHost.TabSpec; import android.widget.TextView;/*** @author yangyu* 功能描寫敘述:自己定義TabHost*/ public class MainTabActivity extends FragmentActivity{ //定義FragmentTabHost對象private FragmentTabHost mTabHost;//定義一個布局private LayoutInflater layoutInflater;//定義數(shù)組來存放Fragment界面private Class fragmentArray[] = {FragmentPage1.class,FragmentPage2.class,FragmentPage3.class,FragmentPage4.class,FragmentPage5.class};//定義數(shù)組來存放button圖片private int mImageViewArray[] = {R.drawable.tab_home_btn,R.drawable.tab_message_btn,R.drawable.tab_selfinfo_btn,R.drawable.tab_square_btn,R.drawable.tab_more_btn};//Tab選項卡的文字private String mTextviewArray[] = {"首頁", "消息", "好友", "廣場", "很多其它"};public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main_tab_layout);initView();}/*** 初始化組件*/private void initView(){//實例化布局對象layoutInflater = LayoutInflater.from(this);//實例化TabHost對象,得到TabHostmTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); //得到fragment的個數(shù)int count = fragmentArray.length; for(int i = 0; i < count; i++){ //為每個Tabbutton設(shè)置圖標(biāo)、文字和內(nèi)容TabSpec tabSpec = mTabHost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i));//將Tabbutton加入進(jìn)Tab選項卡中mTabHost.addTab(tabSpec, fragmentArray[i], null);//設(shè)置Tabbutton的背景mTabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.selector_tab_background);}}/*** 給Tabbutton設(shè)置圖標(biāo)和文字*/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;} }7、Fragment頁面,FragmentPage1.java:
package com.yangyu.mycustomtab02;import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;public class FragmentPage1 extends Fragment{@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_1, null); } }源代碼下載地址
總結(jié)
以上是生活随笔為你收集整理的FragmentTabHost的应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: form表单提交数据编码方式和tomca
- 下一篇: HNUSTOJ 1601:名字缩写