简体   繁体   English

在活动上保存/恢复片段堆栈已损坏

[英]save/restore fragment stack on Activity destroyed

In my project, there are Activities and Fragments. 在我的项目中,有活动和片段。 And there's an Fragment backstack. 而且有一个Fragment堆栈。

My question is how to save/restore the fragment stack in case of Activity is destroyed by the OS. 我的问题是在操作系统破坏Activity的情况下如何保存/恢复片段堆栈。


@forcewill are you taling about addToBackStack? @forcewill谈谈addToBackStack吗? Yes I did. 是的,我做到了。 I'm not talking about popup topmost fragment in case of back pressed. 我不是在谈论弹出的最上面的片段,以防后按。 I'm talking about to restore the fragment stack in case of Activity destroyed. 我说的是在活动被破坏的情况下恢复片段堆栈。


@Derek, I did follow your way to write the following to every fragment and activity to override onStaveInstanceState(...) @Derek,我确实按照您的方式将以下内容写入每个片段和活动,以覆盖onStaveInstanceState(...)

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

But it seems like it's still not working. 但似乎仍然无法正常工作。

I have tested on - Galaxy S3 with Android 4.1 - Emulator with Android 5.1 (to turn a debugging option named "Don't keep activity" 我已经测试过-具有Android 4.1的Galaxy S3-具有Android 5.1的模拟器(打开名为“请勿继续活动”的调试选项)


@josedlujan, it's not about save single Fragment instance, it's about save the fragments in stack. @josedlujan,这与保存单个Fragment实例无关,而与将片段保存在堆栈中有关。

Use savedInstanceState 使用savedInstanceState

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ...
    if (savedInstanceState != null) {
        //Restore the fragment's state here
    }
}
...
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

//Save the fragment's state here



}

Derek Fung is corrrect. 冯德烈是正确的。 As long as the fragment is add to backstack, the fragment backstack will be maintained by the system. 只要将片段添加到Backstack,片段Backstack就会由系统维护。

I was stupid, I did something in onResume/onCreate in the activity, which leads to clear up the fragment backstack which has been restored. 我很愚蠢,我在活动的onResume / onCreate中做了一些操作,这导致清理已还原的片段回栈。

Close this 关闭这个

How did I make the stupid mistake 我怎么犯了愚蠢的错误


public class MyActivity {
    ....
    onResume() {
        bottomBar.setDefaultIfNotSet();
    }
    ....
}

The method in onResume would clear the Fragment Backstack. onResume中的方法将清除Fragment Backstack。 In the BottomBar, I didn't save it's state on Activity destroy. 在BottomBar中,我没有保存活动销毁状态。 So while the Activity is restored, this view doesn't have the knowledge that it's actually restored "not created from scratch" 因此,在还原“活动”时,该视图不知道它实际上是“不是从头开始创建的”还原的

Thank you Derek and other guys. 谢谢德里克和其他人。

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

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