Android Study Notes (14) -- add fragments at runtime (with source code)

Source: Internet
Author: User

Add fragments at runtime


Click to get source code

Splitting the UI into multiple configurable parts is one of the advantages of fragmentation, but its real strength lies in the ability to dynamically add them to activities at runtime.


1. Use the Fragments project created in the previous article to comment out two items in the main. xml file. Element;

2. Add the following code to FragmentActivity. java:

FragmentManager fragmentManager = getSupportFragmentManager (); // Add FragmentTransaction fragmentTransaction = fragmentManager to the activity. beginTransaction (); // Add FragmentTransaction to operate fragments. // obtain the current screen information of the device. Determine whether the device is in portrait or Landscape mode. WindowManager windowManager = getWindowManager (); Display display Display = windowManager. getdefadisplay display (); if (display. getWidth ()> display. getHeight () {// horizontal 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 (); Submit changes

3. Run the program on the simulator. The effect is as follows:

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

Vcqxo6zP1Mq + y + ngrdgjuw.vcd4kpha + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20140513/2014051308585220.jpg" alt = "">


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.