Reputation: 5926
In my Acitivty i keep on switching between the fragements depending upon the user data.
Now lets say i have two Fragments A & B.
Now i want fragment A to communicate with B.
Upon some condition fragment might call the hosted activity to replace the current fragment with fragment B (with the commit operation which is scheduled as a work ).
Now i want some communication to happen from frag A to frag B (call a method on frag b from frag A) But that method of frag B requires the whole creation process of frag B to happen which i don't know when will happen because that is happening asynchronously.
How can i achieve such scenario where frag A should help to crate frag B and then invoke a method on frag B.
I have checked the inter fragment communication topic http://developer.android.com/training/basics/fragments/communicating.html but that is more on how to replace a fragment. There is no info on how after that communication can happen.
cheers, Saurav
Upvotes: 0
Views: 130
Reputation: 1888
Well you could always go to your Activity getActivity()
, ask if there is a Fragment you want to communicate with findFragmentByXyz()
and do your stuff with it (or create it, if it's not created yet).
If you want to make sure, that you communicate with the other Fragment, when it's ready (e.g. when its UI is ready), you can post a 'Runnable' on the UI of Fragment B and notify your Activity/Fragment A/whatever, when you're ready.
getView().post(new Runnable() {
@Override
public void run() {
if (getActivity() != null) { // or whatever
registerComponents();
}
}
});
Upvotes: 0
Reputation: 130
A possible way might be to make both of the fragments implement a common interface (let's call it Subscriber
).
The interface shall look like this:
public interface Subscriber {
void callMe();//to be used by the fragment who gets called
void theOtherFragmentIsReady(Subscriber sub);//to be used by the fragment that will perform the call.
}
In the activity hosting the fragments add the following method:
public void fragmentCreated(Subscriber sub) {
Subscriber fragmentA = ...;//retrieve fragment A
fragmentA.theOtherFragmentIsReady(sub);//let the fragmentA that fragment B has been created
}
Finally, in the onCreated() method of the fragments add:
public void onCreate() {
((YourActivity)getActivity()).fragmentCreated(this);
}
Upvotes: 1