首页 > 解决方案 > ViewPager 嵌套片段未正确替换

问题描述

我有一个带有 3 个片段的 ViewPager。其中一个片段包含一个 RecyclerView。我单击 RecyclerView 中的一个项目,我只想将其替换为不同的片段。我只是不确定要更换哪个容器?

这是具有 ViewPager 的主要 Activity 的 XML:

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".activities.MainActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:minHeight="?attr/actionBarSize"
        android:layout_weight="1"
        android:gravity="bottom"
        android:background="@drawable/main_header"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:title="@string/app_name">

    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        style="@style/AppTabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">



    </android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/containerViewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior</android.support.design.widget.CoordinatorLayout>

这是带有 RecyclerView 的片段的 XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/cocktailContainer"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragments.CocktailFragment">



<android.support.v7.widget.RecyclerView
    android:id="@+id/cocktail_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>

这是我在 Fragment 的 onClick 方法中的代码,它应该用新的 RecyclerView Fragment 替换当前的 RecyclerView Fragment:

    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    transaction.replace(R.id.cocktailContainer, new RecipesFragment() ).commit();

我的问题是,我不确定我应该更换什么。从上面的当前代码中,新的 Fragment 弹出在旧的 Fragment 之上,但旧的仍然存在(单词 recipes 是新的 Fragment):

在此处输入图像描述

如何让它完全替换 RecyclerView?谢谢

标签: androidandroid-fragmentsandroid-viewpager

解决方案


如果您不希望旧片段位于底部,则可以在添加新片段之前通过调用 remove 方法将其从后堆栈中删除。fragmentManager.beginTransaction().remove(fragmentManager.findFragmentById(R.id.cocktailContainer))


推荐阅读