Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to share a fragment with a fragment?


Asked by Forest Pugh on Dec 03, 2021 FAQ



By passing getActivity instead of “this” to the ViewModelProviders.of method, we can scope the lifecycle of this ViewModel to the activity instead of the fragment, and this way access it from multiple different fragments to share data between them, as long as their activity is alive.
One may also ask,
If there are two or more fragments in an activity, they need to communicate and share the data between them. The traditional way of sharing the data between the two fragments is implementing the callback using an interface that is cumbersome and may throw exceptions. But the modern way of doing that is using shared ViewModel.
Also Know, Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly. You can communicate among fragments with the help of its Activity.
Likewise,
It is strongly recommended to always use a FragmentContainerView as the container for fragments, as FragmentContainerView includes fixes specific to fragments that other view groups such as FrameLayout do not provide. To declaratively add a fragment to your activity layout's XML, use a FragmentContainerView element.
In this manner,
You can’t treat a Fragment same as that of Activity. Like Activity, Fragments have their own life cycle. So, you should handle the lifecycle of Fragments while using it. In this blog, we will learn how to communicate between Fragments in our Android application.