Optimization of the fragment switchover

Source: Internet
Author: User

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

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.