Fragment 2 fragment communicating

后端 未结 4 920
一向
一向 2020-12-21 01:24

Why i should use the Communicating with Other Fragments pattern when I could simply use

((MyActivity)getActivity()).doFoo();

In my Fragmen

4条回答
  •  一整个雨季
    2020-12-21 02:24

    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 :

    • Otto
    • EventBus
    • RoboGuice events

    Those solutions are even cleaner and will lead to more elegant code.

提交回复
热议问题