Fragment and activity (transfer)

Source: Internet
Author: User
Interaction between Android fragment and activityfragment and activity Fragment

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

Fragment can be passed throughgetActivity()Then you can call methods such as findviewbyid.

For example:

View listview =Getactivity ().Findviewbyid(R. Id. List );

  Note that when getactivity () is called, fragment must be associated with the activity (attached to an activity); otherwise, a null value is returned.

 

Similarly, an activity can obtain a reference to fragment and call the method in fragment.

To get the reference of fragment, useFragmentmanagerCan be called laterfindFragmentById()OrfindFragmentByTag().

For example:

Examplefragment fragment = (examplefragment) getfragmentmanager (). findfragmentbyid (R. Id. example_fragment );

Create Event Callback

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

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

For example, a news display application has two fragment items in an activity, one fragment A shows the list of Article topics, and the other fragment B shows the article.

Therefore, when an article is selected, fragment A must notify activity, and then activity notifies fragment B to display this article.

In this case, define an onarticleselectedlistener interface in fragment:

public static class FragmentA extends ListFragment {    ...    // Container Activity must implement this interface    public interface OnArticleSelectedListener {        public void onArticleSelected(Uri articleUri);    }    ...}

 

The activity that contains this fragment then implements the onarticleselectedlistener interface and notifies fragment B of what happened in fragment A using the override onarticleselected () method.

To ensure that the host activity implements this interface, fragment A'sonAttach()(This method is called by the system when fragment is added to the activity) by forcibly converting the input activity type and instantiating an 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 throwClasscastexceptionIf the call succeeds, mlistener is a reference to the onarticleselectedlistener interface implemented by activity. Therefore, fragment A can share the event with activity by calling the onarticleselectedlistener interface.

For example, if fragment A isListfragmentSub-class. Each time a user clicks a list item, the system callsonListItemClick()In this method, you can call the onarticleselected () method to share the event with the 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 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);    }    ...}

 

 

Process fragment Lifecycle

Three stay statuses

The lifecycle of fragment management is similar to that of activity management. Like activity, fragment can stay in three states:

Resumed

Fragment is visible in the running activity.

Paused

The other activity runs in the foreground and has focus, but the activity where the fragment is located is still visible (the foreground activity is partially blocked or translucent ).

Stopped

Fragment is invisible. It may be because the host activity is in the stopped status, or the fragment is removed and added to the back stack.

An activity in the stopped status is still alive, and all the status and member information will be kept by the system. However, it is no longer visible to users, and if the host activity is killed, it will also be killed.

 

Oncreate (),onCreateView(), OronActivityCreated().

 

Back Stack

The most important difference between activity and fragment lifecycle is how they are stored in their respective back stacks.

When an activity is stopped, it is stored in a back stack maintained by the system. However, when the fragment is stopped (removed), the programmer must call it explicitly.addToBackStack()And fragment exists in a back stack managed by the host activity.

Fragment and activity Lifecycle

 

The declared period of the host activity directly affects the lifecycle of the fragment. For example, when the callback function of the activity life cycle is called, all the same callback functions in the fragment will be called at the same time.

 

Fragment also has some additional lifecycle callback functions:

 

Onattach ()

 

Called when fragment and activity are associated.

 

Oncreateview ()

 

It is called when the UI for creating fragment is initialized.

 

Onactivitycreated ()

 

Called when the oncreate () method of the activity returns.

 

Ondestroyview ()

 

Called when the fragment UI is removed.

 

Ondetach ()

 

Called when fragment is associated with activity.

 

 

We can see from this figure thatThe activity status determines the callback function that fragment may receive..

For example, if the activity receives its oncreate () callback function, the fragment in the activity receives the onactivitycreated () at most ().

When the activity is in the resumed state, fragment can be freely added and removed, that is, the fragment state can be changed independently only when the activity is in the resumed state.

However, when the activity leaves the resumed status, the lifecycle of fragment is controlled by the activity.

 

 

References

API guides: Fragments

Http://developer.android.com/guide/components/fragments.html

 

Fragment and activity (transfer)

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.