Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communicate between different instances of same fragment

The problem as follows. Let us have 3 tabs with fragments:

  • Tab 1 (Fragment A). Needs to send data to Tab 2.
  • Tab 2 (Fragment B). Needs to receive data from Tab 1.
  • Tab 3 (Fragment B). Already contains data.

As you see Tab 3 and Tab 2 contain the same Fragment but different instances.

How do I send data (not via arguments) to exactly Tab 2?

What I've tried:

  1. Set the unique ID for Fragment B via arguments when they were created.
  2. Register same Local Broadcast Receiver for both instances of Fragment B
  3. Send data from Fragment A to Fragment B with its ID
  4. In Fragment B onReceive() check if recevied ID equals ID of Fragment

But unfortunately broadcast was sent to Tab 3 only.


EDIT: some more information.

Those tabs are hosted inside another fragment with ViewPager. Thats due to combination of NavigationDrawer which has fragment with ViewPager and Tabs mentioned in question.

like image 234
AnZ Avatar asked Dec 10 '15 10:12

AnZ


2 Answers

I'd suggest to introduce EventBus in your app.

To add dependency - add compile 'de.greenrobot:eventbus:2.4.0' into your list of dependencies.

Then, you just subscribe your third tab's fragment to listen to event from the first fragment.

Something like this: in Fragment B

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    eventBus.register(this);
}

@Override
public void onDetach() {
    eventBus.unregister(this);
    super.onDetach();
}

@SuppressWarnings("unused") // invoked by EventBus
public void onEventMainThread(NewDataEvent event) {
    // Handle new data
}

NewDataEvent.java

public class NewDataEvent extends EventBase {
    public NewDataEvent() {}
}

And in Fragment A just send the event:

protected EventBus eventBus;
....
eventBus = EventBus.getDefault();
....
eventBus.post(new NewDataEvent());

(and to avoid handling event in 2nd tab - just pass extra parameter during instantiation of fragment, if it has to listen to the event)

like image 162
Konstantin Loginov Avatar answered Sep 21 '22 10:09

Konstantin Loginov


Are the fragments hosted in one activity? Then you could implement an interface on your hosting activity.

YourActivity implements MyInterface {
...
}

And in your fragments you define this:

@Override
public void onAttach(final Activity context) {
  myInterface = (MyInterface) context;
}

And when you click something in your fragment then call myInterface.doSomething(parameter);. And then your activity can delegate to another fragment.

like image 22
Thomas R. Avatar answered Sep 22 '22 10:09

Thomas R.