Http://www.tuicool.com/articles/FJ7VBb
Avoid UI reload when fragmenttabhost switches to fragment
However, there is a defect in the first implementation. Each time the fragmenttabhost switches to fragment, it will call oncreateview () to re-paint the UI.
Solution: cache view in fragment oncreateview:
Java code collection code
Private view rootview; // cache fragment View
@ Override
Public View oncreateview (layoutinflater Inflater, viewgroup container,
Bundle savedinstancestate)
{
Log. I (TAG, "oncreateview ");
If (rootview = NULL)
{
Rootview = Inflater. Inflate (R. layout. fragment_1, null );
}
// You need to determine whether the cached rootview has been added with a parent. If a parent needs to be deleted from the parent, the rootview has a parent error.
Viewgroup parent = (viewgroup) rootview. getparent ();
If (parent! = NULL)
{
Parent. removeview (rootview );
}
Return rootview;
}
Http://www.yrom.net/blog/2013/03/10/fragment-switch-not-restart/
Fragment switching is required in the project. The Replace () method is always used to replace fragment:
123456789 |
Public void switchcontent (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 is a problem:
During each switchover, fragment will be re-instantiated to reload data on one side, which consumes a lot of performance and user data traffic.
Just think about how to make multiple fragment do not re-instantiate when switching from one another?
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:
123456789101112 |
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 }}}
|
Enable re-instantiation of multiple fragment Switches