如何在Fragment中处理返回栈?

huangapple go评论48阅读模式
英文:

How to handle back-stack in Fragment?

问题

case 1: 我有3个片段 A、B、C。当我从 A 切换到 B,然后再从 B 切换到 C,然后在 C 片段上按下保存按钮后,我回到了片段 B,现在当我在片段 B 中按下返回按钮时,它会将我带到片段 C(C 片段存储在返回栈中),但我需要将用户带到片段 A 而不是 C。

---> 当用户在片段 B 的返回按钮上按下时,我使用以下代码。

navController!!.popBackStack()

case 2: 当我从 A 切换到 B,然后如果我按返回按钮,它会将我带回到片段 A(这个工作正常)。但在上述情况(案例 1)中,它会将用户带到片段 C 而不是 A。

我应该如何处理这种返回栈的情况?

英文:

case 1: I have 3 fragments A,B,C. When I am moving from A->B->C and then by pressing a save button on C fragment , I come back to fragment B and now when I press the back button at this point (in fragment B), it takes me to fragment C (C fragment is stored in the backstack) but I need to take the user to fragment A instead of C.

---> I am using this below code when user presses on back button of fragment B.

navController!!.popBackStack()

case 2: When I am moving A->B and now if I press back button it takes me back to fragment A. (This is working fine) . But in above case (case 1), it takes the user to fragment C instead of A.

How should I handle this backstack case?

答案1

得分: 1

在保存按钮点击后且在重定向到 B 片段之前,调用相同的代码:

navController!!.popBackStack()

因此,在 C 片段的代码如下:

// 保存按钮被点击
// 你的逻辑和代码
navController!!.popBackStack()
// 导航回到 B 片段
navController!!.navigate(B 片段的ID)
英文:

call same code

navController!!.popBackStack()

after saving button click and before redirection to B fragment

so in C Fragment code will be

//save button clicked 
// you logic and code 
navController!!.popBackStack()
//navigate back to B fragment 

navController!!.navigate(B fragment ID)

huangapple
  • 本文由 发表于 2023年2月8日 17:55:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384028.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定