[Android] Fragment Full Analysis

Source: Internet
Author: User

1. Overview

Fragment is a behavior or part of the user interface in activity. The main support is to dynamically and flexibly combine or exchange UI components on a large screen, by splitting the activity's layout into several fragment that can edit the rendering of the activity at run time, and those changes will be stored in the background stack managed by the activity.

  fragment must always be embedded in an activity , and the life cycle of the fragment is directly affected by the life cycle of its host activity. You can think of fragment as a module part of activity that has its own life cycle, receives its own input events, and can be added or deleted while the activity is running.

Each fragment should be designed as a modular and reusable activity component. That is, you can refer to the same fragment in more than one activity, because fragment defines its own layout and uses its own life cycle callback behavior.

2. The life cycle of fragment

First look at the Fragment life cycle diagram:

The activity life cycle of fragment directly affects the life cycle of fragment, thus triggering a fragment similar callback for each life cycle callback of the activity. For example, when activity receives OnPause (), each fragment in the activity receives OnPause ().
Here's a detailed description of the activity.

Fragment has some additional life cycle callback methods (creating and destroying fragment interfaces).

    • Onattach ()

      Called when fragment is bound to activity (activity is passed in).

    • Oncreateview ()

      Build your own layouts into activity (fragment as part of the activity Interface)
        

    • Onactivitycreated ()

      Called when the activity's OnCreate () function returns.

    • Ondestroyview ()

      Called when the view system associated with fragment is being removed.

    • Ondetach ()

      Called when fragment is being disassociate from activity.

When the activity receives its oncreate () callback, the fragment in the activity receives a onactivitycreated () callback.

Once the activity is in the resumed state, you can freely add or remove fragment in the activity. Therefore, only when the activity is in the resumed state , the life cycle of the fragment can change independently.
  
Fragment will again be pushed into its life cycle by activity when the activity leaves the recovery state.

