Android-multiple Fragment switches are not re-instantiated
Problem:
To switch Fragment in a project, you can use the replace () method to replace Fragment:
Public void switchContent (Fragment fragment) {if (mContent! = Fragment) {mContent = fragment; mFragmentMan. beginTransaction (). setCustomAnimations (android. r. anim. fade_in, R. anim. slide_out ). replace (R. id. content_frame, fragment) // replace Fragment to implement failover. commit ();}}
However, there will beProblem:
During each switchover, Fragment will re-instantiate and reload the data, which consumes a lot of performance and user data traffic.
Solution:
How does one prevent multiple Fragment instances from being re-instantiated when they are switched to each other?
After reading the official Android Doc and the source code of some components, we found that the replace () method is only a simple method used when the previous Fragment is no longer needed.
The correct switching method is add (). When switching, hide (), add () and another Fragment; when switching again, only the current hide () and show () are needed.
In this way, multiple Fragment switches are not re-instantiated:
Public void switchContent (Fragment from, Fragment to) {if (mContent! = To) {mContent = to; FragmentTransaction transaction = mFragmentMan. beginTransaction (). setCustomAnimations (android. R. anim. fade_in, R. anim. slide_out); if (! To. isAdded () {// first checks whether transaction has been added. hide (from ). add (R. id. content_frame, ). commit (); // hide the current fragment and add the following to the Activity} else {transaction. hide (from ). show (). commit (); // hide the current fragment and display the next one }}}