The problem as follows. Let us have 3 tabs with fragments:
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:
Local Broadcast Receiver
for both instances of Fragment BonReceive()
check if recevied ID equals ID of FragmentBut 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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With