简体   繁体   English

使用两个可能的后堆栈路径为片段还原片段后堆栈

[英]Restoring fragment backstack for fragment with two possible backstack paths

I have one Activity with 3 fragments which form a workflow to collect user input. 我有一个带有3个片段的Activity,构成了收集用户输入的工作流。 Normally, Fragment A is the first fragment -> Launches B -> Launches C. B is supposed to launch A if the back button is pressed, and similarly C's Back button is supposed to launch B. 通常,片段A是第一个片段->启动B->启动C。如果按下后退按钮,B应该启动A,类似地,C的后退按钮也应该启动B。

However, in some cases, A is supposed to launch C directly, and then C's back should launch A again. 但是,在某些情况下,A应该直接启动C,然后C的后背应该再次启动A。

I prefer that C should not know who launched it. 我更喜欢C不应该知道谁启动了它。 Ie I want C's "backstack" to operate without C knowing who launched it. 也就是说,我希望C的“后堆栈”在不知道C是谁启动的情况下运行。

I tried using the usual addToBackstack approach, but I'm facing a problem when the Activity gets killed after the user lets the app go into the background while C was open. 我尝试使用通常的addToBackstack方法,但是当用户在C打开时让应用程序进入后台后,Activity被杀死时,我遇到了一个问题。

  1. I would like the user to return to "C" instead of starting all over from A. To achieve this I'm using the saved Instance state, and detecting which fragment was previously active, and launching it from the activity. 我希望用户返回“ C”,而不是从A重新开始。要实现这一点,我要使用保存的Instance状态,并检测先前处于活动状态的片段,然后从活动中启动它。
  2. The problem starts when the user wants to go back from C, after the Activity was recreated after being killed. 当用户被杀死后重新创建活动后,当用户想从C返回时,问题就开始了。 C doesn't know who launched it: A or B. How do I make the Back button work as expected for this case? C不知道是谁启动的:A或B。在这种情况下,如何使“后退”按钮正常工作?

Found some answers in this excellent video by Android Developers + Adam Powell: Fragments: Google I/O 2016 在Android开发人员+ Adam Powell的精彩视频中找到了一些答案: Fragments:Google I / O 2016

In summary, Fragments and the Fragment BackStack are considered part of the navigational state of the app, so, as long as I don't mess with the backstack when the activity is launched, the OS will also restore the FragmentBackStack, thus the BackStack will know who launched C (A or B) even if the activity gets re-created. 总而言之,Fragments和Fragment BackStack被认为是应用程序导航状态的一部分,因此,只要在启动活动时我不打扰Backstack,操作系统还将还原FragmentBackStack,因此BackStack将即使重新创建了活动,也知道谁发起了C(A或B)。 Thus, popBackStack will move from C to A or B as required. 因此,popBackStack将根据需要从C移到A或B。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM