I am new to Android Fragment and trying to learn Fragment to Activity communications. What is the better approach(best practice) in Android for Fragment to Activity communication?
Lets say I have FragmentA and ActivityA. After my screen popups FragmentA, I would like to perform somemethod(probably UI related) in ActivityA
Here are two(pattern) possible Solutions:
Which pattern is more common/perfer in Android development and why. Or do you have an even better way to communicate from fragment to activity in Android to share with me?
Any comments, opinions, and suggestions is highly appreciated and welcome. ^^ .
The Fragment library provides two options for communication: a shared ViewModel and the Fragment Result API. The recommended option depends on the use case. To share persistent data with any custom APIs, you should use a ViewModel .
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 to communicate with the Activity.
Two Fragments should never communicate directly. The reason for this is that Fragment s are fluid & dynamic UI components that may fade in and out of view. Only the hosting Activity is capable of determining if a Fragment is added to the UI or has been detached from it.
We can communicate within fragments using the ViewModel. We can also communicate between fragments using Interface.
The second solution is the preferred one, because it allows your fragment to be more independent of its hosting activity.
If in the future you decide to put your fragment on a different activity, there are no changes needed on the fragment, and you will only need to implement the interface on your activity.
I'll add a third solution which is using an event bus (Otto for instance), which also works, although some might argue that it makes your code a little less readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With