The following is a detailed analysis of the use of Fragment. If you need a friend, please refer to it.
Recently, things are very busy. A new project is coming out, but many functions need to be re-implemented, and code and Debug have been being compiled. Today, a new program uses Fragment. Although Fragment has been used before, it has not been carefully studied. Today, I will write an article to record the use of Fragment. This article mainly refers to the introduction on the Android official website.
Fragment is a new control added after Android3.0. It is similar to the Activity component and is used to hold various View elements. Google's goal is to reuse some of the displayed views on a tablet. if you write a View, it can be used on devices of different sizes, such as mobile phones and tablets. The conversion process system helps you solve the problem. Next we will talk about the use of Fragment in classification.
1. Why Fragment?
The following is an example of the function of Fragment on the Android Website: A news application can use fragment on the left side of the screen to display a list of articles, then, use another fragment on the right side of the screen to display an article-two fragment and display them in the same activity, and each fragment has its own set of lifecycle callback methods, and process their own user input events. Therefore, instead of using one activity to select an article and another activity to read the article, you can select an article in the same activity and read it ,:
When running on A very large screen (such as A tablet), the application can embed two fragment entries in Activity. However, if there is not enough space on A normal-sized screen (such as A mobile phone) for two fragment at the same time, Activity A will only contain the fragment of the article list, when you select an article, it starts ActivityB, which contains fragment for reading the article. therefore, the application can support two design modes at the same time.
Fragment is a component that can be reused for the interface view, because fragment defines its own layout and defines its own behavior by using its own lifecycle callback method, you can include fragment into multiple activities. this is especially important because it allows you to adapt your user experience to different screen sizes. for example, you may only include multiple fragment in an activity when the screen size is large enough. If this is not the case, another independent one will be started, use different fragment activities.
2. Create Fragment
To create a Fragment, you must create a Fragment subclass (or inherit from an existing subclass ). The code of the Fragment class looks like Activity. It contains callback methods similar to activity, such as onCreate (), onStart (), onPause (), and onStop (). In fact, if you want to convert a ready-made Android app to fragment, you may simply move the code from the callback method of your activity to the callback method of your fragment.
Next let's take a look at the child classes of Fragment:
• DialogFragment displays a floating dialog box. Using this class to create a dialog box is a good choice outside of the box tool method of the Activity class, because you can merge a fragment dialog box into the fragment back stack of activity management, allow the user to return to a previously abandoned fragment.
• ListFragment displays a list of projects managed by an adapter (for example, SimpleCursorAdapter), similar to ListActivity. It provides some methods to manage a list view, such as onListItemClick () callback to handle click events.
• PreferenceFragment displays a list of Preference object hierarchies, similar to PreferenceActivity. This is useful when creating a "set" activity for your application.
3. Fragment Lifecycle
The following figure shows the lifecycle of Fragment, which is taken from the Android website.
After inheriting the related Fragment classes, we need to rewrite several callback functions to implement relevant functions. The following three functions are the callback methods we will generally rewrite:
Copy codeThe Code is as follows:
// Edited by mythou
Public class MainFragment extends Fragment
{
// Create Fragment
Public void onCreate ()
{}
// Return the View to the Activity.
Public View onCreateView ()
{}
Public void onPause ()
{}
}
• OnCreate () When you create a fragment, the system calls this method. In the implementation code, you should initialize the necessary components to be maintained in the fragment. After the fragment is paused or stopped, it can be restored.
• The system calls this method when onCreateView () fragment draws its user interface for the first time. to draw the fragment UI, this method must return a View, which is the root view of your fragment layout. if fragment does not provide the UI, null can be returned.
• When an onPause () user is about to leave fragment, the system calls this method as the first indication (however, it does not always mean that fragment will be destroyed ). Before the end of the current user session, you should submit any persistent changes here (because the user may not return ).
In addition, we can see other callback methods by comparing the above lifecycle. We can rewrite related methods as needed.
4. Create Fragment
Fragment is usually used as a part of the user interface of an activity and provides its layout to the activity. To provide a layout for a fragment, you must implement the onCreateView () callback method. When the fragment draws its own layout, the Android system calls it. The implementation code of this method must return the Root view of layout of your fragment.
In addition, if your fragment is a subclass of ListFragment, its default implementation is to return a ListView from onCreateView (), so it generally does not have to be implemented.
The View returned from onCreateView () can also be read and generated from the xml resource file of layout. To help you do this, onCreateView () provides a LayoutInflater object.
The following is an example of loading a View from XML, which is the same as loading and parsing XML in a general View to generate a View.
Copy codeThe Code is as follows:
// Edited by mythou
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 into onCreateView () is the parent ViewGroup (layout from activity) that will be inserted by your fragmentlayout. The savedInstanceState parameter is a Bundle. If fragment is restored, it provides data about the previous instance of fragment. The inflate () method has three parameters:
• RSID: The resource ID of the layout to be loaded.
• Container: parent ViewGroup of the loaded layout. it is very important to pass in the container. The purpose is to allow the system to accept the layout parameter of the Root view to be loaded, which specifies the parent view to be attached.
• Boolean: indicates whether the expanded layout should be attached to ViewGroup during loading (the second parameter) (in this example, false is specified, because the system has inserted the expanded layout into the container-input true, a redundant view group will be created in the last layout)
5. Add Fragment to Activity
Generally, fragment provides a part of the UI for the host activity and is embedded as part of the entire viewhierarchy of the activity. You can add a fragment to the activity layout in two ways:
Declare fragment in the layout file of the activity:
In this case, you can specify the layout attribute for fragment like a View. In this example, an activity with two fragment entriesLayout:
Copy codeThe Code is as follows:
// Edited by mythou
<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: orientation = "horizontal"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent">
<Fragment android: name = "com. example. news. ArticleListFragment"
Android: id = "@ + id/list"
Android: layout_weight = "1"
Android: layout_width = "0dp"
Android: layout_height = "match_parent"/>
<Fragment android: name = "com. example. news. ArticleReaderFragment"
Android: id = "@ + id/viewer"
Android: layout_weight = "2"
Android: layout_width = "0dp"
Android: layout_height = "match_parent"/>
</LinearLayout>
The android: name attribute in <fragment> specifies the Fragment class instantiated in layout. When the system creates this activity layout, it instantiates each fragment specified in layout and calls the onCreateView () method on each to obtain the layout of each fragment. The system inserts the View returned from fragment directly to the location where the <fragment> element is located. Note: Each fragment requires a unique identifier. If the activity restarts, the system can be used to restore fragment (and you can also capture fragment to process transactions, such as removing it ).
There are three methods to provide an identifier for a fragment:
• Provide a unique id for the android: ID attribute.
• Provides a unique string for the android: tag attribute.
• If none of the above two items are provided, the system uses the container view ID.
Write code to add fragment to an existing ViewGroup.
You can add fragment to activity layout at any time when the activity is running. You only need to specify a ViewGroup for fragment. To operate fragment transactions (such as adding, removing, or replacing a fragment) in your activity, you must use APIs from FragmentTransaction. You can obtainFragmentTransaction instance:
Copy codeThe Code is as follows:
FragmentManager fragmentManager = getFragmentManager ();
FragmentTransaction fragmentTransaction = fragmentManager. beginTransaction ();
Then you can use the add () method to add a fragment, specifying the fragment to be added and the view to be inserted.
Copy codeThe Code is as follows:
Fragment = newExampleFragment ();
FragmentTransaction. add (R. id. fragment_container, fragment );
FragmentTransaction. commit ();
The first parameter of add () is the ViewGroup to be added by fragment, which is specified by the resource ID. The second parameter is the fragment to be added. Once a change is made with FragmentTransaction, commit () must be called to make the change take effect ().