有一个主活动MainActivity,framelayout所在的位置
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/mainContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
一个带有导航的片段被放置在那里,其中嵌套的片段由选项卡切换。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/navigationContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/tabLayout" />
<android.support.design.widget.TabLayout
android:id="@+id/tabLayout"
style="@style/AppTabLayout"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_alignParentBottom="true"
android:background="#FFFFFF"
android:elevation="@dimen/size_medium"
tools:targetApi="lollipop">
<android.support.design.widget.TabItem
android:layout_width="@dimen/size_large"
android:layout_height="@dimen/size_large"
android:icon="@drawable/ic_nav_main" />
<android.support.design.widget.TabItem
android:layout_width="@dimen/size_large"
android:layout_height="@dimen/size_large"
android:icon="@drawable/ic_nav_popular" />
<android.support.design.widget.TabItem
android:layout_width="@dimen/size_large"
android:layout_height="@dimen/size_large"
android:icon="@drawable/ic_nav_favorites" />
</android.support.design.widget.TabLayout>
</RelativeLayout>
我改变这样的片段:
val transaction = fragmentManager?.beginTransaction()
transaction?.replace(R.id.navigationContainer, fragment, screenKey)
?.addToBackStack(screenKey)?.commit()
当我需要显示没有底部导航的片段时,我不是通过navigationContainer而是通过mainContainer 更改片段。
val transaction = fragmentManager?.beginTransaction()
transaction?.replace(R.id.mainContainer fragment, screenKey)
?.addToBackStack(screenKey)?.commit()
而当我们按下后退按钮时,我们会显示一个导航片段,但是 navigationContainer 容器中的嵌套片段变成了空的。
为了让一切正常工作,您需要使用 childFragmentManager 而不是fragmentManager嵌套片段。