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: