【发布时间】:2015-01-21 13:18:47
【问题描述】:
我正在阅读许多教程如何在扩展 FragmentActivity 的类中实现选项卡,
但没有人了解如何在扩展 Fragment 的类中实现选项卡
我使用 AndroidStudio 创建了一个新项目,其中包含 NavigationDrawerFragment:
此 navigationDrawerFragment 为它显示的每个选项菜单创建一个新片段。在这个片段中,我需要有一些标签。
如何在片段的onCreateView 方法中添加选项卡?
有人可以给我一个非常简单的例子吗?
我正在做什么来尝试解决我的问题:
第 1 步 - 我创建了一个新的 @987654327 @,它包含tabHost,它是主要片段:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment1"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TabHost
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tabHost"
android:layout_gravity="center_horizontal">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="@+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
<LinearLayout
android:id="@+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
<LinearLayout
android:id="@+id/tab3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
第 2 步 - 在主片段上我放了这行代码:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//View rootView = inflater.inflate(R.layout.vediamo, container, false);
mTabHost = new FragmentTabHost(getActivity());
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.fragment1);
mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
CreaAnnoFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
ModificaAnnoFragment.class, null);
mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
EliminaAnnoFragment.class, null);
return mTabHost;
}
@Override
public void onDestroyView() {
super.onDestroyView();
mTabHost = null;
}
如果我运行程序我得到这个错误:
java.lang.NullPointerException at myapps.studentsmarks.CreaAnnoFragment.onAttach(CreaAnnoFragment.java:100)
已修复 - 解决方案
“包装的片段”不需要onAttach() 方法,这是逻辑。那就删掉吧
【问题讨论】:
-
为什么不使用 ActionBar 中的选项卡?
-
因为来自 ActionBar 的标签需要一个活动,我需要将它们添加到一个片段中