Android Learning Note (14)--Add fragments at runtime (source code included)

Source: Internet
Author: User

Adding fragmentation at run time


Click to get Source code

Splitting the UI into multiple configurable parts is one of the advantages of fragmentation, but its real strength is that it can be dynamically added to the activity at run time.


1, using the fragments project created in the previous article, two <fragment> elements are commented out in the Main.xml file;

2. Add the following code in Fragmentactivity.java:

Fragmentmanager Fragmentmanager = Getsupportfragmentmanager ();//Add fragmentation to activity fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();//Add fragmenttransaction to manipulate fragmentation//Get device Current screen information: Determine whether you are in portrait or landscape mode WindowManager WindowManager = Getwindowmanager ();D isplay Display = Windowmanager.getdefaultdisplay (); if (Display.getwidth () > Display.getheight ()) {//Landscape mode Fragment1 fragment1 = new Fragment1 (); Fragmenttransaction.replace (Android). R.id.content, fragment1);} else {//portrait mode Fragment2 Fragment2 = new Fragment2 (); Fragmenttransaction.replace (Android. R.id.content, Fragment2);} Fragmenttransaction.commit (); Commit changes

3, run the program on the simulator, the effect is as follows:

When the device is in portrait mode, fragmentation 2 is displayed:


When the device is in landscape mode, fragmentation 1 is displayed:



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.