Analysis of the implementation of Android4.0-fragment framework (I.)

Source: Internet
Author: User

After repeated study and comparison, individuals feel that learning knowledge with problems is the most effective way of learning, so the text on the way to ask questions to tell the fragment framework implementation way.

1. What is fragment?

Fragment is included in the activity, fragment can only exist within the context of the activity, and fragment cannot be used without activity. Therefore, fragment can only be created in the context of the activity. Fragment can be a part of activity, fragment and activity are very similar, fragment has a view hierarchy associated with her, with a life cycle very similar to the activity.

2. Why use fragment?

Activity Usage Limitations: Multiple activity interfaces cannot be displayed on the screen. Therefore, fragment is created to compensate for the limitations of the activity. Fragment can respond to activity-like functions such as the back key like activity.

3, when the implementation of fragment, why should have a default constructor?

Talking about here, we have to talk about the structure of fragment. The structure of the fragment includes: The View hierarchy, the package that initializes the parameters

First look at the inheritance relationship between fragment and activity, 1-1, 1-2:

figure 1-1 Fragment class inheritance relationship                                                                                                                     figure 1-2 activity class inheritance relationship                           

It is easy to see that fragment is inherited directly from object, and activity is the subclass of the context. So we can conclude thatfragment is not an extension of activity. But like activity, we always extend fragment (or her subclasses) when we use fragment, and can change her behavior through subclasses.

Fragment can have a view hierarchy that interacts with the user, which is the same view hierarchy as the activity's view hierarchy, or can be created (augmented) or code-created through the XML Layout specification. (Note: If the view hierarchy needs to be displayed to the user, you must attach the fragment view hierarchy to the activity's attempt hierarchy)

So much has been introduced, just to get to the point, why fragment must include a default constructor (in Java classes, without constructors, a default constructor without parameters is automatically created at compile time.) Therefore, if there is no other constructor in the Java class, the default function can be omitted, the compiler will create it automatically, and if there are other constructors in the Java class, the system will not create a default constructor at compile time, so when there is a non-default constructor, a default constructor is required at compile time. The package that initializes the parameter, which must be displayed in the Java class, writes out the default constructor--similar to an activity, the fragment can be automatically saved by the system and restored later. When the system restores fragment, she calls the default constructor, and then restores the parameter package to the new fragment. Subsequent callbacks performed by the fragment can access these parameters, restoring the fragments to the previous state. So when using fragment, make sure you have the following two points:

    1. Ensure that the fragment class has a default constructor;
    2. Add a parameter Pack (bundle) as soon as fragment is created so that the fragment can be set correctly when fragment is rebuilt, and the Android system can correctly restore fragment if necessary.

