Interactive Introduction to Android fragment and activity

Source: Internet
Author: User

interaction of fragment and activity

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

Fragment is able getActivity() to obtain an instance of activity by means of a method. You can then invoke some methods such as Findviewbyid ().

Such as:

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

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

Similarly, activity can also obtain a fragment reference. The method in fragment is called.

Get a reference to fragment with Fragmentmanager. Can then be invoked findFragmentById() or findFragmentByTag() .

Example:

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

Create an event callback

  In some cases, it may be necessary to fragment and activity sharing events, a good practice is to define a callback interface in fragment. The host activity is then required 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 one of these interface Onarticleselectedlistener in fragment a:

 Public Static classFragmentaextendslistfragment {...//Container Activity must implement this interface     Public InterfaceOnarticleselectedlistener { Public voidonarticleselected (Uri Articleuri); }    ...}

This Onarticleselectedlistener interface is then implemented by the fragment activity. A onarticleselected () method is used to notify fragment B of what happens in fragment a.

To ensure that the host activity implements this interface. The method of fragment a onAttach() (this method is called by the system when fragment is added to the activity) by casting the incoming activity coercion type. Instantiate a Onarticleselectedlistener object:

 Public Static classFragmentaextendslistfragment {Onarticleselectedlistener mlistener; ... @Override Public voidOnattach (activity activity) {Super. Onattach (activity); Try{Mlistener=(Onarticleselectedlistener) activity; } Catch(classcastexception e) {Throw NewClassCastException (activity.tostring () + "must implement Onarticleselectedlistener"); }    }    ...}

Assume that the activity does not implement this interface. Fragment will throw a classcastexception exception, assuming it succeeds, Mlistener will be a reference to the activity implementation Onarticleselectedlistener interface. So by invoking the Onarticleselectedlistener interface method, fragment a can share events with the activity.

Example. Suppose fragment A is a subclass of listfragment , and each time a user taps a list item, the system calls the method in fragment, which in onListItemClick() this way can call onarticleselected () method to share events with activity.

 Public Static classFragmentaextendslistfragment {Onarticleselectedlistener mlistener; ... @Override Public voidOnlistitemclick (ListView L, View V,intPositionLongID) {//Append The clicked item ' s row ID with the content provider UriUri Noteuri =Contenturis.withappendedid (Articlecolumns.content_uri, id); //Send the event and Uri to the host activitymlistener.onarticleselected (Noteuri); }    ...}

handling the life cycle of fragment

Three kinds of stay states

The life cycle of management fragment is similar to the life cycle of management activity, as is the activity. Fragment can stay in three different states:

  Resumed

Fragment is visible in the activity of running.

  Paused

There is also an activity that is performed in the foreground and has the focus, but the activity of the fragment is still visible (the foreground activity is partially obscured or translucent).

  Stopped

Fragment not visible.

This may be due to the host activity being in the stopped state. Or the fragment is removed and added to the back stack.

An activity in the stopped state is still alive, and all state and member information is maintained by the system. But. It is no longer visible to users. And assuming that the host activity is killed, it will also be killed.

Data storage and Recovery

Similar to activity, the fragment state can be saved with the Bundle class object. When the activity process is killed, it is necessary to reconstruct the activity, which can be used to restore the fragment state.

The onsaveinstancestate () callback function is used for storage when it is restored, onCreate() or in onCreateView() onActivityCreated() .

Back Stack

The most important difference between the activity and the fragment life cycle is how they are stored in their back stack.

When activity stops, there is a system-maintained back stack. But when fragment stopped (removed). There is a need for the program ape to addToBackStack() be called, and the fragment is in the back stack that the host activity is in charge of.

The life cycle of fragment and activity

The declaration period of the host activity directly affects the life cycle of the fragment, for example, when the callback function call of the activity life cycle, all the same callback functions in the fragment are called at the same time.

Fragment other additional life cycle callback functions:

Onattach ()

Called when fragment and activity are associated.

Oncreateview ()

Called when the UI that created the fragment is initialized.

Onactivitycreated ()

Called when the activity's OnCreate () method returns.

Ondestroyview ()

Called when the UI of fragment is removed.

Ondetach ()

Called when the fragment is associated with the activity.

It can be seen from this graph that the state of activity determines the callback function that fragment may receive .

Say. 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 join and remove fragment, that is to say. The state of fragment can be changed independently only when the activity is in the resumed state .

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

Interactive Introduction to Android fragment and activity

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.