Explanation of the interaction between Fragment and Activity based on Android

Source: Internet
Author: User

The following section describes the relationship between Fragment and Activity. For more information, see

Today, we will continue to explain the features of the Fragment component, mainly the relationship between the interaction with the Activity and the lifecycle. We have already said that Fragment depends on the Activity and the lifecycle is also bound with the Activity. Let's take a 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 the event with the activity. A good method is to define a callback interface in fragment and require the host activity to implement it. When an activity receives a callback through the interface, it can share information with other fragment in layout if necessary. For example, if A new application has two fragment items in the activity-one for displaying the article list (framgent A) and the other for displaying the article content (fragment B) -Then framgent A must tell the activity when A list item is selected, and then it can tell fragmentB to display the article.

In this example, the OnArticleSelectedListener interface declares in fragment:

Copy codeThe Code is as follows:
Public static class FragmentA extends ListFragment
{
//...
// Container Activity must implement this interface
Public interface OnArticleSelectedListener {
Public void onArticleSelected (Uri articleUri );
}
//...
}


Then, the host activity of fragment implements the OnArticleSelectedListener interface and overwrites onArticleSelected () to notify fragment B of the events that come from fragment. To ensure that the host activity implements this interface, the onAttach () callback method of fragment A (called by the system when fragment is added to the activity) passes in onAttach () as A parameter () to instantiate an OnArticleSelectedListener instance.

Copy codeThe Code is 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 will throw a ClassCastException. Under normal circumstances, the mListener member will keep A reference to the OnArticleSelectedListener implementation of the activity. Therefore, fragment A can share an event to the activity by calling the method defined in the OnArticleSelectedListener interface. For example, if fragment A is A subclass of ListFragment, each time you click A list item, the system calls onListItemClick () in fragment, and the latter calls onArticleSelected () to assign events to the activity.

Copy codeThe Code is 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 row ID of the item to be clicked, and activity (or other fragment) is used to obtain the article from the application's ContentProvider.

2. Add a project to ActionBar
Your fragment can provide the option menu for the activity by implementing onCreateOptionMenu () (similarly, the Action Bar ). To enable this method to receive calls, you must call setHasOptionsMenu () during onCreate () to indicate that fragment is willing to add items to the option menu (otherwise, fragment will not receive calls to onCreateOptionsMenu ).

Any items added from fragment to the Option menu will be appended to the end of the existing menu item. When a menu item is selected, fragment also receives a callback to onOptionsItemSelected. You can also register a view in your fragment layout by calling registerForContextMenu () to provide an environment menu. When you open the environment menu, fragment receives a call to onCreateContextMenu (). When you select a project, fragment receives a call to onContextItemSelected.

Note: although your fragment receives the callback after each menu item added to it is selected, the activity receives the corresponding callback first when you select a menu item. For example, if the on-item-selected callback function of the activity does not process the selected project, the event will be passed to the fragment callback.

This rule applies to option menus and environment menus.

3. process the lifecycle of fragment
Managing the lifecycle of fragment is similar to managing the lifecycle of an activity in most cases. Like an activity, fragment can be in three states:
Resumed
Fragment is visible in the running activity.
Paused
The other activity is in the foreground and has focus, but the activity where the fragment is located 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 fragment has been removed from the activity but added to the background stack.
The fragment in the stopped state is still alive (all States and member information are kept by the system ). However, it is invisible to users and will be killed if the activity is killed.
The corresponding relationship diagram is as follows:

Like activity, you can use Bundle to maintain the fragment state. In case the activity process is killed and the activity is re-created, you can use it to restore the fragment state. you can save the status during the onSaveInstanceState () of fragment and restore it during onCreate (), onCreateView (), or onActivityCreated.

The most important difference between activity and fragment in life cycle is how they are stored in their backend stacks. By default, an activity is placed in a background stack managed by the system to save the activity after it is stopped. (You can use the BACK button to navigate BACK to it ).

However, only when you remove fragment during a transaction and explicitly call addToBackStack () to save the instance is put into a background stack managed by the host activity.

In addition, the lifecycle of fragment management is very similar to that of activity management. Therefore, the same practices in "managing the activitylifecycle" also apply to fragment. You need to understand how the life of an activity affects the life of fragment.

4. Coordination with activity Lifecycle
The lifecycle of the activity that fragment lives on directly affects the lifecycle of fragment. The callback behavior of each activity's lifecycle will cause a similar callback in each fragment.

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

Fragment has some additional lifecycle callback methods that process the unique interaction with the activity to execute the UI action such as creating and destroying fragment. These additional callback methods are:

• OnAttach ()
It is called when fragment is bound to activity (Activity will be passed in)
• OnCreateView ()
Call when creating view hierarchy associated with fragment
• OnActivityCreated ()
Called when the onCreate () method of activity returns
• OnDestroyView ()
Called when the view hierarchy associated with fragment is being removed
• OnDetach ()
Called when fragment disassociates from activity
The fragment Lifecycle Process and the impact of the host activity on it are shown in figure 3. In this figure, we can see how each status of the activity determines how the fragment can receive the callback method. For example, when an activity receives its onCreate (), fragment in the activity receives onActivityCreated () at most ().
Once the activity reaches the resumed state, you can freely add and remove fragment in the activity. Therefore, the lifecycle of fragment can be changed independently only when the activity is in the resumed state.
In any case, when the activity leaves the resumed status, the fragment is pushed into its own Lifecycle Process by the activity again.

5. Summary
Fragment-related knowledge is here for the time being. Demo examples can be used to directly view the program in APIDEMO. If you do not know where the API Demo is, please Baidu! To learn programming, you need to learn 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.