FragmentTabHost作用。
一般被用于作为底部菜单栏(Tab栏)
FragmentTabHost的使用方法。
1 . 布局xml的定义。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.spore.study.MainActivity"> <!-需要替换的fragment布局-> <FrameLayout android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> </FrameLayout> <android.support.v4.app.FragmentTabHost android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/colorAccent"> <!-FragmentTabHost id需要使用android:id -> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="0dp" android:layout_height="0dp" android:layout_weight="0" > </FrameLayout> </android.support.v4.app.FragmentTabHost>
2 . 先定Class义数组来承载Fragment.class
例如: private Class[] mFragmentClass = { TestFragment.class, Test1Fragment.class, Test2Fragment.class, Test3Fragment.class, Test4Fragment.class,};
3 . 定义int数组去承载图片资源数据。
例如: //这都是一个一个颜色选择器(对应nomar和press) private int[] drawables = {R.drawable.main_tab_item_category, R.drawable.main_tab_item_down, R.drawable.main_tab_item_home, R.drawable.main_tab_item_setting, R.drawable.main_tab_item_user,};
4 . 定义图片数据下面对应的文字。
例如: // Tab选项卡的文字 private String mTextviewArray[] = {"主页", "分类", "下载", "我的", "设置"};
5 . 初始化布局参数,
//1. 先找到tabHost控件 findViewById. //2. 将FragmentTabhost 和 Fragment结合起来。 tabhost.setup(this, getSupportFragmentManager(), R.id.pager); //3. 通过循环来设置整体布局. for (int i = 0; i < mFragmentClass.length; i++) { //得到TabSpec 对象 TabHost.TabSpec tabSpec = tabhost.newTabSpec(mTextviewArray[i]).setIndicator(getTabItemView(i)); //添加 tabhost.addTab(tabSpec, mFragmentClass[i], null); //设置背景 tabhost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.main_tab_item_bg); } //去掉默认的分割线 tabhost.getTabWidget().setDividerDrawable(null); //具体的填充的布局的方法 private View getTabItemView(int i) { View view = View.inflate(this, R.layout.tab_item_view, null); ImageView iv = (ImageView) view.findViewById(R.id.imageview); iv.setImageResource(drawables[i]); TextView tv = (TextView) view.findViewById(R.id.textview); tv.setText(mTextviewArray[i]); return view; }
6 . 一些优化。
使用FragmentTabHost时,Fragment之间切换时每次都会调用onCreateView方法, 导致每次Fragment的布局都重绘,无法保持Fragment原有状态。 解决办法:在Fragment onCreateView方法中缓存View 但是下面测试好像没有什么用. 优化: private View rootView;//缓存Fragment view @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if(rootView==null){ rootView=inflater.inflate(R.layout.tab_fragment, null); } //缓存的rootView需要判断是否已经被加过parent, 如果有parent需要从parent删除,要不然会发生这个rootview已经有parent的错误。 ViewGroup parent = (ViewGroup) rootView.getParent(); if (parent != null) { parent.removeView(rootView); } return rootView; }