Junior — Middle
How is information transferred between Fragment components in Android?
sobes.tech AI
Answer from AI
In Android, data transfer between fragments usually occurs through the activity that contains them or using shared ViewModel.
Main methods:
-
Via activity:
- Fragment A calls a method of the activity and passes data.
- The activity passes data to Fragment B.
-
Using interfaces:
- Fragment A declares an interface for data transfer.
- The activity implements this interface and receives data from Fragment A, then passes it to Fragment B.
-
Shared ViewModel (using architecture components):
- Both fragments use the same ViewModel associated with the activity.
- The ViewModel contains LiveData through which fragments exchange data.
Example with Shared ViewModel:
class SharedViewModel : ViewModel() {
val selectedItem = MutableLiveData<String>()
}
// In Fragment A
viewModel.selectedItem.value = "Data to transfer"
// In Fragment B
viewModel.selectedItem.observe(viewLifecycleOwner) { data ->
// Use the received data
}