Android Fragment-detailed explanation

Source: Internet
Author: User


1. Fragment Overview

In an Activity, Fragment represents a part or action of the UI. An Activity can combine multiple Fragment objects or use different objects corresponding to the same Fragment bytecode in multiple activities. A Fragment object must be embedded in a main Activity object. The lifecycle of this Fragment is closely related to the main Activity. For example, when the main Activity is in the paused state, all its corresponding Fragment objects are in the paused state. Fragment can be freely controlled only when the main Activity is in the resumed state.

2. Create Fragment

To create a Fragment, you should inherit Fragment or its subclass and overwrite the corresponding method. For example, onCreate (), OnCreateView (), onPause (), etc.

Instantiate a Fragment object. In addition to the new object, you can also use the Fragment static function Fragment. instantiate (mContext, "full class path", info. args);, implemented using reflection, but with low performance

(1). Add the UI

To display a layout for the Fragment, you must implement the onCreateView () method.
Note:: When the Fragment inherits the ListFragment,The onCreateView () method does not need to be overwritten.Because a ListView object is returned by default.

[Java]View plaincopy
  1. Public View onCreateView (LayoutInflater inflater, ViewGroup container,
  2. Bundle savedInstanceState ){
  3. View view = inflater. inflate (R. layout. list, null );
  4. Return view;
  5. }
(2) Add Fragment to Activity
1) layout the file through layout

Android: The name attribute should be the full path of the corresponding class of Fragment.

[Html]View plaincopy
  1. Android: id = "@ + id/f"
  2. Android: layout_width = "wrap_content"
  3. Android: layout_height = "wrap_content"
  4. Android: name = "com. example. a29fragment. MyFragment"/>Static RegistrationMyFragment is compatible with support. v4.app. Fragment, so no Activity can be used.FragmentActivity

    FragmentStaticConfigure the fragment in the xml fileCannot be removedAnd cannot be edited dynamically.

    [Html]View plaincopy
    1. Android: layout_width = "match_parent"
    2. Android: layout_height = "match_parent"
    3. Android: orientation = "horizontal">
    4. Android: id = "@ + id/list"
    5. Android: name = "com. example. news. ArticleListFragment"
    6. Android: layout_width = "0dp"
    7. Android: layout_height = "match_parent"
    8. Android: layout_weight = "1"/>
    9. Android: id = "@ + id/viewer"
    10. Android: name = "com. example. news. ArticleReaderFragment"
    11. Android: layout_width = "0dp"
    12. Android: layout_height = "match_parent"
    13. Android: layout_weight = "2"/>
2). Use Java code

When the Activity is running, you can freely add fragment objects to the activity. However, you should specify a ViewGroup container, which can be added, removed, or replaced by FragmentTransaction.

[Java]View plaincopy
  1. Manager = getFragmentManager ();
  2. If (manager. findFragmentByTag ("right") = null ){
  3. Manager. beginTransaction (). replace (R. id. right, new RightFrag (), "right"). commit ();
  4. }
(3). fragment Unique Identifier

Each fragment must define a unique identifier. if the activity is destroyed and restarted, the system can restore the fragment state. If you want to restore the data, you need to meet one of the following three methods:

1). Define ID

Define the android: id attribute in the layout File

[Html]View plaincopy
  1. Android: id = "@ + id/list"
  2. Android: name = "com. example. news. ArticleListFragment"
  3. Android: layout_width = "0dp"
  4. Android: layout_height = "match_parent"
  5. Android: layout_weight = "1"/>
2). Specify the tag

Android: tag indicates that the tag is specified when a fragment object is added () or replace ().

[Html]View plaincopy
  1. Android: id = "@ + id/list"
  2. Android: tag = "first"
  3. Android: name = "com. example. news. ArticleListFragment"
  4. Android: layout_width = "0dp"
  5. Android: layout_height = "match_parent"
  6. Android: layout_weight = "1"/>

    Or

    [Java]View plaincopy
    1. Manager. beginTransaction ()
    2. . Replace (R. id. right, new RightFrag (), "right") // specify the fragment tag in the transaction
    3. . Commit ();
3). viewgroup ID

If no id or tag exists for this fragment, the container view is used.Layout id

3. Fragment Management

You can get the FragmentManager object through the getFragmentManager () method, mainly to complete the following functions

