Junior — Middle
How is data exchanged between fragments when using FragmentManager?
sobes.tech AI
Answer from AI
Data exchange between fragments when using FragmentManager is usually carried out through the activity, which acts as an intermediary. Fragments should not directly interact with each other to maintain loose coupling.
Main methods of data exchange:
-
Through activity methods:
- A fragment sends data to the activity (for example, via an interface or direct method call).
- The activity passes data to another fragment by calling its public methods.
-
Using ViewModel with activity lifecycle:
- A shared ViewModel allows fragments to observe the same data.
- Changes in the ViewModel are automatically reflected in all subscribed fragments.
-
Using setFragmentResultListener and setFragmentResult (starting from Fragment 1.3.0):
- A fragment sends a result via FragmentManager.
- Another fragment listens for these results and reacts accordingly.
Example using setFragmentResult:
// Sending result from the first fragment
setFragmentResult("requestKey", bundleOf("dataKey" to "value"))
// In another fragment, listening for the result
setFragmentResultListener("requestKey") { key, bundle ->
val result = bundle.getString("dataKey")
// handle the result
}