Communicate Between Fragments Using ViewModel
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 itsActivity
, you can define an interface in theFragment
class and implement it within theActivity
. TheFragment
captures the interface implementation during itsonAttach()
lifecycle method and can then call the Interface methods in order to communicate with theActivity
.The host activity can deliver messages to a fragment by capturing the
Fragment
instance withfindFragmentById()
, 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…