11Communicating with other fragments (communication between fragment)

Source: Internet
Author: User

In order to reuse the Fragment UI components, you should build each as a completely self-contained, modular component that Defines its own layout and behavior. Once You has defined these reusable fragments, you can associate them with a Activity and connect them with the Applicat Ion logic to realize the overall composite UI.

Often you'll want one Fragment to communicate with another, for example to change the content based on a user event. All fragment-to-fragment communication are done through the associated Activity. Fragments should never communicate directly.

Two fragment cannot communicate directly and must be communicated through the activity associated with it.

First step:Define an Interface

Define an interface:

to allow a Fragment-to-communicate up-to-it Activity, you can define an interface in the Fragment class and implement It within the Activity. The Fragment captures the interface implementation during its Onattach () lifecycle method and can then call the interface Methods in order to communicate with the Activity.
define an interface in the fragment class, implement it in activity, and when fragment enters the Onattach () cycle, fragment captures the implementation of the interface in the activity, The interface's methods are then invoked to communicate with the activity.
public class Headlinesfragment extends Listfragment {    Onheadlineselectedlistener mcallback;    Container Activity must implement this interface public    interface Onheadlineselectedlistener {public        void OnA rticleselected (int position);    }    @Override public    void Onattach (activity activity) {        Super.onattach (activity);                This makes sure, the container activity has implemented        //the callback interface. If not, it throws an exception        try {            mcallback = (onheadlineselectedlistener) activity;        } catch (Classcast Exception e) {            throw new ClassCastException (activity.tostring ()                    + "must implement Onheadlineselectedlistener ");        }    }        ...}

Now the fragment can deliver messages to the activity by calling the onArticleSelected()method (or other methods in the interface) using the mCallbackinstance of the OnHeadlineSelectedListenerinterface.

for example, the following method in the fragment was called when the user clicks on a l IST item. The fragment uses the callback interface to deliver the event to the parent activity.
   @Override public    void Onlistitemclick (ListView l, View V, int. position, long ID) {        //Send the event to the host a Ctivity        mcallback.onarticleselected (position);    }

Step Two:Implement the Interfaceimplementing the interface:

In order to receive event callbacks from the fragment, the activity that hosts it must implement the interface defined in The Fragment class.

For example, the following activity implements the interface from the above example.

public static class Mainactivity extends Activity        implements headlinesfragment.onheadlineselectedlistener{    ...        public void onarticleselected (int position) {        //the user selected the headline of a article from the Headlinesfragme NT//Do something-here-to-        display that article    }}
Step Three:deliver a Message to a Fragment
Pass data to fragment: for instance, imagine of the activity shown above may contain another fragment that's used to display the item Speci Fied by the data returned in the above callback method. In this case, the activity can pass the information received in the callback method to the other fragment that would displa Y The item:
public static class Mainactivity extends Activity implements headlinesfragment.onheadlineselectedlistener{... public void onarticleselected (int position) {//the user selected the headline of a article from the HEADLINESF                Ragment//Do something-to-display that article articlefragment Articlefrag = (articlefragment)        Getsupportfragmentmanager (). Findfragmentbyid (r.id.article_fragment); if (Articlefrag! = null) {//If article Frag is available, we ' re in Two-pane layout ...//Call a Me        Thod in the articlefragment to update its content articlefrag.updatearticleview (position); } else {//Otherwise, we ' re in the One-pane layout and must swap frags ...//Create fragment and GI            ve it an argument for the selected article articlefragment newfragment = new Articlefragment ();            Bundle args = new bundle (); Args.putint (articlefragment.arg_position, position);                    Newfragment.setarguments (args);            Fragmenttransaction transaction = Getsupportfragmentmanager (). BeginTransaction (); Replace whatever is in the Fragment_container view with this fragment,//and add the transaction to the BAC            K stack so the user can navigate back transaction.replace (R.id.fragment_container, newfragment);            Transaction.addtobackstack (NULL);        Commit the transaction transaction.commit (); }    }}

One of the more important methods is:
Newfragment.setarguments (args);

11Communicating with other fragments (communication between fragment)

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.