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)