我正在开发一个带有菜单栏的 android 应用程序,我有 mainactivity,它有一个菜单栏和容器内的片段导航。当应用程序启动时,它会自动在 main_container 中设置一个片段
<FrameLayout
android:id="@+id/main_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" />
</FrameLayout>
导航转到:
<navigation 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/nav_graph"
app:startDestination="@id/spliFragment">
<fragment
android:id="@+id/spliFragment"
android:name="com.example.tutorme.ui.SearchResultsFragment"
android:label="SearchResultsFragment"
tools:layout="@layout/search_results_fragment">
</fragment>
现在,如果我按下菜单中的一个项目,我想替换 main_container 中的片段,我在 onNavigationItemSelected 中执行此操作:
else if (id == R.id.xx){
Fragment newFrag = new xxFrag();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, newFrag);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
但是,当我按下后退按钮时,这一切都有效,它只是返回,但不会在我替换的容器中分段。它回到一个空容器。我将如何解决这个问题?