【发布时间】:2019-09-25 11:42:25
【问题描述】:
使用导航架构组件,在某些情况下,我们还可以从这样的代码中获得动态导航:
navController.navigate(R.id.cartFragment)
然后当我们需要从那个目的地导航到一个新的根目的地(返回导航将关闭应用程序)时,我们无法知道我们当前的根目的地是什么,所以我们不知道要设置什么 popUpTo目的地。
val navigationOptions = NavOptions.Builder().setPopUpTo(R.id.???, true).build()
navController.navigate(R.id.loginFragment, null, navigationOptions)
如果我们将其设置到不在后台堆栈中的目的地,那么我们会得到警告日志(来自NavController 中的popBackStackInternal):
“忽略 popBackStack 到目标 *:id/splashFragment,因为在当前返回堆栈上找不到它”
发生这种情况是因为我们之前在流程中也有多个案例,我们将 PopUpTo 设置为依赖于我们有不同的根目的地的流程。
我查看了NavController 上的所有可用方法,并尝试了对mBackStack 的一些反思,但我无法找到清除后台堆栈的方法。
在不知道当前根目的地的情况下如何清除backstack?
编辑:添加导航图示例
<fragment
android:id="@+id/navigation_cart"
android:name="ProjectsFragment_"
android:label="Cart"
tools:layout="@layout/fragment_cart" />
<fragment
android:id="@+id/loginFragment"
android:name="LoginFragment_"
android:label="Login"
tools:layout="@layout/fragment_login">
<--! Dynamic navigation to either Consent or Cart based on state -->
<action
android:id="@+id/action_login_to_home"
app:destination="@id/navigation_cart"
app:popUpTo="@id/loginFragment"
app:popUpToInclusive="true" />
<action
android:id="@+id/action_loginFragment_to_consentFragment"
app:destination="@id/consentFragment" />
<action
android:id="@+id/action_loginFragment_to_contactFragment"
app:destination="@id/contactFragment" />
</fragment>
<fragment
android:id="@+id/splashFragment"
android:name="SplashFragment_"
android:label="SplashFragment"
tools:layout="@layout/fragment_splash">
<--! Dynamic navigation to either Onboarding, Login or Cart based on state -->
</fragment>
<dialog
android:id="@+id/consentFragment"
android:name="ConsentFragment"
android:label="ConsentFragment"
tools:layout="@layout/fragment_consent" />
<fragment
android:id="@+id/onboardingIntroFragment"
android:name="OnboardingIntroFragment_"
android:label="OnboardingIntroFragment"
tools:layout="@layout/fragment_onboarding">
<action
android:id="@+id/action_onboardingIntroFragment_to_loginFragment"
app:destination="@id/loginFragment"
app:popUpTo="@id/onboardingIntroFragment"
app:popUpToInclusive="true" />
</fragment>
<dialog
android:id="@+id/contactFragment"
android:name="ContactFragment"
android:label="ContactFragment"
tools:layout="@layout/fragment_contact" />
关于上面 SplashFragment 中的具体案例,我们将根据状态动态导航到 Onboarding、Login 或 Cart。如果我们导航到登录,成功登录后导航到购物车。
在一般动态导航的两种情况下,我们都不知道我们的根目的地是什么,尽管无法正确设置 popUpTo。当从 Splash 调用时,它是 SplashFragment,当从 Login 调用时,它是 LoginFragment,或者在结帐中的另一种情况,它可能是 CartFragment 或另一个作为根目标的片段。
如何动态确定根目的地是什么,或者只是在导航过程中清除后台堆栈?
虽然这有点简化,因为我们的应用中有更多相同模式的案例。
编辑 2:根目标定义 我将根目的地定义为 popUpTo 的目的地,其中包含清除完整的后台堆栈,例如后台操作将关闭应用程序。 例如 Splash -> Login 将使用 popUpTo 清除 splash,然后 Login to Cart 应该清除 backstack 的其余部分,但现在根目标不是 Splash,而是 Login as Splash 在进入 Login 时弹出。
【问题讨论】:
-
能否请您提供导航图或屏幕流程草图
-
@user158 导航图示例已添加。
标签: android android-architecture-navigation