1.只要在Activity即将销毁时的onSaveInstanceState回调中通过FragmentManager.putFragment将Fragment保存在savedInstanceState中,则当APP回到前台恢复界面的时候,通过FragmentManager.getFragment可以获取到当前系统自动恢复并显示的Fragment的对象,即通过getVisibleFragment()获取到的Fragment与系统自动恢复并显示的Fragment是同一个对象
public Fragment getVisibleFragment(){ List fragments = fragmentManager.getFragments(); for(Fragment fragment : fragments){ if(fragment != null && fragment.isVisible()) return fragment; } return null; }
2.将Fragment通过FragmentManager.putFragment保存的时候,需要判断当前要保存的Fragment对象是否已经在FragmentManager中,否则会报错
if (fragment != null && fragmentManager.getFragments().contains(fragment)){ fragmentManager.putFragment(outState, getResources().getString(R.string.tag), fragment); }
3.Fragment中的ViewPager中再嵌套Fragment时,内存回收再恢复时生命周期的情况:父Fragment onAttach -> ViewPager中的Fragment onAttach -> onCreate -> 父Fragment onCreate -> onCreateView -> onActivityCreated -> ViewPager中的Fragment onCreateView -> onActivityCreated
正常情况下,生命周期为:父Fragment onAttach -> onCreate -> onCreateView -> onActivityCreated -> ViewPager中的Fragment onAttach -> onCreate -> onCreateView -> onActivityCreated