Summary: The subclass of fragment must have a default constructor and a parameter package, because fragment will call the default constructor when re-created and will save the state to a package (bundle) object upon re-creation ( Note: Notice that the package (bundle) object is echoed back to the fragment OnCreate () callback in the case of the object package and the previously mentioned parameter package. The saved package (bundle) is also passed to Oninflate () \oncreateview () \onactivitycreated (). (Note: This is not a package that is attached as an initialization parameter.) It is possible to store the current state of the fragment in this package instead of the value that should be used to initialize her.

4. How does the life cycle of fragment integrate with the activity's life cycle?

Before using fragment, be sure to understand the life cycle of the fragment. The life cycle of the fragment is more complex than the life cycle of the activity, and understanding when to deal with fragment is critical. Since fragment is dependent on activity, let's look at the similarities and differences in the life cycle of the two, fragment with activity life cycle 1-3 and 1-4:

Figure 1-3 Activity Runtime fragment life cycle Figure 1- 4 Activity life Cycle

By comparing fragment and activity, many differences will be found, mainly because interactions between activity and fragment are needed. I believe that everyone's life cycle of activity is very familiar with, do not do too much introduction, directly into the topic fragment life cycle. At the beginning of fragment, the fragment is present in memory as an object. There are two scenarios for creating fragment instances:

    1. Create fragment instances;
    2. When the system re-creates the fragment from the save state, the initialization parameters are added to the fragmented object. When the system restores fragment from a saved state, the default constructor is called, and then the attachment initializes the parameter pack;

To create an instance of fragment using code:

[Java]View Plaincopy
    1. Public static myfragment newinstance (int index) {
    2. myfragment MF = new Myfragment ();
    3. Bundle args = new bundle ();
    4. Args.putint ("index", index);
    5. Mf.setarguments (args);
    6. return MF;
    7. }
1.onInflate () callback

API Documentation: Oninflate (activity activity, AttributeSet attrs, Bundle savedinstancestate)--called When a fragment is being create D as part of a view layout inflation, typically from setting the content view of an activity.

Called when a fragment are being created as part of a view layout inflation typically from setting the content view of a Activity. This may being called immediately after the fragment are created from a tag in a layout file. Note This is before the fragment ' s have been called; all you should does here are onAttach(Activity) parse the attributes and save them away.

Fragment calls its own oninflate () callback if fragment is defined by the <fragment> tag (usually in the active call Setcontentview () to set its own primary layout). This process passes in a attributeset (contains attributes from the <fragment> tag) and a saved package. If you recreate the fragment and you previously saved a state in Onsaveinstancestate (), the package (bundle) will contain the saved state value. Oninflate () expects the developer to read the attribute values and save them for later use. At fragment's oninflate () This life stage, it is too early to perform any action on the user interface, because fragment is not even associated with its activity.

(Note: the Oninflate () document does not match the actual use, and the document indicates that oninflate () is always called before Onattach (). In fact, after the activity restarts, oninflate () may be called after Oncreateview (). This is too late for setting the value to the package (bundle) and calling Setarguments (), and the Fragment life cycle diagram in the Android Official document does not include the Oninflate () in the life cycle, see For Android, it's hard to predict when oninflate () will be recalled.

2.onAttach () callback

Well, the discussion of so tangled problem, compared to everyone was I around dizzy, but the pursuit of technology in the road is not a slightest snub, a thorough analysis of the problem is our pursuit of technology mission. If everyone is a bit dizzy, it is recommended that you first see a comedy, sober mind! If you can persist, follow my thoughts and continue to explore. Onattach () callback, looking back, Mygod, the method finally appeared in the fragment life cycle of the diagram, and finally led everyone to the right track.

API documentation: public void Onattach (activity activity)--called when a fragment was first attached to its activity. onCreate(Bundle) 'll is called after this.

The Onattach () callback is called after fragment is associated with its activity. The use of activity references or the use of activity as a context for other operations will be implemented in this callback method.

Note: The fragment class has a getactivity () method that returns the activity associated with fragment. The initialization parameter bundle (bundle) can be obtained from the fragment's Getarguments () method throughout the lifetime of the fragment.

Avoid: After attaching fragment to activity , you cannot call Setarguments () again--except at the very beginning, you cannot add content to the initialization parameter.

3.onCreate () callback

The next callback method is OnCreate (), which you can not confuse with the activity's OnCreate () callback method. This callback gets the passed-in parameter package (NOTE: If a parameter bundle (bundle) is set at creation time), the code that needs to rely on the presence of the activity view hierarchy should not be placed in this callback method, although Fragment may now be associated with its activity, but we have not yet obtained the activity's OnCreate () completed notification, so it is not possible to put code that relies on the presence of the activity view hierarchy in this callback method.

(Note: In the OnCreate () callback method, we should try to avoid the time-consuming operation (avoid blocking the UI thread), it is very useful to trigger the background thread in the actual project, the blocking call should be in the background thread. )

Example code:

[Java]View Plaincopy
  1. /**
  2. * During creation, if arguments has been supplied to the fragment
  3. * Then the parse those out.
  4. */
  5. @Override public void OnCreate (Bundle savedinstancestate) {
  6. super.oncreate (savedinstancestate);
  7. Bundle args = Getarguments ();
  8. if (args! = null) {
  9. Mlabel = args.getcharsequence ("label", Mlabel);
  10. }
  11. }
4.onCreateView () callback

The next callback method is Oncreateview (), in which the callback method should return a view hierarchy of the fragment.

View oncreateview (layoutinflater inflater, ViewGroup container, Bundle savedinstancestate)--called to has The fragment instantiate its user interface view. This is optional, and non-graphical fragments can return null (which is the default implementation). This would be called between onCreate(Bundle) and onActivityCreated(Bundle) .

The bundle is a state package (note: Must be distinguished from the previously mentioned parameter bundle (bundle)) Note: Do not attach the view hierarchy to the incoming ViewGroup parent element, and the association will complete automatically. If the view hierarchy of fragmentation is attached to the parent element in this callback, an exception is likely to occur. The instance code is as follows:

[Java]View Plaincopy
  1. /**
  2. * Create The view for this fragment, using the arguments given to it.
  3. */
  4. @Override public View Oncreateview (layoutinflater inflater, ViewGroup container,
  5. Bundle savedinstancestate) {
  6. View v = inflater.inflate (R.layout.hello_world, container, false); The fragment view cannot be attached to the container element for this callback, so the Attachtoroot parameter must be false
  7. View TV = V.findviewbyid (R.id.text);
  8. ((TEXTVIEW) TV). SetText (Mlabel! = null? Mlabel: "(No label)");
  9. Tv.setbackgrounddrawable (Getresources (). Getdrawable (Android. R.DRAWABLE.GALLERY_THUMB));
  10. return v;
  11. }
5.onActivityCreated () callback

Finally the time to interact with the user, the onactivitycreated () callback is called after the activity completes its oncreate () callback. Before calling Onactivitycreated (), the activity's view hierarchy is ready, which is where you can perform the final adjustment to the user interface before the user sees the user interface. (Note: This callback is especially important if the activity and her fragment are recreated from the saved state, and you can ensure that all other fragment for this activity are already attached to the event)

6. Fragment and activity same life cycle call

The next OnStart () \onresume () \onpause () \onstop () callback method binds to the activity's callback method, that is, the same life cycle as the activity, and therefore does not introduce too much.

7.onDestroyView () callback

The callback method is called after the view hierarchy is detached from the fragment.

8.onDestroy () callback is not invoked when fragment is no longer used. (Note: Fragment is still attached to activity and can be found, but cannot perform other actions) 9.onDetach () Callback Fragme life cycle last callback function, after invocation, fragment no longer binds with activity, frees resources  . Through the above instructions, look at the fragment lifecycle and activity life cycle integration after 1-5 shows:                            Figure 1-5 Activity and fragment life cycle integration Figure 1-6 Fragment life cycle10. Clever use of setretaininstance ()

Why do you spend a certain length of time here detailing the Setretaininstance () method? Because this method can effectively improve the operating efficiency of the system, the application of high fluency requirements can be set appropriately by this method.

Fragment has a very powerful feature-that is, you can not completely destroy fragment when the activity is re-created so that fragment can recover. Calling the Setretaininstance (True/false) method in the OnCreate () method is the best place. Note the Red arrows in the figure as shown in life cycle 1-6 of the fragment recovery. When Setretaininstance (true) is called in the OnCreate () method, the OnCreate () and OnDestroy () methods are skipped fragment recovery, so you cannot place some initialization logic in OnCreate ().

5, how to manage fragment?

Since fragment must exist within the context of activity, how to manage fragment is the next topic we need to be concerned about. The Fragmentmanager component is responsible for managing fragments belonging to one activity (including fragments on the back stack and idle fragments). You can use the Getfragmentmanager () method on the activity or attached fragment to get the Shard manager. The code looks like this:

[Java]View Plaincopy
    1. Fragmentmanager Fragmentmanager = Getfragmentmanager ()
    2. Fragmenttransaction fragmenttransaction = Fragmentmanager.begintransaction ();

Analysis of the implementation of Android4.0-fragment framework (I.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.