Android-Multiple fragment switches are not re-instantiated

Source: Internet
Author: User
Tags switches

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.