So, I got the event in my fragment to pass to the activity, so how do I make it so the activity in turns, notifies fragment B to do something. I want to fragment B to populate a custom list when fragment A has a list item clicked on. So, it sends the event to the activity, now how do I get the activity to call events in fragment B?
Asked
Active
Viewed 1.5k times
2 Answers
32
One way to do it would be like this in your activity:
FragmentB fragmentB = (FragmentB)getFragmentManager().findFragmentById(R.id.fragmentBId);
fragmentB.performSomeTask();
This is of course assuming that you have a publicly accessibly method in FragmentB called performSomeTask();
Hope that helps!

runor49
- 3,870
- 1
- 21
- 18
-
Im stupid, I can just do it by calling fragment_b.doTask() if it is declared as public and static. – Shaun Mar 14 '11 at 01:32
-
2if you call that performSomeTask method in the onCreate method of activity and lets say that you fill some edittext field on it. Youll have a null pointer exception in case you're initializing the edittext in the onActivityCreate method of the the fragment. What's the best solution here? – Maxrunner Jun 15 '12 at 18:39
10
The best practice is probably to create interfaces for both fragments and then have the activity implement the interfaces. You want to have good decoupling between fragments so that you can reuse them in other places.

Marco RS
- 8,145
- 3
- 37
- 45