【发布时间】:2017-08-15 22:06:48
【问题描述】:
我编写了一些包含 TabHost 的应用程序。 每个选项卡都包含一个 LinearLayout - 我想将我创建的一些不同的现有片段添加到每个选项卡
怎么做?
private void setNewTab(Context context, TabHost tabHost, String tag, String title, int contentID ){
TabHost.TabSpec tabSpec = tabHost.newTabSpec(tag);
tabSpec.setIndicator(title);
Fragment newFragment = new ActionFragment ();
tabSpec.setIndicator(newFragment.getView());
tabSpec.setContent(contentID);
tabHost.addTab(tabSpec); // after this line i get an exception
}
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_blue_light">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab 1 Content" />
</LinearLayout>
<LinearLayout
android:id="@+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_red_dark">
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab 2 Content" />
</LinearLayout>
<LinearLayout
android:id="@+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_green_light">
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tab 3 Content" />
</LinearLayout>
</FrameLayout>
</LinearLayout>
【问题讨论】:
-
请显示您正在使用的代码
-
附上代码
-
你应该使用
ViewPager而不是LinearLayout -
你想在其他 Fragment (tab) 中使用 Fragment 吗?使用 getChildFragmentManager。你仍然可以在其他片段中使用片段
-
通常,您使用 ViewPager 设置 TabLayout 并使用 FragmentAdapter 设置 ViewPager。目前,
newFragment.getView()应该为 null,因为 Fragment 从未膨胀