Fragment replacement display for Android development

Source: Internet
Author: User

Generally we get fragmentmanager when we write a program, then we start a transaction, then we make a fragment substitution and commit the transaction.

// 1. Get Fragmentmanger        Fragmentmanager fm = Getsupportfragmentmanager (); //        // 2. Turn on the transaction        Fragmenttransaction transaction = fm.begintransaction (); //        // 3. Replace         transaction.replace (r.id.fl_content, fragment); //        // 4. Commit a transaction        Transaction.commit ();

However, in actual development, this approach leads to frequent creation of fragment, consumes user traffic, and all the following optimizations are proposed:

is to use Add () and hide (), before the fragment hide, and then to display the fragment added in, when to show the previous fragment, direct Show () out on it.

Private voidswitchframent (Fragment from,fragment to) {if(From! =To ) {mcontent=to ; Fragmenttransaction ft=Getsupportfragmentmanager (). BeginTransaction (); //before switching//judged to have not been added            if(!to.isadded ()) {                //To not be added//From Hidden                if(From! =NULL) {ft.hide (from); }                //Add to                if(To! =NULL) {Ft.add (r.id.fl_content,to). commit (); }            }Else{                //To has been added//From Hidden                if(From! =NULL) {ft.hide (from); }                //Show to                if(To! =NULL{ft.show (To). commit (); }            }        }    }

Tip: Remember to determine if the Add () fragment is null.

Fragment replacement display for Android development

Related Article

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.