我正在尝试使用导航主机片段进行片段事务,但是在导航到目标片段时,旧片段仍然像在彼此上添加的片段一样在屏幕上可见。
这是我的代码:
settings_nav.xml
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/settings_nav"
app:startDestination="@+id/WelcomeFragment">
<fragment
android:id="@+id/WelcomeFragment"
android:name="com.example.ui.fragment.WelcomeFragment"
android:label="WelcomeFragment">
<action
android:id="@+id/action_WelcomeFragment_to_secondFragment"
app:destination="@+id/secondFragment"
/>
</fragment>
<fragment
android:id="@+id/secondFragment"
android:name="com.example.ui.fragment.ConfigFragment"
android:label="secondFragment">
</fragment>
activity_main.xml
<fragment
android:id="@+id/all_navigation_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/settings_nav"
app:defaultNavHost="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/toolbar"
android:layout_gravity="top"
tools:ignore="MergeRootFrame" />
WelcomeFragment.kt
button.setOnClickListener{
findNavController().navigate(R.id.action_WelcomeFragment_to_secondFragment)
}
MainActivity.kt
host = supportFragmentManager
.findFragmentById(R.id.all_navigation_host_fragment) as NavHostFragment? ?: return
navController = host.navController
navController.addOnDestinationChangedListener { _, destination, _ ->
val dest: String = try {
resources.getResourceName(destination.id)
} catch (e: Resources.NotFoundException) {
Integer.toString(destination.id)
}
MALogger.d(TAG, "Navigated to $dest")
var toolBarText = R.string.title
when (destination.id) {
R.id.WelcomeFragment -> toolBarText = R.string.title
R.id.secondFragment -> toolBarText = R.string.button
}
setupToolbar(toolBarText)
}
为什么要相互覆盖?我想念任何明显的东西吗?
这是因为您没有将选项添加到Pop up
中,该选项会从后堆栈中弹出所有不匹配的目标,直到找到指定的目标为止。另外,您还需要添加popToInclusive
选项,该选项还会从后堆栈中弹出指定的目标以及所有不匹配的目标。您的settings.xml
应该如下所示:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/settings_nav"
app:startDestination="@+id/WelcomeFragment">
<fragment
android:id="@+id/WelcomeFragment"
android:name="com.example.ui.fragment.WelcomeFragment"
android:label="WelcomeFragment">
<action
android:id="@+id/action_WelcomeFragment_to_secondFragment"
app:destination="@+id/secondFragment"
app:popUpTo="@id/WelcomeFragment"
app:popUpToInclusive="true"
/>
</fragment>
<fragment
android:id="@+id/secondFragment"
android:name="com.example.ui.fragment.ConfigFragment"
android:label="secondFragment">
</fragment>