Problem:
You need to switch fragment in your project, you can replace fragment with the Replace () method:
public void Switchcontent (Fragment Fragment) {if (mcontent ! = fragment) {mcontent = Fragment Mfragmentman.begintransaction () .set Customanimations (Android .anim .fade _in, R.anim .slide _out) .replace (R.id _frame, fragment)//replace fragment, implement toggle .commit () } }
However, there is a problem with this:
每次切换的时候,Fragment都会重新实例化,重新加载数据,这样非常消耗性能和用户的数据流量。
Solve:
How do I make multiple fragment switch to each other without re-instantiating it?
Turned to the Android official doc, and some components of the source code, found that replace () This method is only 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-instantiating:
public void Switchcontent (Fragment from, Fragment to) {if (mcontent! =) {mcontent = to;Fragmenttransaction transaction = Mfragmentman. BeginTransaction(). Setcustomanimations(Android. R. Anim. Fade_in, R. Anim. Slide_out);if (!to. isadded()) {//To determine if theAddOver transaction. Hide(from). Add(R. ID. Content_frame, to). Commit()//Hide current fragment,add next to activity} else {Transaction. Hide(from). Show(To). Commit();//hides the current fragment, showing the next} } }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android-Multiple fragment switches are not re-instantiated