managing the Fragment life cycle is similar to managing the activity life cycle. Like activity, fragment also has three states:

    • Resumed

      Fragment is visible in the running activity.

    • Paused

      Another activity is in the foreground and gets the focus, but the activity of the fragment is still visible (the foreground activity is partially transparent or not covered in full screen).

    • Stopped

      Fragment not visible. Either the host activity has stopped, or fragment has been removed from the activity but has been added to the background stack. A stopped fragment is still alive (all state and member information is still kept by the system). However, it is no longer visible to the user and will be killed if the activity is killed.

      If the activity process is killed, you need to restore the fragment state when the activity is recreated. You can perform fragment onsaveinstancestate () to save the State (note that the fragment is restored in OnCreate (), Oncreateview (), or onactvitycreate ().

      In the life cycle, an important difference between activity and fragment is how it is stored in its own background stack.
      When activity is stopped, activity is placed in the system-managed activity background stack by default ;
      Fragment only when a transaction is removed, the fragment is placed in the background stack managed by the host activity by explicitly invoking Addtobackstack () to request the saved instance.

to create a fragment, you must create a fragment subclass. In general, we need to implement at least some of the following fragment life cycle methods:

OnCreate ()

This method is called by the system when the fragment is created. In the implementation code, you can initialize the necessary components that you want to keep in fragment, and re-enable them when the fragment is paused or stopped.

Oncreateview ()

This method is called by the system the first time the user interface is drawn for fragment. To draw the user interface for fragment, this function must return the root view of the painted fragment. If fragment does not have a user interface, you can return empty.

@Override        publiconCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {             // Inflate the layout for this fragmentreturnfalse);        }

The inflate () function requires the following three parameters:

① The resource ID of the layout to be inflate.

② is inflate the layout of the parent viewgroup.

③ A Boolean value that indicates whether the layout that was infalte during inflate should be attached viewgroup (the second parameter container). (False is passed in this example, because the system has inserted the inflate layout into the container (container)--passing in true creates an extra viewgroup in the final layout. )

OnPause ()

The system callback uses this function as the first omen for the user to leave fragment (although this does not always mean that fragment is destroyed). Before the end of the current user session, it is common to commit any changes that should persist here (because the user may no longer return).

3. Add fragment to the activity

You can insert the fragment into the activity's layout with the fragment tag by declaring fragment in the activity layout file, or add it to an existing viewgroup using the application source code.
  
But fragment is not a set to be part of the activity layout, fragment can also work stealth for activity.

3.1 Declare fragment in the activity's layout file

You can specify layout properties for fragment as you would for a view. For example:

<?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.test.FragmentOne"android:id=  "@+id/fo"android:layout_width="Match_parent"android:layout_height="Match_ Parent " />                                                    </linearlayout>

The Android:name property in the fragment tag specifies the fragment class that is instantiated in the layout.

When the system creates an activity layout, it instantiates each of the fragment specified in the layout file and calls the Oncreateview () function for them to get the layout of each fragment. The system inserts the view returned by the fragment directly at the location of the element.

Note: Each fragment requires a unique identity, and if the activity is restarted, the system can be used to recover the fragment (and to capture fragment transactions such as removal). There are three ways to provide an ID for fragment:

    • Provides a unique identity with the Android:id property.

    • Provides a unique string with the Android:tag property.

    • If neither of these properties is available, the system uses the ID of its container view.

3.2 Adding fragment to an existing ViewGroup by encoding

You can add fragment to the activity layout at any time when the activity is running.
  
To manage fragment in your activity, you can use Fragmentmanager. can be obtained by calling Getfragmentmanager () in the activity. Using Fragmentmanager, you can do the following things, including:

    • Use Findfragmentbyid () (to provide an interface fragment in the activity layout) or Findfragmentbytag () Gets the fragment that exist in the activity (for fragment with or without an interface).

    • Eject fragment from the background stack using Popbackstack () (imitating the user's back command).

    • Use Addonbackstackchangedlistener () to register a listener that listens for changes in the background stack.

In Android, transactional operations on fragment are performed through Fragmenttransaction. Operations can be broadly divided into two categories:

    • Display: Add () replace () show () Attach ()

    • Hide: Remove () Hide () detach ()

Description
When the show () & Hide () method is called, the Fragment life cycle method is not executed, only the fragment view is displayed or hidden.

When you execute replace () (at least two fragment), the second fragment Onattach () method is executed, the OnPause ()-ondetach () method of the first fragment is executed, At the same time Containerview will detach the first fragment view.

The Add () method executes the life cycle of Onattach ()-onresume (), and the relative remove () is the remaining onpause ()-ondetach () cycle of execution completion.

You can get an instance of fragmenttransaction from the activity as follows:

FragmentManager fragmentManager = getFragmentManager() FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

You can add fragment with the Add () function and specify the fragment to add and the view to which you want to insert it (note the commit TRANSACTION):

ExampleFragment fragment = new ExampleFragment();    fragmentTransaction.add(R.id.fragment_container, fragment);    fragmentTransaction.commit();
3.3 Add fragment with no interface

You can also use fragment to provide background action for activity without rendering redundant user interfaces.

To add a Fragment without an interface, you can use Add (Fragment, String) (provides a unique string "tag" for Fragment instead of a view ID). This adds fragment, but the call to Oncreateview () is not received because there is no view associated to the activity layout. So there is no need to implement this method.
  
For no interface fragment, the string label is the only way to identify it. If you want to take fragment from the activity later, you need to use Findfragmentbytag ().

4.fragment Transaction Background Stack

Before calling commit (), you can add a transaction to the fragment transaction background stack (by calling ADDTOBACKSTATCK ()). This background stack is managed by the activity and allows the user to fall back to the previous fragment state by pressing the backward key.

One fragment in the following code replaces the other fragment and retains the previous fragment state in the background stack:

 Fragment newFragment = new ExampleFragment(); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.fragment_container, newFragment); transaction.addToBackStack(null); transaction.commit();

Attention:

If you add more than one change transaction (for example, another add () or remove ()) and call Addtobackstack (), then any changes to the app before calling commit () are added to the background stack as a separate transaction, and the back key can roll them out.

When a fragment is removed, if Addtobackstack () is called, then fragment is stopped, and if the user rolls back, it will be restored.

Calling commit () does not immediately execute the transaction, but instead takes an appointment, which can be run once the interface thread (main thread) of the activity is ready. However, if necessary, you can invoke Executependingtransations () from the interface thread to immediately execute the transaction committed by commit ().

Transactions can only be committed with commit () before the activity is saved (when the user leaves the activity). If you try to commit after that time, an exception will be thrown. This is because if the activity needs to be restored, the status after the commit is lost. For such lost submissions, you can use the Commitallowingstateloss ()

5. Interacting with the activity
    • The activity has a reference to the fragment that interacts directly with the reference.

      -If no reference can be obtained by calling fragment's function Findfragmentbyid () or Findfragmentbytag (), get the fragment index from Fragmentmanager, for example:

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
    • An instance of the currently bound activity can be obtained through getactivity in fragment.

    • Create an Activity event callback function that defines a callback interface within fragment that hosts the activity to implement it.

Reference:

Fragments API Guides

Fragmenttransaction Reference

[Android] Fragment Full Analysis

Related Article

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.