2017-08-15 42 views
1

我写了一些包含TabHost的应用程序。 每个选项卡包含一个LinearLayout - 我想添加一些不同的存在片段,我创建了每个选项卡如何将一些片段添加到TabHost?

如何做到这一点?

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> 

+0

请显示您正在使用的代码 –

+0

附加代码 – Yanshof

+0

您应该使用'ViewPager'而不是'LinearLayout' – Omkar

回答

1

快速搜索 “Android的碎片TabHost” 到在FragmentTabHost class的文档结果。你在使用它吗?

mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost); 
    mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent); 

    mTabHost.addTab(mTabHost.newTabSpec("action").setIndicator("action"), ActionFragment.class, null); 

我仍然认为TabLayout会是一个更简单的选择。

如果你想在底部标签,甚至有选择。

Which view should be used for new Material Design Bottom Navigation?

+0

所有 – Yanshof

+0

只是不工作,或实际的错误不工作? –

+0

不工作:(看不到错误 – Yanshof