Android Learning Notes (14)--Add fragments when executing (source code)

Source: Internet
Author: User

Adding fragmentation at execution time


Click to get Source code

Cutting 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 execution time.


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

2. Add the following code to the Fragmentactivity.java:

Fragmentmanager Fragmentmanager = Getsupportfragmentmanager ();//Add fragment to activity fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();//Add fragmenttransaction to manipulate fragmentation//Get device current screen information: Infer 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, execute 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. Show Fragmentation 1:



Android Learning Note (14)--Add fragments when executing (source code)

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.