Fragment Advantages of Android

Source: Internet
Author: User

What is Fragment

Since Android 3.0 introduced the concept of fragments, according to the translation of the word Sea can be translated as: fragments, fragments. Its purpose is to solve the dynamic and flexible UI set -up for different screen resolution. A large screen such as a flat screen, such as a mobile phone, is designed so that it has more room to put more UI components, and the extra space to store the UI makes it more interactive, resulting in fragments.

Fragments's design does not require you to personally manage the complex changes in view hierarchy by dispersing the activity's layout into frament, which can modify the appearance of the activity at run time, and the back stack managed by the activity Save some of the changes. When a fragment specifies its own layout, it can be configured in a different combination with the other clips, modifying the layout configuration for different screen sizes in the activity (the small screen may show one clip at a time, while a large screen can show two or more).

Fragment must be written into reusable modules. Because fragment has its own layout, responds to events, has its own life cycle and behavior, you can include different instances of the same fragment in multiple activities. This is especially important for making your interface a perfect experience for users with different screen sizes.

Fragment Advantages

Fragment enables you to separate activity into multiple reusable components, each with its own lifecycle and UI.

Fragment can easily create dynamic and flexible UI designs that can be adapted to different screen sizes. From your phone to your tablet.

Fragment is a standalone module that is tightly bound to the activity. Can be dynamically removed, joined, exchanged, etc. in the run.

Fragment provides a new way for you to unify your UI on different Android devices.

Fragment to solve the switch between the activity is not smooth, light-weight switch.

Fragment Alternative tabactivity Do the navigation, better performance.

Fragment added nested Fragment usage in version 4.2 to produce better interface effects.

Fragment do local content update more convenient, originally in order to reach this point to put a number of layouts into an activity inside, now can use more fragment to replace, only when needed to load fragment, improve performance.

The return result can be received from the Startactivityforresult, but view cannot.

Fragment The life cycle

You can think of fragment as a modular component of activity that has its own life cycle

A fragment is a part or a behavior in the interface of an activity. You can combine multiple fragment into one activity to create a faceted interface and you can reuse a fragment in multiple activity. You can think of fragment as a modular activity that has its own life cycle, receives its own events, and can be added or deleted while the activity is running.

Fragment cannot exist independently, it must be embedded in the activity, and the life cycle of fragment is directly affected by the activity in which it resides. For example, when activity is paused, all the fragment that it owns are paused, and when the activity is destroyed, all of its fragment are destroyed. However, when the activity is running (before Onresume (), OnPause (), you can manipulate each fragment individually, such as adding or removing them. When you perform the above transaction for fragment, you can add a transaction to a stay, the stack is managed by the activity, and each of the stacks is a fragment transaction. With this stack, the fragment transaction can be executed in reverse, so that the return key (navigating backwards) can be supported at the fragment level.

The core life cycle method to invoke when displaying fragment (interacting with the user) is as follows:

1. Call the Onattach (activity) method when associating the fragment object with the activity;

2. When the fragment object is initially created, call the OnCreate (Bundle) method;

3. Oncreateview (Layoutinflater, ViewGroup, Bundle) method is used to create and return the view object associated with the fragment;

4. The Onactivitycreate (Bundle) method tells the fragment object that the activity object it is attached to has completed the execution of the Activity.oncreate () method;

5. The OnStart () method causes the Fragment object to be displayed to the user (after the activity that contains the fragment object is started);

6. Onresume () causes the fragment object to interact with the user (after the activity that contains the fragment object is restarted).

The method to reverse the callback when the fragment object is no longer in use:

1. Because the activity object that the fragment object is attached to is suspended, or if an action is being performed in the activity that modifies the fragment object, causing the fragment object to no longer interact with the user, The system invokes the OnPause () method of the Fragment object;

2. The system invokes the onstop of the fragment object because the activity object that the fragment object is attached to is terminated, or if an operation that modifies the fragment object is being performed in the activity, causing the fragment object to no longer be displayed to the user. () method.

3. The Ondestroyview () method is used to clear the resources associated with the view object in the fragment;

4. After the state of the fragment object is finally cleared, the OnDestroy () method is called;

5. The Ondetach () method is immediately called when the fragment object is no longer associated with the activity it is attached to

is the correspondence between the life cycle of fragment and activity :

As you can see from this diagram, the state of the activity determines the callback function that fragment may receive .

For example, when the activity receives its oncreate () callback function, the activity's fragment receives a maximum of onactivitycreated ().

When activity is in the resumed state, it is free to add and remove fragment, that is, the state of fragment can be changed independently only when the activity is in the resumed state.

However, when activity leaves the resumed state, the fragment life cycle is controlled by the activity.

Information interaction between fragment

(1) Acquisition of objects

  /* * Click on the Fragment button to set the button's text to the text value of EditText in another fragment  *  /public View Oncreateview ( Layoutinflater inflater, ViewGroup container,          Bundle savedinstancestate) {      View view = Inflater.inflate ( R.layout.list, null);      Final button button = (button) View.findviewbyid (r.id.confirm);      Button.setonclicklistener (New View.onclicklistener () {                    @Override public          void OnClick (View v) {              // Find the EditText object in another fragment by Fragmentmanager and get the text content                           button.settext (Edittext.gettext (). ToString ());          }      );      return view;  }

(2) through the callback function

public class Mainactivity extends Activity {private Fragmentmanager manager;        Private button button;          @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                    Setcontentview (R.layout.activity_main);                  Button.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {                  Rightfragment Rightfrag = (rightfragment) (Getfragmentmanager (). Findfragmentbytag ("right"));                  /* * Pass an instantiated object to it through the set method, and pass the parameter because the Rightfrag.set () method executes the RightFragment.CallBack.get () method internally.                      */Rightfrag.set (new Rightfragment.callback () {@Override                      public void get (String str) {button.settext (str);              }                  });      }          }); }    }  

  

