Fragment — Activity — Fragment Communications with ViewModels and Live Data
Android development is evolving at a rapid pace. There’s more that ever before in the android api’s, especially with the inclusion Android JetPack, about a year ago.
Fragment to activity communication is one of the most common things to work with in an application. And traditional developers will use a very traditional way to handle this. There’s still a lot of developers who use interfaces to communicate with the activity, and it works well even now.
However, in swoops in Android JetPack, with a mission to make the life of developers easier and get a certain level of structure to the application. Using these components, I’m going to explain how to achieve fragment communication with ViewModels and LiveData
Let's begin by creating a ViewModel, that's going to be shared between two fragments and the main_activity. We'll name this CommonViewModel
. This ViewModel will have one variable data
of type MutableLiveData
which we will update using the editData
function.
Now we’re going to create two fragment files, fragment_one
and fragment_two.
The second fragment will contain an edittext
, and whenever the user types into it, the edittext
will spew out data to the LiveData variable in the CommonViewModel
. The first fragment is going to be observing this LiveData variable and update the textview
every time it observes a change.
Lets begin with FragmentTwo.
In the onActivityCreated()
we create an instance of the CommonViewModel
by using the ViewModelProviders
method. We also set a listener to the et_fragmenttwo
EditText and update the data
variable using the editData
method
Next, in FragmentOne
we create an instance of the CommonViewModel
in the onActivityCreated().
We also set an observe
function on the LiveData
variable and assign values from the observable to TextView tv_fragmentone.
Finally we add both this fragments to the MainActivity
such that both are visible at the same time. We can observe that upon adding text to EditText et_fragementtwo
, the TextView tv_fragmentone
is updated instantly. We can use this technique to pass any type of data across fragments or activity.
You can find the entire project on my Github. I’ve also added code for fragment to communicate with the activity using the same technique. Drop a comment if you come across an roadblocks while implementing this.
https://github.com/jami4n/FragmentCommunicationWithViewModels