Junior — Middle
What methods can be used to organize data exchange between two fragments in an application?
sobes.tech AI
Answer from AI
In Android, there are several approaches to exchange data between two fragments:
-
Through Activity — fragments communicate via the parent Activity, which acts as an intermediary. One fragment passes data to the Activity, and the other receives it.
-
ViewModel with LiveData — a shared ViewModel associated with the Activity allows fragments to observe data changes and exchange data reactively.
-
Callback interfaces — a fragment implements an interface that another fragment calls through the Activity.
-
SharedPreferences or databases — for more persistent storage and data exchange.
Example with ViewModel:
class SharedViewModel : ViewModel() {
val selectedItem = MutableLiveData<String>()
}
// In the first fragment
sharedViewModel.selectedItem.value = "Data to pass"
// In the second fragment
sharedViewModel.selectedItem.observe(viewLifecycleOwner) { data ->
// Handle received data
}
This method is considered modern and convenient for exchanging data between fragments within the same Activity.