Junior — Middle
How do you transfer information between two fragments in an application?
sobes.tech AI
Answer from AI
There are several approaches to passing information between two fragments in Android:
-
Via Activity: Fragments communicate through the parent Activity, which acts as an intermediary.
-
Using ViewModel with a shared lifecycle with the Activity: A ViewModel is created associated with the Activity, and both fragments access it, exchanging data via LiveData.
-
Fragment arguments: When creating the second fragment, data can be passed through a Bundle using the
setArguments()method.
Example of passing data via ViewModel:
class SharedViewModel : ViewModel() {
val selectedData = MutableLiveData<String>()
}
// In the first fragment
sharedViewModel.selectedData.value = "Data to pass"
// In the second fragment
sharedViewModel.selectedData.observe(viewLifecycleOwner) { data ->
// Use the received data
}