gpt4 book ai didi

android - 如何找出前一个 fragment 正在使用导航组件

转载 作者:行者123 更新时间:2023-12-02 12:03:20 24 4
gpt4 key购买 nike

我试图找出前一个 fragment 在后台堆栈中是什么,如果它是我想要的那个,那么回到那个 fragment ,否则转到另一个 fragment 。我在查找上一个 fragment 的名称/ID 时遇到问题。我目前的设置如下:

Fragment 1 -> Fragment 2 -> Fragment 3 if the previous id of Fragment 3 is >Fragment 2 then go back to it with arguments.



但我也会遇到这种情况:

Fragment 4 -> Fragment 3 here I want to be able to also check if the previous id/name of Fragment 3 is equal to Fragment 4 and if it is go back to that Fragment with arguments.



基本上, fragment 3 将有不同的路线,我希望能够确定它将去往下一个之前的 fragment 。

我的问题是我无法从以前的 fragment 中获取信息。检查是否有任何可能。我是使用 Android 导航组件的新手,因此不胜感激。

如果这个问题看起来有点令人困惑,请告诉我,以便我在需要时重写它。

谢谢!

最佳答案

你会使用 previousBackStackEntry返回 NavBackStackEntry那是:

the previous visible entry on the back stack or null if the back stack has less than two visible entries


要获取上一个目的地的 id,请使用: previousBackStackEntry.destination.id但因为它可以为空,所以使用 previousBackStackEntry?.destination?.id在您的场景中应用它:
在 fragment 3 中:
val previousFragment = findNavController().previousBackStackEntry?.destination?.id

previousFragment?.let {
when (previousFragment) {
R.id.fragment_2_id ->
// The previous fragment is Fragment 2

R.id.fragment_4_id ->
// The previous fragment is Fragment 4

else ->
// The previous fragment is neither Fragment 2 nor 4
}
}

关于android - 如何找出前一个 fragment 正在使用导航组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56382098/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com