Inter Fragment Communication After Fragment Creation
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. Up
Solution 1:
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:
publicinterfaceSubscriber {
voidcallMe();//to be used by the fragment who gets calledvoidtheOtherFragmentIsReady(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);
}
Solution 2:
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(newRunnable() {
@Overridepublicvoidrun() {
if (getActivity() != null) { // or whateverregisterComponents();
}
}
});
Post a Comment for "Inter Fragment Communication After Fragment Creation"