[Java]View plaincopy
  1. FragmentManager manager = getFragmentManager (); (1). Get the existing Fragment object.

    If the fragment specifies the id in the layout file, the object is obtained through findFragmentById (), or the object can be obtained through findFragmentByTag () if the tag is specified

    [Java]View plaincopy
    1. Fragment fragment = getFragmentManager (). findFragmentByTag ("right ");
    2. // Or
    3. Fragment fragment = getFragmentManager (). findFragmentById (id );
    (2) register the OnBackStackChangedListener listener.

    The onBackStackChanged () method can be used to listen to the stack information returned for this task. When the returned stack status changes, the onBackStackChanged () method is executed.

    [Java]View plaincopy
    1. Manager. addOnBackStackChangedListener (new FragmentManager. OnBackStackChangedListener (){
    2. @ Override
    3. Public void onBackStackChanged (){
    4. Toast. makeText (MainActivity. this, "heap status changed", 1). show ();
    5. }
    6. });
    (3). the returned stack is displayed.

    Click the return key to bring up the specified fragment from the return stack. This operation is asynchronous. The premise is that the fragment object is added to the return stack using. beginTransaction (). addToBackStack ("right ").

    [Java]View plaincopy
    1. Manager. popBackStack (); // Pop the top state off the back stack
    (4). FragmentTransaction transaction

    A transaction mainly contains a set of operations, such as adding remove replacement,Animation settingsAnd so on.

    [Html]View plaincopy
    1. /*
    2. * Start a transaction through manager. The transaction contains a set of operations. You can add (), remove (), replace () for the transaction ()
    3. * Complete the Fragment operation and use commit () to submit
    4. */
    5. FragmentTransaction transaction = manager. beginTransaction ();
    6. Transaction. replace (R. id. right, new RightFrag (), "right ");
    7. Transaction. setTransition (FragmentTransaction. TRANSIT_FRAGMENT_OPEN); // sets the animation
    8. Transaction. addToBackStack ("right"); // Add the fragment to the returned heap
    9. // Submit the transaction
    10. Transaction. commit ();
    (5) Fragment Status Management
    [Java]View plaincopy
    1. /*
    2. * Fragment Management Status
    3. * If you add a fragment to a master activityViewGroup,
    4. * If the mobile phone screen is rotated, the current activity is destroyed and rebuilt, and fragment is also created by activityManager.
    5. * In onCreate, You need to determine
    6. */
    7. @ Override
    8. Protected void onCreate (Bundle savedInstanceState ){
    9. Super. onCreate (savedInstanceState );
    10. SetContentView (R. layout. activity_main );
    11. Manager = getFragmentManager ();
    12. If (manager. findFragmentByTag ("right") = null ){
    13. // If (savedInstanceState = null), you can also determine whether the fragment has been loaded.
    14. Manager. beginTransaction ()
    15. . Replace (R. id. right, new RightFrag (), "right ")
    16. . SetTransition (FragmentTransaction. TRANSIT_FRAGMENT_OPEN) // sets the animation
    17. . AddToBackStack ("right") // Add the fragment to the returned heap
    18. // Submit the transaction
    19. . Commit ();
    20. }
    21. }
4. Backward compatibility
See compatibility of CursorLoader ~~, Note: If you use Static Registration, In the layout file configuration Because the class with the name specified is compatible with support. v4.app. Fragment, the Class that loads the layout file cannot inherit the Activity and can only inherit FragmentActivity
5. Fragment information interaction
(1). Get object
[Java]View plaincopy
  1. /*
  2. * Click the button of the Fragment to set the text of the button to the text value of Edittext in another fragment.
  3. */
  4. Public View onCreateView (LayoutInflater inflater, ViewGroup container,
  5. Bundle savedInstanceState ){
  6. View view = inflater. inflate (R. layout. list, null );
  7. Final Button button = (Button) view. findViewById (R. id. confirm );
  8. Button. setOnClickListener (new View. OnClickListener (){
  9. @ Override
  10. Public void onClick (View v ){
  11. // Use FragmentManager to find the edittext object in another fragment and obtain the text content.
  12. EditText editText = (EditText) (getFragmentManager (). findFragmentByTag ("left"). getView (). findViewById (R. id. name ));
  13. Button. setText (editText. getText (). toString ());
  14. }
  15. });
  16. Return view;
  17. }
