Android official Getting Started document [18] communication with other fragments

Source: Internet
Author: User

Android official Getting Started document [18] communication with other fragments communicating with other fragments
Communicating with other fragments

This lesson teaches
1.Define an Interface
2.Implement the Interface
3.Deliver a Message to a Fragment

You should also read
? Fragments

This lesson teaches you
1. Define an interface
2. Implementing the interface
3. Pass a message to a code snippet

You should also read
? fragment


Try it Out
Give it a try.

Download the sample
Fragmentbasics.zip
Download sample
Fragmentbasics.zip

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.
In order to reuse the code snippets UI components, you should create individual, modular components that define your own layout and behavior completely independent. Once you have defined these reusable fragments, you can connect them with their activities and join the application logic to achieve a holistic 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.
Usually you want a code snippet to communicate with another, for example, to change the content based on the user event. All code snippets to code snippets are communicated through the associated activity. Two fragments should never communicate directly.

Define an Interface
Define an interface

--------------------------------------------------------------------------------

To-allow a Fragment to communicate-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.
In order for a code fragment to come up with the activity of the communication, you can define the interface of the Code fragment class and implement it in the activity. The code fragment captures the process of implementing its Onattach () lifecycle method, and can then invoke an interface method to communicate with the activity.

Example of Fragment to Activity communication:
Here is an example of fragment-to-activity communication:

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 I Nterface) using the Mcallback instance of the Onheadlineselectedlistener interface.
The fragment can now transmit messages to the activity by calling the Mcallback instance onarticleselected () method using the Onheadlineselectedlistener interface (or other methods on the interface).

For example, the following method in the fragment was called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.
For example, in the fragment following method, when the user taps a list item is called. The fragment uses the callback interface to pass 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);    }


Implement the Interface
Implementing interfaces


--------------------------------------------------------------------------------

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

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

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    }}


Deliver a Message to a Fragment
Pass a message to a code snippet

--------------------------------------------------------------------------------

The host activity can deliver messages to a fragment by capturing the fragment instance with Findfragmentbyid () and then dire ctly call the fragment ' s public methods.
Host activity can be transmitted to a fragment by capturing a code fragment such as a Findfragmentbyid (), and then invoking the public method of the fragment directly.

For instance, imagine of the activity shown above may contain another fragment that's used to display the item specified 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:
For example, assume that the activity shown above can contain another fragment that displays the item specified by the data returned by the preceding callback method. In this case, the activity can be passed in other fragments of the callback method, and the information received by the item will be displayed:

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 (); }    }}


Next class:saving Data
Next lesson: Saving data

This article is translated from: https://developer.android.com/training/basics/fragments/communicating.html

Android official Getting Started document [18] communication with other fragments

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.