The fragment of Android Foundation and activity Interactive detailed _android

Source: Internet
Author: User
Tags static class

Today we continue to explain the characteristics of the fragment component, primarily with the interaction of the activity and the lifecycle, as we have said earlier that fragment is dependent on activity and that the lifecycle is bound to the activity. Let's look at the relationship between fragment and activity.

1. Create an event callback method for the activity
In some cases, you may need a fragment to share events with the activity. A good approach is to define a callback interface in fragment and require the host activity to implement it. When an activity receives a callback via interface, it can share information with other fragment in the layout if necessary. For example, if a new application has 2 fragment– in the activity one is used to display a list of articles (Framgent a), another displays the article content (fragment B) – then framgent a must tell the activity when a list ite M is selected, and then it can tell FRAGMENTB to show the article.

In this example, the Onarticleselectedlistener interface is declared in fragment a:

Copy Code code as follows:

public static class Fragmenta extends Listfragment
{
//...
Container activity must implement this interface
Public interface Onarticleselectedlistener {
public void onarticleselected (Uri articleuri);
}
//...
}

The fragment host activity then implements the Onarticleselectedlistener interface, and the onarticleselected () is overridden to notify fragment B of events coming from fragment A. To ensure that the host activity implements this interface, fragment A's Onattach () callback method (called by the system when adding fragment to the activity) is passed as a parameter to the Onattach () Activity does a type conversion to instantiate a Onarticleselectedlistener instance.
Copy Code code as follows:

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 Implementonarticleselectedlistener");
}
}
//...
}

If the activity does not implement an interface, fragment throws a ClassCastException exception. Under normal circumstances, Mlistener members maintain a reference to the Onarticleselectedlistener implementation of the activity, so fragment A can share events to the activity by calling methods defined in the Onarticleselectedlistener interface. For example, if fragment A is a listfragment subclass, each time a user clicks on a list item, the system calls Onlistitemclick in fragment (), and then the latter invokes onarticleselected () To assign events to an activity.
Copy Code code as follows:

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 row 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);
//...
}

The ID parameter passed to Onlistitemclick () is the line id,activity (or other fragment) of the item being clicked to get the article from the applied ContentProvider.

2. Add Items to Actionbar
Your fragment can be implemented Oncreateoptionmenu () to provide menu items to the activity of the option menus (and so on, Action bar is the same). In order for this method to receive calls, at any rate, you must call Sethasoptionsmenu () during onCreate () to indicate that fragment is willing to add item to the option menu (otherwise, fragment will receive no Call to Oncreateoptionsmenu ()).

Any items that are then added to the option menu from fragment are appended to the list of existing menu items. When a menu item is selected, fragment also receives a callback to onoptionsitemselected (). You can also provide an environment menu by calling Registerforcontextmenu () to register a view in your fragment layout. When the user opens the Environment menu, fragment receives a call to Oncreatecontextmenu (). When the user selects an item, fragment receives a call to Oncontextitemselected ().

Note: Although your fragment will receive a callback that is selected for each menu item that it adds, the activity will first receive the corresponding callback when the user selects a menu item. If the on-item-selected callback function implementation of the activity does not process the selected item, then the event is passed to the fragment callback.

This rule applies to the options menu and the Environment menu.

3, the processing of fragment life cycle
Managing the fragment lifecycle is much like managing the activity lifecycle. As with activity, fragment can be in 3 different states:
resumed
Fragment visible in a running activity.
paused
Another activity is in the foreground and has focus, but the activity of the fragment is still visible (the foreground activity is partially transparent or does not cover the entire screen).
Stopped
Either the host activity has been stopped, or the fragment is removed from the activity but added to the background stack.
The fragment of the stop State is still alive (all state and member information is maintained by the system). However, it is no longer visible to the user and will be killed if the activity is killed.
The corresponding diagram is as follows:

As with activity, you can use bundle to keep fragment in the event that the activity process is eliminated and you need to restore the fragment state when the activity is recreated. You can save the state during the Onsaveinstancestate () of the fragment and restore it during onCreate (), Oncreateview (), or onactivitycreated ().

The most important difference between activity and fragment in the lifecycle is how each is stored in its background stack. By default, when an activity stops, it is placed in a background stack managed by the system to hold the activity. (So the user can navigate back to it by using the return key).

However, only if you remove fragment during a transaction, an explicit call to the Addtobackstack () request to save the instance is placed in a background stack managed by the host activity.

In addition, managing the fragment lifecycle and managing the activity lifecycle is very similar. Therefore, the same practice in the "Managing the Activitylifecycle" applies to fragment as well. What you need to understand is how the activity's life affects fragment's life.

4. Coordination with activity life cycle
The life cycle of the activity that fragment survives directly affects the life cycle of the fragment, and the callback behavior of each activity's lifecycle causes a similar callback in every fragment.

For example, when an activity receives onpause (), every fragment in the activity receives OnPause ().

Fragment has some additional lifecycle callback methods that handle the only interaction with the activity, in order to perform actions such as creating and destroying the Fragment UI. These additional callback methods are:

Onattach ()
Called when fragment is bound to an activity (the activity is passed in)
Oncreateview ()
Called when the view hierarchy associated with the fragment is created
onactivitycreated ()
Called when the OnCreate () method of the activity returns
Ondestroyview ()
Called when the view hierarchy associated with fragment is being removed
Ondetach ()
Called when fragment is disassociate from an activity
The fragment lifecycle process, and the impact of host activity on it, is shown in Figure 3. In this diagram, you can see how each state of the activity in turn determines the callback method that fragment may receive. For example, when an activity receives its oncreate (), the fragment in the activity receives up to onactivitycreated ().
Once the activity reaches the resumed state, you are free to add and remove fragment from the activity. Therefore, the life cycle of fragment can be changed independently only when the activity is in resumed state.
In any case, when the activity leaves the resumed state, fragment is again pushed by the activity into its own lifecycle process.

5, summary
Fragment related knowledge temporarily here, example demo can directly look at the Apidemo inside the program, if you do not know where the API demo, please Baidu! Learning to program requires learning to find the answer.

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.