撰写导航:一旦导航出当前目的地,如何避免将其添加到后队列中?
用例如下:
- 我有一个已经有多个目的地的后队列。
? -> ... -> ?
- 将显示一个新的目的地(我们称之为 Foo 屏幕),并且当前位于顶部。
? -> ... -> ? -> F
- 我想从 Foo 屏幕导航到新的 Bar 屏幕,但是,根据特定条件,当导航回来时,我想返回 Foo 屏幕或跳过 Foo 屏幕并直接转到队列中的上一个屏幕。
if (skipFoo)
? -> ... -> ? -> B
else
? -> ... -> ? -> F -> B
这可以使用 androidx.navigation
中的 NavOptionsBuilder
来实现吗?
我知道我可以使用 popUpTo(0) { Include = true }
从堆栈中删除除新目的地之外的所有内容,但我只想防止在导航时添加当前屏幕并且仅当满足一定条件时才可以。
另外,目的地堆栈的内容是动态的(可以随时添加 Foo 屏幕),因此我不能简单地硬编码具有固定目的地的 popUpToId
,因为我不知道什么是堆栈上 Foo 屏幕之前的目的地。
The use case is the following:
- I have a back queue with already several destinations.
? -> ... -> ?
- A new destination, let's call it Foo screen, is shown and is currently at the top.
? -> ... -> ? -> F
- From the Foo screen I want to navigate to a new Bar screen but, depending on a certain condition, when navigating back I want to either go back to the Foo screen or skip the Foo screen and go directly to the previous screen in the queue.
if (skipFoo)
? -> ... -> ? -> B
else
? -> ... -> ? -> F -> B
Can this be achieved using the NavOptionsBuilder
from androidx.navigation
?
I know that I can use popUpTo(0) { inclusive = true }
to remove everything but the new destination from the stack but I just want to prevent the current screen to be added when I'm navigating out of it, and only when a certain condition is satisfied.
Also, the content of the stack of destinations is dynamic (the Foo screen can be added at any time) so I can't simply hardcode a popUpToId
with a fixed destination, since I don't know what is the destination immediately before Foo screen on the stack.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以使用 popUpTo 来完成:
It can be done using
popUpTo
:按照代码即可实现。它对我有帮助。
示例 1:
在导航到“好友列表”目的地之前,将所有内容从后台堆栈弹出到“主页”目的地
示例 2:
将所有内容弹出到“主页”目的地(包括“主页”)在导航到“好友列表”目的地之前,将“目的地从返回堆栈中删除
示例 3:
仅当我们尚未位于“搜索”目的地时才导航到“搜索”目的地,从而避免在“搜索”目的地上进行多次复制顶部返回堆栈的
引用:
https://developer.android.com/jetpack/compose/navigation
It can be achieved by following the code. it has helped me.
Example 1:
Pop everything up to the "home" destination off the back stack before navigating to the "friendslist" destination
Example 2:
Pop everything up to and including the "home" destination off the back stack before navigating to the "friendslist" destination
Example 3:
Navigate to the "search” destination only if we’re not already on the "search" destination, avoiding multiple copies on the top of the back stack
Ref Taken:
https://developer.android.com/jetpack/compose/navigation