Switching fragment in the project has always replaced the fragment with the Replace () method. However, there is a problem, each time you switch the fragment will be re-serialized, reload the data, so that it will be very expensive performance with the user's traffic.
The official document explains that the replace () method is simply a convenient way to use the last fragment when it is no longer needed.
The correct way to switch is add (), hide (), add () another fragment when switching again, just hide () and show () another.
This makes it possible to do multiple fragment switches without re-instantiating:
Switching method:
/*** Fragment Toggle * *@paramFrom *@param to*/ Public voidSwitchcontent (Fragment from, Fragment to,intposition) { if(Mcontent! =To ) {mcontent=to ; Fragmenttransaction Transaction=fm.begintransaction (); if(!to.isadded ()) {//first determine if the add has beenTransaction.hide (from). Add (R.id.content_frame, to, Tags[position]). commit (); /c8>//hides the current fragment,add next to the activity}Else{transaction.hide (from). Show (To). commit ();//hides the current fragment, showing the next } } }
It seems to be fine after doing it. But the low-end phone memory is not enough to cause fragment overlap.
It is the problem of duplicate creation and overlap of fragment caused by restarting after the activity is recycled.
onCreate()
when adding fragment to your activity, be sure not to forget to check savedInstanceState
:
Multiple fragment overlap can be handled this way: by FragmentManager
finding all of them UI Fragment
, show () one fragment,hide () and others as needed!
In order to accurately identify the desired fragment, add()
replace()
Remember to take the parameters when or fragment, tag
because a viewgroup container can be attached to add()
multiple fragment, their id
Nature is the same.
/*** Status detection is used when memory is low to ensure fragment does not overlap * *@paramsavedinstancestate*/ Private voidStatecheck (Bundle savedinstancestate) {if(Savedinstancestate = =NULL) {FM=Getfragmentmanager (); Fragmenttransaction FTS=fm.begintransaction (); Animationfragment af=Newanimationfragment (); Mcontent=af; Fts.add (R.id.content_frame, AF); Fts.commit (); } Else{animationfragment af=(animationfragment) Getfragmentmanager (). Findfragmentbytag (tags[0]); Plainfragment PF=(plainfragment) Getfragmentmanager (). Findfragmentbytag (tags[1]); Recordfragment RF=(recordfragment) Getfragmentmanager (). Findfragmentbytag (tags[2]); Informationfragment inf=(informationfragment) Getfragmentmanager (). Findfragmentbytag (tags[3]); Testingfragment TF=(testingfragment) Getfragmentmanager (). Findfragmentbytag (tags[4]); Getfragmentmanager (). BeginTransaction (). Show (AF). Hide (PF). Hide (TF). commit (); } }
Android frament switch (to solve the inefficiencies of replace)