Why use fragment to manage the user interface?
Using fragment can make the interface more flexible and adapt well to different sizes of screens. It is recommended to use the classes in the Support library (android.support.v4.app.*) to implement the latest API features to fragment by upgrading the project's support library
How do I use fragment to manage the user interface?
Step one: Add a dependency in Androidstudio because the support library must be included in the dependency relationship in the project. Specific operation slightly!
Step two: Create Crimeactivity to inherit fragmentactivity, because Fragmentactivity knows how to manage fragment.
Activity managed fragment is available in two ways: adding (but not flexible) to the activity layout, which is added in the activity code (often in this way).
Step three: Arrange the location for the fragment in the crimeactivity layout file, usually with the Framelayout container view. The XML file code is as follows:
<framelayout
Xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:id= "@+id/fragment_container"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
/>
Step four: Create a new XML file named Fragment_crime, add the controls or something. This is Crimefragment's layout file.
Step five: Create a new Uifragment class (Inherit fragment), which requires the use of fragment lifecycle-related content. This class uses Oncreateview (Layoutinflater inflater, ViewGroup container, Bundle savedinstancestate) to instantiate the layout of the Fragment view,
Returns the materialized view to the managed avtivity, which is crimeactivity. This process establishes a link between fragment and activity. The fragment is also linked to its XML layout file. The code is as follows:
Public View Oncreateview (Layoutinflater inflater, viewgroup container, Bundle savedinstancestate) {
View v = inflater.inflate (r.layout.fragment_crime,container,false);
return v;
}
Step Six: You must associate the component in fragment and add a response.
Step Seven: Fragmentmanager is responsible for adding the fragment view to the activity's view structure. The code is as follows:
Fragmentmanager fm = Getsupportfragmentmanager ();
Fragment Fragment = Fm.findfragmentbyid (R.id.fragment_container);
if (fragment = = null) {
fragment = createfragment ();
Fm.begintransaction (). Add (R.id.fragment_container,fragment). commit ();
}
Uifragment and Fragmentmanager