给定应用程序流程显示在下面的图形和文字描述中。
- fragment 1 是最低 fragment ,但通过设置
disallowAddToBackStack
不在后台堆栈中。 - 使用
fragmentTransaction.addToBackStack()
将 fragment 2 压入堆栈。 - fragment 1 的新实例被压入堆栈。
- 从堆栈中弹出最顶部的 fragment ( fragment 1)。
- Activity 2 成为前景。
- Activity 1 成为前景。
这是我用来处理 fragment 的通用方法:
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();
}
问题
当 Activity 1 在最后一步恢复时, fragment 1 的最低实例也会恢复。此时 fragment 1 在 getActivity()
上返回 null
。
问题
- 为什么不是栈顶的 fragment 会被恢复?
- 如果恢复 fragment 是正确的 - 我应该如何处理分离的 fragment ?
最佳答案
当 Activity
未显示 UI 然后又显示 UI 时,关联的 FragmentManager
将与您的所有 fragment 一起消失,您需要恢复其状态。
作为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
中,尝试保存你的 Fragment
引用,然后用类似的东西恢复它们这个:
public void onSaveInstanceState(Bundle outState){
getFragmentManager().putFragment(outState,"myfragment", myfragment);
}
public void onRetoreInstanceState(Bundle inState){
myFragment = getFragmentManager().getFragment(inState, "myfragment");
}
试试这个,祝你好运! :-)
关于android - 恢复堆栈中不是最顶层的 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15878109/