片段未显示在 tablayout 中

Fragments are not showing inside tablayout

我正在用没有 ViewPager 的片段填充 TabLayout。 But when selected a tab my fragments are not displaying inside tab.如果我把它放在工具栏下方,它的文本会显示在工具栏下方和选项卡的顶部,但它永远不会显示在选项卡内。这是 XML.

<android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/toolbarColor"
    android:elevation="3dp"
    />

<android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabGravity="fill"
    app:tabMode="fixed"
    android:layout_below="@+id/my_toolbar" />

<FrameLayout
    android:id="@+id/frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

MainActivity 在这里。

switch(tab.getPosition()){
    case 0:
        Log.i("MainActivity ", "one ");
        FragmentManager fm = getSupportFragmentManager();
        ft = fm.beginTransaction();
        ft.replace(R.id.frame, new TodayFragment());

        break;

    case 1:
        FragmentManager fm1 = getSupportFragmentManager();
        ft = fm1.beginTransaction();
        Log.i("MainActivity ", "two");
        ft.replace(R.id.frame, new SettingsFragment());
}

ft.addToBackStack(null);
ft.commit();

每个 Fragment 都有一个 TextView

首先,由于您没有提供完整的 xml,我认为 ToolbarTabLayoutFrameLayoutRelativeLayout 中.

现在据我所知,您可以正确加载 Fragment,但它们没有显示,因为它们隐藏在其他布局下。所以要摆脱你的问题,你需要像这样进行布局设计。

<RelativeLayout 
   android:layout_width="match_parent"
   android:layout_height="match_parent"/>

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/toolbarColor"
        android:elevation="3dp" />

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="fixed"
        android:layout_below="@+id/my_toolbar" />

    <RelativeLayout
        android:id="@+id/frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tabs"/>
<RelativeLayout/>

只需删除 FrameLayout 并使用 RelativeLayout 作为您的片段容器并将其放在您的 TabLayout 下,看看它现在是否工作。

根布局应该是线性布局不明白为什么它必须是线性布局但它就是这样