Cause analysis
Activity saves the status of all added Fragments after adding Fragments to Activity; Activity recreates the original fragments and attach es them when it is reclaimed due to problems such as system memory; however, if we use a reference to save and use Fragments in ViewPager, it will cause an exception.
Problem solving
Programme 1
Activity does not call the parent class's method to save Fragment status.
@Override protected void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); }
Programme 2
In the onCreate method of Fragment, the following method is called to clear all the sub-Fragments to which the current Fragment belongs.
private void clearFragments(){ FragmentManager fm = getChildFragmentManager(); if(fm != null && fm.getFragments() != null && fm.getFragments().size() > 0){ FragmentTransaction ft = fm.beginTransaction(); for(Fragment fragment : fm.getFragments()){ ft.remove(fragment); } ft.commit(); } }
Programme 3
Override Activity's onCreate method:
@Override protected void onCreate(Bundle savedInstanceState) { if(savedInstanceState != null){ savedInstanceState.remove("android:support:fragments"); } super.onCreate(savedInstanceState); ... }
Programme 4
When obtaining Fragment s in ViewPager, do not get them by reference, instead, get them by the following way:uuuuuuuuuuuu
/** * ViewPager Find the Fragment of the specified location based on position * @param fragmentManager * @param viewPagerId * @param fragmentPagerAdapter * @param position * @return */ public static Fragment getFragment(FragmentManager fragmentManager, int viewPagerId, FragmentPagerAdapter fragmentPagerAdapter, int position){ if(fragmentManager != null){ String tag; if(fragmentPagerAdapter != null){ tag = "android:switcher:" + viewPagerId + ":" + fragmentPagerAdapter.getItemId(position); } else { tag = "android:switcher:" + viewPagerId + ":" + position; } return fragmentManager.findFragmentByTag(tag); } else { return null; } }
conclusion
The above four methods can solve some problems caused by Activity's own reconstruction of Fragment, but the maintainability and scalability of scheme 1, 2 and 3 are not good, recommend scheme 4.
Thoughts on Problems
1. In scenario 2, when Activity destruction is rebuilt, sub-fragments will be rebuilt automatically, but after onCreate is cleaned up with code, our business code will be rebuilt later.
2. Schemes 1, 2 and 3 are all trying to eliminate the original Fragment and its state. Schemes 4 only modifies the way of obtaining Fragment and better retains the original Fragment state logic.