Generally we get fragmentmanager when we write a program, then we start a transaction, then we make a fragment substitution and commit the transaction.
// 1. Get Fragmentmanger Fragmentmanager fm = Getsupportfragmentmanager (); // // 2. Turn on the transaction Fragmenttransaction transaction = fm.begintransaction (); // // 3. Replace transaction.replace (r.id.fl_content, fragment); // // 4. Commit a transaction Transaction.commit ();
However, in actual development, this approach leads to frequent creation of fragment, consumes user traffic, and all the following optimizations are proposed:
is to use Add () and hide (), before the fragment hide, and then to display the fragment added in, when to show the previous fragment, direct Show () out on it.
Private voidswitchframent (Fragment from,fragment to) {if(From! =To ) {mcontent=to ; Fragmenttransaction ft=Getsupportfragmentmanager (). BeginTransaction (); //before switching//judged to have not been added if(!to.isadded ()) { //To not be added//From Hidden if(From! =NULL) {ft.hide (from); } //Add to if(To! =NULL) {Ft.add (r.id.fl_content,to). commit (); } }Else{ //To has been added//From Hidden if(From! =NULL) {ft.hide (from); } //Show to if(To! =NULL{ft.show (To). commit (); } } } }
Tip: Remember to determine if the Add () fragment is null.
Fragment replacement display for Android development