編輯:關於android開發
接著研究,在實際項目中我們我們其實經常看到上面(或者下面)是一個類似於tab標簽的東西,下面是真正的內容區域,點擊不同標簽內容區域會顯示不同的內容,以前用過一個TabHost的組件,現在貌似過時了,大概是因為有了fragment,被FragmentTabHost取代了。閒言少敘,先看一下官方文檔的描述,了解一個類的用法,看官方文檔,是最快和最准確的
原來這個家伙來自於android.support.v4.app這個包下,繼承自TabHost,並且實現了TabHost.OnTabChangeListener接口。文檔上也直接放了兩個例子。一個是在Activity下包含多個fragment,注意這個activity是v4包下的FragmentActivity,
public class FragmentTabs extends FragmentActivity {
private FragmentTabHost mTabHost;
@Override
protected 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內部包含fragment的時候也可以使用FragmentTabHost。官方給出的栗子如下:
public class FragmentTabsFragmentSupport extends Fragment {
private FragmentTabHost mTabHost;
@Override
public 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;
}
@Override
public void onDestroyView() {
super.onDestroyView();
mTabHost = null;
}
注意這個fragment必須是v4包下的fragment。
tabhost的XML布局文件如下:
注意:FragmentTabHost是v4包下的類,一定要寫全包名和類名。
寫完了布局文件,接著研究java代碼,
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);先把tabhost找到,也可以把context傳進去直接new出來。
mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);對tabhost做初始化的操作,但是在activity和在fragment裡面這兩句代碼是不一樣的,fragment的FragmentManager一定要寫成getChildFragmentManager(),說明是他子fragment的manager。
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
FragmentStackSupport.CountingFragment.class, null);
然後添加4個Tab,其中mTabHost.newTabSpec("simple")這個simple是該Tab的tag,setIndicator("Simple")是標簽顯示的label,有三個重載方法,
setIndicator(CharSequence label);
setIndicator(CharSequence label, Drawable icon);
setIndicator(View view)
從參數名字就可以看出來,就不多做解釋,其中一和二是系統提供的布局,第三種可以自定義自己想要的view。
FragmentStackSupport.CountingFragment.class是要添加的fragment字節碼,最後一個參數是一個bundle類型的tag。
其實到這個地方已經大功告成。我們不需要add,replace等等一切對fragment的操作,FragmentTabHost非常強大,他會對所添加的fragment進行管理,保存棧信息和恢復棧信息等一切操作,比如我的fragment內部有三個子fragment,我退出該fragment的時候開啟的是第二個子fragment,下次我再進入該fragment的時候依然會開啟第二個子fragment,且看FragmentTabHost源碼中對保存,和恢復的操作:
@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()方法,把當前打開的fragment的TabTag通過Parcelable的方式記錄下來,然後當再次進入到該fragment的時候會自動執行OnRestoreInstanceState(Parcelable state)方法,把之前保存的狀態恢復,打開記錄的TabTag對應的fragment
通過代碼實際檢驗,即使退出的時候是打開的第二個fragment,但是再次進來的時候也會執行一遍第一個fragment的生命周期方法,主要是因為tabhost要有一個默認的打開界面。且看他的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方法,發現他有這樣一句代碼:
if (mCurrentTab == -1) {
setCurrentTab(0);
}
也就是當前沒有Tab的時候,會指定第0個元素為當前的Tab。所以會執行他的生命周期方法。
另外FragmentTabHost還有一個重要的方法就是setOnTabChangedListener(TabHost.OnTabChangeListenerl)
就是當頁面發生變化的時候,設置回調監聽接口,這個接口只有一個方法public void onTabChanged(String tabId),其實參數就是Tab的Tag。
各位看官,其實這是一個很有用的方法,比如你在給你自定義的Tab設置背景的時候,這個就可以派上用途了。
最後,我們在項目中其實是有一個個性化的需求的,比如說我想直接跳到fragment的第三個子fragment而不是按之間棧裡保存的狀態,經過研究
有一個比較笨的方法,希望大家批評指正並提出更好的解決方案。
寫一個自己的類並繼承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");
}
}
}
當你想跳到fragment下的哪個子標簽的時候,在代碼中調用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這個新引進類的使用,目的就是為了讓大家能夠牢牢的掌握它的使用方法,以便讀者在今後的開發中能夠熟練的使用它。
三、詳細代碼編寫
1、主tab布局界面,main_tab_layout:
<framelayout android:id="@+id/realtabcontent" android:layout_height="0dip" android:layout_weight="1" android:layout_width="fill_parent"> </framelayout>
2、Tab按鈕選項布局,tab_item_view.xml:
3、fragment布局界面,這裡只列出一個,fragment_1.xml:
4、Tab選項的自定義按鈕資源文件,列出其中一個按鈕,tab_home_btn:
5、Tab選項按鈕背景資源文件,selector_tab_background.xml:
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;
//定義數組來存放Fragment界面
private Class fragmentArray[] = {FragmentPage1.class,FragmentPage2.class,FragmentPage3.class,FragmentPage4.class,FragmentPage5.class};
//定義數組來存放按鈕圖片
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對象,得到TabHost
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
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;
}
}
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{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_1, null);
}
}
Android之genymotion模擬器安裝於配置,androidgenymotion
Android之genymotion模擬器安裝於配置,androidgenymotion 今天是雙休日,可憐沒人陪,只好一個人玩電腦了,之前別人一直給我推薦genymo
QQ空間實現(一)—— 展示說說中的評論內容並有相應點擊事件,評論內容事件
QQ空間實現(一)—— 展示說說中的評論內容並有相應點擊事件,評論內容事件大家都玩QQ空間客戶端,對於每一個說說,我們都可以評論,那麼,對於某一條評論: 白雪公主 回復
Android學習指南之四十六:用戶界面View之視圖切換組件ViewAnimator
上一節中為大家講解了ImageSwitcher和TextSwitcher兩個視
Android實現一個自定義相機的界面
Android實現一個自定義相機的界面 我們先實現拍照按鈕的圓形效果哈,Android開發中,當然可以找美工人員設計圖片,然後直接拿進來,不過我們可以自己寫代碼實現這個效