Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
941 views
in Technique[技术] by (71.8m points)

android - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...