android在导航组件中导航后清除碎片



这里有一些问题。

假设我有3个片段A-B-C。首先我从片段A导航到B。然后从片段B导航到片段C并从堆栈中清除片段B。我需要在导航时清除它,因为我需要确保当用户在片段C中时堆栈变为A-C,如果用户点击返回,用户将返回片段A,并且片段C中还有一个按钮可以导航到片段B

请帮助我,需要一些建议来做这件事,或者如果有其他解决方案,请在这里分享。

感谢

这个问题很棘手,因为Jetpack Navigation关于Conditional Navigation糟糕的文档本应解释这个主题,但未能解释,但答案实际上很简单。

您只需要popUpTopopUpToInclusive

<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/navigation"
app:startDestination="@id/splash_graph"
tools:ignore="UnusedNavigation">
<navigation
android:id="@+id/splash_graph"
app:startDestination="@id/splash_fragment">
<action
android:id="@+id/splash_to_main_graph"
app:destination="@id/main_graph"
app:popUpTo="@id/splash_graph"
app:popUpToInclusive="true" />
<fragment
android:id="@+id/splash_fragment"
android:name="fqn.SplashFragment"
tools:layout="@layout/splash_fragment" />
</navigation>
<navigation
android:id="@+id/main_graph"
app:startDestination="@id/fragment_a">
<action
android:id="@+id/fragment_a_to_fragment_b"
app:destination="@id/fragment_b"
app:enterAnim="@anim/slide_in_from_left"
app:exitAnim="@anim/slide_out_to_right"
app:popEnterAnim="@anim/slide_out_to_left"
app:popExitAnim="@anim/slide_in_from_left" />
<action
android:id="@+id/fragment_b_to_fragment_c"
app:destination="@id/fragment_c"
app:enterAnim="@anim/slide_in_from_left"
app:exitAnim="@anim/slide_out_to_right"
app:popEnterAnim="@anim/slide_out_to_left"
app:popExitAnim="@anim/slide_in_from_left"
app:popUpTo="@id/fragment_b"
app:popUpToInclusive="true" />
<action
android:id="@+id/fragment_c_to_fragment_b"
app:destination="@id/fragment_b"
app:enterAnim="@anim/slide_in_from_left"
app:exitAnim="@anim/slide_out_to_right"
app:popEnterAnim="@anim/slide_out_to_left"
app:popExitAnim="@anim/slide_in_from_left"
app:popUpTo="@id/fragment_c"
app:popUpToInclusive="true" />
<fragment
android:id="@+id/fragment_a"
android:name="fqn.FragmentA"
tools:layout="@layout/fragment_a" />
<fragment
android:id="@+id/fragment_b"
android:name="fqn.FragmentB"
tools:layout="@layout/fragment_b" />
<fragment
android:id="@+id/fragment_c"
android:name="fqn.FragmentC"
tools:layout="@layout/fragment_c" />
</navigation>
</navigation>

然后它应该像一样简单

// FragmentA
findNavController().navigate(R.id.fragment_a_to_fragment_b)
// FragmentB
findNavController().navigate(R.id.fragment_b_to_fragment_c)
// FragmentC
findNavController().navigate(R.id.fragment_c_to_fragment_b)

如果您想从FragmentB或FragmentC返回FragmentA,可以调用findNavController().popBackStack()

最新更新