Reputation: 21
I am working with Fragments in Android. I have two identical fragments FragA and FragB. Since they are identical: I need a method that says if I am on FragA and a textView in FragA changed or updates the same textView should change/update in FragB. Can anyone help me with creating a method that takes data from FragA changed about a particular View and passes it to FragB to update its View.
I have tried using interfaces and ViewModel for communicating with fragments, but I can't seem to figure out how to update two identical fragments when let's say one of them changes.
Upvotes: 0
Views: 79
Reputation: 885
This is actually an easily approachable problem these days. With a ViewModel
we can achieve this easily.
We can make a ViewModel
where our MutableLiveData
can live.
Our two (or more) fragments can observe the LiveData
events and both update at the same time.
I could post some code but I really think this CodeLabs is exactly what you are looking for and can get you up to speed in just a few minutes.
Android Lifecycle Aware Components Codelab
Upvotes: 1
Reputation: 36
You can easily do this with an external and awesome library, https://github.com/greenrobot/EventBus . This is a hidden gem for easy fragment to fragment communication in android. The docs are pretty self explanatory.
Please note: if you are using eventbus please remember to register eventbus only in the fragments OR classes you will be using it in, you do not have register an eventbus even in the class from where you are posting the event, else it will be giving you a compile time error. Also DO Not forget to unregister the eventbus using EventBus.getDefault().unRegister(this);
or EventBus.getDefault().unregister(context);
in order to prevent memory leaks
Upvotes: 0