Android-multiple Fragment switches are not re-instantiated

Source: Internet
Author: User

Android-multiple Fragment switches are not re-instantiated

Problem:
To switch Fragment in a project, you can use the replace () method to replace Fragment:

Public void switchContent (Fragment fragment) {if (mContent! = Fragment) {mContent = fragment; mFragmentMan. beginTransaction (). setCustomAnimations (android. r. anim. fade_in, R. anim. slide_out ). replace (R. id. content_frame, fragment) // replace Fragment to implement failover. commit ();}}

However, there will beProblem:
During each switchover, Fragment will re-instantiate and reload the data, which consumes a lot of performance and user data traffic.

Solution:
How does one prevent multiple Fragment instances from being re-instantiated when they are switched to each other?
After reading the official Android Doc and the source code of some components, we found that the replace () method is only a simple method used when the previous Fragment is no longer needed.
The correct switching method is add (). When switching, hide (), add () and another Fragment; when switching again, only the current hide () and show () are needed.
In this way, multiple Fragment switches are not re-instantiated:

Public void switchContent (Fragment from, Fragment to) {if (mContent! = To) {mContent = to; FragmentTransaction transaction = mFragmentMan. beginTransaction (). setCustomAnimations (android. R. anim. fade_in, R. anim. slide_out); if (! To. isAdded () {// first checks whether transaction has been added. hide (from ). add (R. id. content_frame, ). commit (); // hide the current fragment and add the following to the Activity} else {transaction. hide (from ). show (). commit (); // hide the current fragment and display the next one }}}

 

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.