ViewPager嵌套片段无法正确替换

时间:2018-06-12 01:08:31

标签: android android-fragments android-viewpager

我有一个包含3个片段的ViewPager。其中一个片段包含RecyclerView。我点击RecyclerView中的一个项目,我只想用它替换一个不同的片段。我只是不确定要更换哪个容器?<​​/ p>

以下是我的主要Activity的XML,它包含ViewPager:

<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:

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

我的问题是,我不确定我应该替换什么。从上面的当前代码开始,新的Fragment弹出旧的片段,但旧片段仍在那里(食谱这个词是新的片段):

enter image description here

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

1 个答案:

答案 0 :(得分:0)

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