(2). Call back the Function
[Java]View plaincopy
  1. Public class MainActivity extends Activity {
  2. Private FragmentManager manager;
  3. Private Button button;
  4. @ Override
  5. Protected void onCreate (Bundle savedInstanceState ){
  6. Super. onCreate (savedInstanceState );
  7. SetContentView (R. layout. activity_main );
  8. Button. setOnClickListener (new View. OnClickListener (){
  9. @ Override
  10. Public void onClick (View v ){
  11. RightFragment rightFrag = (RightFragment) (getFragmentManager (). findFragmentByTag ("right "));
  12. /*
  13. * The set method is used to pass an instantiated object to it. Because the rightFrag. set () method internally executes the RightFragment. CallBack. get () method, the parameter is passed.
  14. */
  15. RightFrag. set (new RightFragment. CallBack (){
  16. @ Override
  17. Public void get (String str ){
  18. Button. setText (str );
  19. }
  20. });
  21. }
  22. });
  23. }
  24. }[Java]View plaincopy
    1. Public class RightFragment extends ListFragment {
    2. Private LoaderManager;
    3. @ Override
    4. Public void onCreate (Bundle savedInstanceState ){
    5. Super. onCreate (savedInstanceState );
    6. Manager = getLoaderManager ();
    7. }
    8. /*
    9. * Click the button of the Fragment to set the text of the button to the text value of Edittext in another fragment.
    10. */
    11. Public View onCreateView (LayoutInflater inflater, ViewGroup container,
    12. Bundle savedInstanceState ){
    13. View view = inflater. inflate (R. layout. list, null );
    14. Return view;
    15. }
    16. /**
    17. * Call this method to receive a callBack function object, callBack. get (str );
    18. * @ Param callBack
    19. */
    20. Public void set (CallBack callBack ){
    21. EditText editText = (EditText) getView (). findViewById (R. id. name );
    22. CallBack. get (editText. getText (). toString ());
    23. }
    24. /*
    25. * Return the interface
    26. */
    27. Interface CallBack {
    28. Public void get (String str );
    29. }
    30. }
6. Fragment Lifecycle
(1). lifecycle Roadmap

Life status

Periodic Process

Foreground lifetime

OnResume ()

OnResume (F)

OnPause (F)

OnPause ()

Visible lifetime

OnCreateView (F)

OnActivityCreated (F)

OnStart ()

OnStart (F)

OnResume ()

OnResume (F)

OnPause (F)

OnPause ()

OnStop (F)

OnStop ()

OnDestroyView (F)

Entire lifetime

Complete lifecycle

(2) Overview of lifecycle loose Functions

Method Description
OnAttach (Activity)

The current Fragment is associated with the Activity. It is called!

OnCreate ()

Complete fragment initialization and Creation

OnCreateView ()

Create and return the hierarchical view associated with the current fragment

OnActivityCreated ()

This method is executed only after onCreate () of the main activity is executed.

OnStart ()

Fragment is visible when the main activity is inRun after the started status

OnResume ()

Fragment can interact with users. When the main activity is inRun after the resumed status

OnPause ()

Fragment does not interact with users, and may be in the main activityToInRun the command before paused., Possibly thisFragment modified

OnStop ()

Fragment is not visible and may be in the main activityToInRun before stopped, Possibly thisFragment modified

OnDestroyView ()

Allows this fragment to clear view-related resources

OnDestroy ()

Clear view state Information

OnDetach ()

This fragment is not associated with the activity.


This blog post is original from zimo. For more information, see the source! Http://blog.csdn.net/zimo2013/article/details/12239349

Experience solves the problem that Fragment is still visible after it is replaced

Most of the questions asked on the Internet will mention replacing Fragment and find that the ones previously replaced are still shown there. I personally use the android 2.3 + support development kit, and a similar problem occurs on the 2.3 system. I searched for any online problems and found no solution. Then, find your own solutions. Finally, I found that the replacement of the JAVA code for Fragment is basically nothing, and it is correct on the Internet, for example:

  1. FragmentManager fragmentManager = getSupportFragmentManager ();
  2. FragmentTransaction transaction = fragmentManager. beginTransaction ();
  3. OrderFragment orderFragment = new OrderFragment ();
  4. Bundle args = new Bundle ();
  5. Args. putInt ("card_id", LoginHelper. currentCard. getId ());
  6. Args. putBoolean ("create_order", true );
  7. OrderFragment. setArguments (args );


  8. Transaction. replace (R. id. layout_shopping1, orderFragment );
  9. // Transaction. addToBackStack (null );
  10. Transaction. commit (); copy the Code but most people do not realize the importance of sticking the XML layout file:
    The correct method is to use FrameLayout as the layout container replaced by Fragment.
    For example:

    1. <FrameLayout xmlns: android = "http://schemas.android.com/apk/res/android" Android: id = "@ + id/layout_shopping1"
    2. Android: layout_width = "match_parent"
    3. Android: layout_height = "wrap_content"
    4. Android: background = "@ color/black">

    5. </FrameLayout> the copied Code cannot be used for linear layout, such as LinearLayout. Otherwise, visible problems may occur.
      We are dedicated to providing experience and hope to help developers who encounter similar problems.






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.