The previous article we talked about the static creation of Fragment, which is almost not used in the actual development, are dynamically created, so-called dynamic creation is based on a condition of the dynamic creation of Fragment,
Now create an Android project dynamicfragment
Mainactivity.java
Package Com.example.dynamicfragment;import Android.app.activity;import Android.app.fragmentmanager;import Android.app.fragmenttransaction;import Android.os.bundle;import Android.view.windowmanager;public Class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (R.layout.activity_main); WindowManager wm = Getwindowmanager (); int width = Wm.getdefaultdisplay (). getwidth (); int height = Wm.getdefaultdisplay () . GetHeight ();//1. Get fragment manager Fragmentmanager FM = Getfragmentmanager ();//2. Manage the inside of the fragment open transaction to ensure that the interface update is successful at the same time or Simultaneous failure fragmenttransaction ft = fm.begintransaction (), if (height > width) {//Vertical screen//Android. R.id.content represents the current application of the Activityft.replace (Android. R.id.content, New Fragment1 ());} else {//flat screen//Android. R.id.content represents the current application of the Activityft.replace (Android. R.id.content, New Fragment2 ());} Ft.commit ();}}
Fragment1.java
Package Com.example.dynamicfragment;import Android.app.fragment;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;public class Fragment1 extends Fragment {@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) { Return inflater.inflate (r.layout.fragment1, NULL);}}
Fragment2.java
Package Com.example.dynamicfragment;import Android.app.fragment;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;public class Fragment2 extends Fragment {@Overridepublic View oncreateview (layoutinflater inflater, ViewGroup container,bundle savedinstancestate) { Return inflater.inflate (R.layout.fragment2, NULL);}}
XML file is not affixed, inside is a textview, so there is nothing to say, when the screen horizontal screen when the display Fragment1, screen vertical screen when the display Fragment2
Android Dynamic Create fragment