如何使用导航组件清除返回堆栈中的每个片段(例如,当 HTTP 401 触发时)并发送到登录片段 [英] How can I clear every fragments in back stack using Navigation Component (for example when HTTP 401 triggeres) and sent to login fragment

本文介绍了如何使用导航组件清除返回堆栈中的每个片段(例如,当 HTTP 401 触发时)并发送到登录片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有下一个属性可以在打开另一个片段时删除片段.

We have next attributes to remove fragment/fragments when opening another one.

app:popUpTo="..."
app:popUpToInclusive="true"

但是,如果我需要清除所有返回堆栈,但不知道 401 事件中的第一个 ID(并且起始目的地可能已经从堆栈中删除).

But in case when I need to clear all back stack not knowing which id was the first one (and start destination could have been already removed from stack) on 401 events for example.

我该怎么做?

例如,我可能有 5 个片段在后堆栈中,但我不知道第一个片段的 id,如何将它们全部删除并打开一个登录片段?

For example I may have 5 fragments in back stack and I don't know the id of the first one, and how can I remove them all and open a login fragment?

推荐答案

更新答案:

我们可以使用 R.id.nav_graph(导航图的 id)作为 setPopUpTo() 来完全清除 backstack

We can use R.id.nav_graph (id of our Navigation Graph) for setPopUpTo() to clear backstack completely

val navOptions = NavOptions.Builder()
    .setPopUpTo(R.id.nav_graph, true)
    .build()
navController.navigate(R.id.loginFragment, null, navOptions)

上一个答案:

我实现了这个解决方案,虽然看起来很困难

I implemented this solution, though it looks difficult

navController.graph = navController.graph.apply {
    startDestination = R.id.loginFragment
}
val navOptions = NavOptions.Builder()
    .setPopUpTo(R.id.loginFragment, true)
    .build()
navController.navigate(R.id.loginFragment, null, navOptions)

但它可以工作并清除所有返回堆栈并且堆栈中只有一个 loginFragment

But it works and clears all back stack and only one loginFragment will be in the stack

这篇关于如何使用导航组件清除返回堆栈中的每个片段(例如,当 HTTP 401 触发时)并发送到登录片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