In the project you need to do a fragment switch, always replace the fragment with the Replace () method: Then always feel a bit of lag when switching, the original code
/** * Toggle the page, which uses the callback * * @param f */public void Switchfragment (Fragment f) {if (f = = null) return; Fragmenttransaction transaction = Getsupportfragmentmanager (). BeginTransaction (); Transaction.replace (R.id.fl_main , f);//Transaction.addtobackstack (descstring); Transaction.commit ();//Let Menu go back to Menu.toggle ();}
However, there is a problem with this:
Each time you switch, fragment is re-instantiated, reloading one side of the data, which consumes both performance and user data traffic.
Just think, how to make multiple fragment switch to each other without re-instantiation?
Turned to the Android official doc, and some components of the source code, found that the replace () This method is only used in the last fragment no longer need to use the simple method.
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-instantiation
/** * Toggles the reload of the page, optimizes the Fragment switch * * @param f * @param descstring */public void Switchfragment (Fragment from, Fragment to) {if (from = = NULL | | to = = NULL) return; Fragmenttransaction transaction = Getsupportfragmentmanager (). BeginTransaction (). Setcustomanimations (R.anim.tran_ Pre_in,r.anim.tran_pre_out), if (!to.isadded ()) {//hides the current fragment,add next to activity in Transaction.hide (from). Add ( R.id.fl_main, to). commit ();} else {//hides the current fragment, showing the next transaction.hide (from). Show (To). commit (); Let menu go back to Menu.toggle ();}
Optimization of the fragment switchover