In general, fragment is used as part of the activity user interface, and it provides its own layout for the activity.
To provide a layout for fragment, you must implement the oncreateview () callback method. The system will call this method when plotting the layout for fragment. The implementation of this method must return a view, which is the root of the fragment layout.
NOTE: If your fragment is a subclass of listfragment, the default implementation is to return a listview () from the oncreateview () method, so you do not need to implement it.
To return a layout from the oncreateview () method, you can fill it with the definition of a layout resource in the XML file. To help you do this, the oncreateview () method provides a layoutinflater object.
For example, a subclass of fragment loads a layout using the example_fragment.xml file:
Public static class examplefragment extends fragment {
@ Override
Public View oncreateview (layoutinflater Inflater, viewgroup container,
Bundle savedinstancestate ){
// Inflate the layout for this fragment
Return Inflater. Inflate (R. layout. example_fragment, container, false );
}
}
The container parameter passed to the oncreateview () method is the parent class of viewgroup (layout from activity). Your fragment parameter will be inserted into this container. If the fragment is being restored, the savedinstancestate parameter provides a bundle object related to the data of the previous fragment instance (handling the fragment lifecycle) in this section, we will discuss more about restoring the status ).
The inflate () method requires three parameters:
1. The first parameter is the resource ID of the layout you want to fill in;
2. the second parameter viewgroup is the parent container of the filled layout. It is vital to pass the container parameter because during the execution of this method, the system uses the layout parameter specified by this parent view as the Root View of the filled layout.
3. A boolean parameter indicates whether to bind the layout to viewgroup (the second parameter) during filling. In this example, false is specified because the system has inserted the filled layout into the container parameter. If true is passed, a redundant viewgroup is created in the final layout.
You have seen how to create a fragment that provides layout. Next you need to add the fragment to the activity.