Principles and examples of communication between fragment and activity in Android

Source: Internet
Author: User
Tags eventbus

Reference articles

Http://blog.csdn.net/guozh/article/details/25327685#comments

Activity and fragment communication methods generally have 3 ways

1. Define the interface in fragment, activity to implement Interface---> View the reference article above

2. Use of broadcasting mechanisms

3. Using Eventbus

These 3 ways recommend the use of Eventbus

The 2nd mode of broadcasting communication mechanism is described below:

First Mainactivity introduced a fragment, the activity of the layout is very simple, there is only one framelayout.

There is only one textview in the leftfragment layout, which replaces Framelayout in mainactivity

 Public classMainactivityextendsactionbaractivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); System.out.println ("Mainactivity--OnCreate"); Fragmentmanager FM= This. Getsupportfragmentmanager (); //register fragment in activity, or register in the archivefm.begintransaction (). replace (R.id.flcontent,NewLeftfragment (), "left"). commit (); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override Public Booleanonoptionsitemselected (MenuItem item) {intItemId =Item.getitemid (); //send a broadcast message to fragmentIntent Intent =NewIntent (); if(R.id.left = =itemId) {Intent.setaction ("Left"); Localbroadcastmanager.getinstance ( This). Sendbroadcast (Intent); }        return true; }}

The Leftfragment code is as follows:

 Public classLeftfragmentextendsFragment {PrivateTextView message; @Override Public voidonCreate (@Nullable Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //register a broadcast in fragment for receiving, messages sent over activityIntentfilter filter =NewIntentfilter (); Filter.addaction ("Left"); Localbroadcastmanager.getinstance (GetContext ()). Registerreceiver (NewBroadcastreceiver () {@Override Public voidOnReceive (Context context, Intent Intent) {//to do some business processing, such as networking operations, parsing operations ...Message.settext ("Leftfragment, received the activity--->left<---broadcast");    }}, filter); } @Override @Nullable PublicView Oncreateview (layoutinflater inflater, @Nullable viewgroup container, @Nullable Bundle savedinstancest ATE) {View View= View.inflate (GetContext (), R.layout.fragment_left,NULL); Message=(TextView) View.findviewbyid (r.id.message); returnview; }}

Click the Actionbar left_item button---> Run:

When you click Left_item, you switch to fragment to display the content.

Then there is the third way of communication: Eventbus

I. Overview

The Eventbus is a publish/Subscribe event bus optimized for Android. The main function is to substitute intent,handler,broadcast for passing messages between Fragment,activity,service and threads. The advantage is that the cost is small and the code is more elegant. and decoupling the sender and receiver.
1. Download the Eventbus class library
Source: Https://github.com/greenrobot/EventBus

2.EventBus Use steps:

1>define events: arbitrarily define an event
      public class MessageEvent { /* Additional fields if needed */ }
2>prepare Subscribers: sign up for our subscribers
      eventBus.register(this);
      public void onEvent(AnyEventType event) {/* Do something */};
3>post Events: publisher
      eventBus.post(event);

If you need to import a package using Gradle:compile ‘de.greenrobot:eventbus:2.4.0‘

3. Simple examples

Use Eventbus's Post method in mainactivity to send a message to fragment

 Public classMainactivityextendsactionbaractivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main);  This. Getsupportfragmentmanager (). BeginTransaction (). replace (R.id.flcontent,NewLeftfragment (), "left"). commit (); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (R.menu.main, menu); return true; } @Override Public Booleanonoptionsitemselected (MenuItem item) {//1.Activity send a message to fragmentEventbus.getdefault (). Post ("Change"); return true; }}

There are 2 things to do in a fragment:

Registering Eventbus and receiving communication messages sent over by activity

 Public classLeftfragmentextendsFragment {PrivateTextView message; @Override Public voidonCreate (@Nullable Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //1. Registration in recipient fragment is required EventbusEventbus.getdefault (). Register ( This); } @Override @Nullable PublicView Oncreateview (layoutinflater inflater, @Nullable viewgroup container, @Nullable Bundle savedinstancest ATE) {View View= View.inflate (GetContext (), R.layout.fragment_left,NULL); Message=(TextView) View.findviewbyid (r.id.message); returnview; }    /*** Receive the message that the activity is passing because the activity is passing a string, so here the argument is String *@paramtxt*/     Public voidonEvent (String txt) {if(Txt.equals ("Change") {Message.settext ("Fragment and activity communication succeeded."); //can do some other business, such as Get network connection, refresh the page ...        }    }}

The layout file and broadcast communication layout are exactly the same, run as follows:

The above is just the simplest communication mechanism of eventbus, and he has some other important methods

Reprint: http://blog.csdn.net/lmj623565791/article/details/40920453

Reprint: http://blog.csdn.net/harvic880925/article/details/40660137

Principles and examples of communication between fragment and activity in Android

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.