Communicate Between Fragments Using ViewModel

Abhilash Das
Geek Culture
Published in
4 min readAug 21, 2019

--

To make the fragments reusable and make them part of a modular architecture, Fragments should be self-reliant and should define its implementation independent of any activity or fragment so that a developer can connect the fragment to any activity or fragment and it should fit in perfectly as any jigsaw puzzle.

Therefore, casting an activity instance to invoke another fragment’s method should be avoided, something like this:

(activity as MainActivity).invokeMethodInAnotherFragment()

Google recommends the communication should be via interfaces. according to the official documentation :

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.

The host activity can deliver messages to a fragment by capturing the Fragment instance with findFragmentById(), then directly call the fragment's public methods.

These are the inference one can derive from above:

  • Fragments can’t and shouldn’t talk to each other.
  • Communication between fragments…

--

--