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

前端之家收集整理的这篇文章主要介绍了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相关文章