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 = "">