参考了http://simplehappy.iteye.com/blog/1783845,用android-support-v13里面FragmentTabHost实现,代码片段:
- public class TabHostFragment extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
- View v = inflater.inflate(R.layout.main_linear, container, false);
- FragmentTabHost fragmentTabHost = (FragmentTabHost) v.findViewById(R.id.fragmentTabHosts);
- fragmentTabHost.setup(getActivity(), getChildFragmentManager(), R.id.tabContent);
- fragmentTabHost.addTab(fragmentTabHost.newTabSpec("Simple").setIndicator("Simple"),
- CountingFragment.class, null);
- fragmentTabHost.addTab(fragmentTabHost.newTabSpec("List").setIndicator("List"),
- FragmentPagerSupport.ArrayListFragment.class, null);
- fragmentTabHost.addTab(fragmentTabHost.newTabSpec("Cursor").setIndicator("Cursor"),
- CursorFragment.class, null);
- return v;
- }
- }
- <?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" >
- <FrameLayout
- android:id="@+id/tabContent"
- android:layout_width="match_parent"
- android:layout_height="0dip"
- android:layout_weight="1" />
- <android.support.v13.app.FragmentTabHost
- android:id="@+id/fragmentTabHosts"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
上面代码里的fragmentTabHost.setup(getActivity(), getChildFragmentManager(), R.id.tabContent)的第二个参数必须是childFragmentManager,但是问题来了,在4.2平台之前,android.app.Fragment是没有getChildFragmentManager()方法的,(之前我就是在4.2的平台下编译,再放到4.0的模拟器上运行,出现了NoSuchMethodError,放到4.2的模拟器上运行就可以)。
在4.2之前的手机上要通过上述方式实现的话,要用android.support.v4.app.Fragment,这个类才有getChildFragmentManager()方法,该方法返回类型是android.support.v4.app.Fragment,导致要做出一系列的改动,用的FragmentTabHost就不是v13的了,是v4的,包括显示页的Activity也只能用android.support.v4.app.FragmentActivity,FragmentPagerAdapter也要v4的,细节可参考代码:http://download.csdn.net/download/tedzyc/5050980(V4.2的版本用New Android projects from existing code导入)。