最近项目中使用到了FragmentTabHost,虽然很简单,但还是将FragmentTabHost的核心知识点抽离出来,做一个小Demo。
一、效果图
二、项目结构
三、main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- android.support.v4.app.FragmentTabHost 来自android.support.v4.jar的扩展包-->
<android.support.v4.app.FragmentTabHost
android:id="@+id/fragment_TabHost"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</android.support.v4.app.FragmentTabHost>
<!-- 这个FrameLayou和上一个 FragmentTabHost 在 xml的位置决定了界面里Tab的位置是在上面的 -->
<FrameLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1" />
</LinearLayout>
四、fragment布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is Fragment One"/>
</LinearLayout>
这里只列举一个fragment布局,其他的fragment布局一样的。
五、FragmentActivity
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_1,null);
}
}
这里加载fragment布局文件
六、mainActivity
最重要的当然属于在Activity中操作定义好的Fragment与FragmentTabHost了。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//实例化FragmentTabHost
tabHost = (FragmentTabHost) findViewById(R.id.fragment_TabHost);
//setup:
// 参数一:context;
// 参数二:FragmentManager
// 参数三:container,内容id
tabHost.setup(this, getSupportFragmentManager(), R.id.content);
/**newTabSper传入的参数是String类型的,作用是标签。 setIndicator有三个复写函数
* setIndicator(CharSequence label) 指定 "标签" 作为 选项卡的指示器,
* setIndicator(View view) 指定 一个 View 作为 选项卡的指示器
* setIndicator(CharSequence label, Drawable icon) 同时指定 标签和 图标 作为
* 选项卡的指示器。
*
* 这里为了更简单,我只传入了 一个文本。
*
* addTab传人的三个参数, addTab(TabHost.TabSpec tabSpec, Class<?> clss,
* Bundleargs)
*/
TabHost.TabSpec tabSpec = tabHost.newTabSpec("f1").setIndicator("one");
tabHost.addTab(tabSpec,FragmentOne.class,null);
tabSpec = tabHost.newTabSpec("f2").setIndicator("two");
tabHost.addTab(tabSpec,FragmentTwo.class,null);
tabSpec = tabHost.newTabSpec("f3").setIndicator("three");
tabHost.addTab(tabSpec,FragmentThree.class,null);
}