Why i should use the Communicating with Other Fragments pattern when I could simply use
((MyActivity)getActivity()).doFoo();
In my Fragmen
Communicating between fragments should be only through activity. ((MyActivity)getActivity()).doFoo() - will call a method in activity and then update the other fragment
Fragment should be control only by the activity. Say.. if an fragment has a direct way to communicate with the other fragment , then there are possible that an fragment can be detached from other fragment without the activity aware.
This is ultimately a question of coupling and re-usability.
If you use the code example you posted in your question your Fragment
is not re-usable with other activities. It is 'tightly coupled'. It's fine if you're working on your own and you don't think anyone is likely to ever use or read your code later (including yourself), and that you're definitely never going to need to use that Fragment
anywhere else. But generally speaking you should still use the proper pattern, just to get into the habit of using it.
If you have a position coding in a company keeping 'loose coupling' will help you and your co-workers a great deal in the long run, and means you can go straight back to your code and re-use it on later projects if called for.
When you call ((MyActivity)getActivity()).doFoo()
you are downcasting your object and you could encounter a RuntimeException
if the containing Activity isn't a an instance of MyActivity
. The direct call means that the Fragment is tightly coupled with the Activity. Many people believe this is not a good thing.
When you implement the interface as described in your link, you won't be able to build your app unless you're passing around an object that has implemented it.
This means that if you use the fragment elsewhere, you eradicate the risk of a RuntimeException
because it is strongly typed.
There's a question here explaining why strong typing is good and tight coupling is bad
Because it creates a strong direct coupling of your Fragment and your Activity, thus decreasing the re-usability of your Fragment : you can only use it with this Activity.
Using an interface to mediate the communication is more flexible has multiple activities can now embed your Fragment, they just have to implement the communication interface.
That's equivalent in term of program execution, but it's a better design, quite close from the Observable-Observer design pattern.
Also note that they are alternative solutions :
Those solutions are even cleaner and will lead to more elegant code.