public class Rightfragment extends Listfragment {      private loadermanager Manager;        @Override public      void OnCreate (Bundle savedinstancestate) {          super.oncreate (savedinstancestate);          Manager = Getloadermanager ();      }      /* * Click on the Fragment button to set the button's text to the text value of EditText in another fragment      *      /public View Oncreateview ( Layoutinflater inflater, ViewGroup container,              Bundle savedinstancestate) {          View view = Inflater.inflate ( R.layout.list, null);          return view;      }        /**      * Receives a return function object by calling the method, Callback.get (str);      * @param callBack */public      void set (CallBack callBack) {          EditText EditText = (EditText) GetView (). Findviewbyid (r.id.name);          Callback.get (Edittext.gettext (). toString ());      }      /* * Back interface      *      /interface CallBack {public          void get (String str);}  }

  

Fragment interacting with activity information: Creating event Callbacks

An instance of fragment is always directly related to the activity that contains it.

Fragment can use getActivity() methods to get an instance of the activity, and then you can invoke methods such as Findviewbyid ().

Such as:

View ListView = getactivity (). Findviewbyid (r.id.list);

  However, when calling Getactivity (), the fragment must be associated with the activity (attached to an activity), otherwise a null will be returned.

Similarly, the activity can also obtain a fragment reference to invoke the method in fragment.

The reference to get fragment is used Fragmentmanager, which can then be called findFragmentById() or findFragmentByTag() .

Like what:

Examplefragment fragment = (examplefragment) Getfragmentmanager (). Findfragmentbyid (r.id.example_fragment);

  In some cases, it may be necessary to fragment and activity sharing events, a good practice is to define a callback interface in fragment, and then ask the host activity to implement it.

When activity receives a callback through this interface, it can share this information with other fragment in the layout.

For example, a news display app has two fragment in an activity, a fragment a displays a list of the title of the article, and a fragment B displays the article.

So when an article is selected, fragment a must notify the activity and then activity informs fragment B to show the article.

In this case, declare an interface such as Onarticleselectedlistener in fragment A:

public static class Fragmenta extends Listfragment {    ...    Container Activity must implement this interface public    interface Onarticleselectedlistener {public        void Onar ticleselected (Uri Articleuri);    }    ...}

This Onarticleselectedlistener interface is then included with the fragment activity, and the Overwrite onarticleselected () method notifies fragment B of what happened in fragment a.

In order to ensure that the host activity implements this interface, the method of fragment A, which is onAttach() called by the system when fragment is added to the activity, is converted by the input activity coercion type. Instantiate a Onarticleselectedlistener object:

public static class Fragmenta extends Listfragment {    Onarticleselectedlistener mlistener;    ...    @Override public    void Onattach (activity activity) {        Super.onattach (activity);        try {            Mlistener = (onarticleselectedlistener) activity;        } catch (ClassCastException e) {            throw new ClassCastException (activity.tostring () + "must implement Onarticleselectedlistener");        }    }    ...}

If the activity does not implement this interface, fragment will throw an classcastexception exception, and if it succeeds, Mlistener will be a reference to the activity implementation of the Onarticleselectedlistener interface, so by calling the Onarticleselectedlistener interface method, fragment A can share events with the activity.

For example, if fragment A is a subclass of listfragment , each time a user clicks on a list item, the system calls the method in fragment onListItemClick() , and in this method the onarticleselected () can be called. method to share events with activity.

public static class Fragmenta extends Listfragment {    Onarticleselectedlistener mlistener;    ...    @Override public    void Onlistitemclick (ListView l, View v, int position, long ID) {        //Append The clicked item ' s RO W ID with the content provider uri        uri Noteuri = Contenturis.withappendedid (Articlecolumns.content_uri, ID);        Send the event and Uri to the host activity        mlistener.onarticleselected (Noteuri);    }    ...}

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.