In Android development, there are a few different ways to send informations between one fragment to another. As of September 2020, the recommended way to allow for this communication is to use LiveData exposed by a shared ViewModel.
The steps are relatively simple. Suppose that we want to send data from Fragment A to Fragment B:
- Create a ViewModel
- Have Fragment A and Fragment B share that same ViewModel.
- Create a LiveData inside the ViewModel to contain the data that’s to be passed from A to B.
- Assign or update value to the LiveData object inside Fragment A, usually with the help of a public method inside the ViewModel to assign or update the value.
- Have Fragment B observe the LiveData inside it
onCreate()
, and make use of the data there.