Junior — Middle
How can information be transferred between two fragments in an application?
sobes.tech AI
Answer from AI
In Android, the following approaches are commonly used for data transfer between two fragments:
-
Through Activity: Fragments communicate via the parent Activity. One fragment passes data to the Activity, and the Activity passes it to another fragment.
-
Using ViewModel: A shared ViewModel associated with the Activity allows fragments to exchange data through LiveData or other observable objects.
-
Fragment arguments: When creating a new fragment, data can be passed via a Bundle in the
setArguments()method, and then retrieved inonCreate().
Example of data transfer via ViewModel:
// Shared ViewModel
class SharedViewModel : ViewModel() {
val selectedItem = MutableLiveData<String>()
}
// In the first fragment
sharedViewModel.selectedItem.value = "Data to transfer"
// In the second fragment
sharedViewModel.selectedItem.observe(viewLifecycleOwner) { data ->
// Use the received data
}
This method is convenient because it does not require direct connection between fragments and takes into account the lifecycle of components.