android – 在backstack中不是最顶级的片段恢复

鉴于应用程序流程在图形和文本中描述如下所示.

>片段1是最低片段,但不是通过设置disallowAddToBackStack在backstack中.
>使用fragmentTransaction.addToBackStack()将片段2推入堆栈.
>片段1的新实例被压入堆栈.
>从堆栈中弹出最顶层的片段(片段1).
>活动2成为前景.
>活动1成为前景.

这是我用来处理片段的通用方法

private void changeContainerViewTo(int containerViewId,Fragment fragment,Activity activity,String backStackTag) {

    if (fragmentIsAlreadyPresent(containerViewId,fragment,activity)) { return; }
    final FragmentTransaction fragmentTransaction = 
                 activity.getFragmentManager().beginTransaction();
    fragmentTransaction.replace(containerViewId,fragment);
    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    if (backStackTag == null) {
        fragmentTransaction.disallowAddToBackStack();
    } else {
        fragmentTransaction.addToBackStack(backStackTag);
    }
    fragmentTransaction.commit();
}

问题

当活动1在最后一步中恢复时,片段1的最低实例也将恢复.此时,片段1在getActivity()上返回null.

>为什么堆栈中不是最重要的片段会重新开始?
>如果恢复片段是正确的 – 我应该如何处理分离的片段?

最佳答案
一个Activity没有显示UI然后显示UI时,FragmentManager关联的所有碎片都会死亡,你需要恢复它的状态.

正如documentation所说:

There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing),but its state will not be saved until its owning activity actually needs to save its state.

在Activity onSaveInstanceState和onRestoreInstanceState中,尝试保存片段引用,然后使用以下内容恢复它们:

public void onSaveInstanceState(Bundle outState){
    getFragmentManager().putFragment(outState,"myfragment",myfragment);
}
public void onRetoreInstanceState(Bundle inState){
    myFragment = getFragmentManager().getFragment(inState,"myfragment");
}

试试这个,祝你好运!

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...