- You may use
Observer Pattern
to achieve this. To do this, You have to create a MutableLiveData
in your MainActivity
and pass it to fragment
through interface
.
- Then post value from FragmentA and observe it from FragmentB and do operation when change
Create interface:
interface UpdateFragmentListener {
fun onUpdate(): MutableLiveData<Any>
}
Implements this in Activity
:
class MainActivity: AppCompatActivity, UpdateFragmentListener {
val fragmentUpdate: MutableLiveData<Any> = MutableLiveData()
...
override fun onUpdate(): MutableLiveData<Any> = fragmentUpdate
}
Inside FragmentA:
...
val updateListener: UpdateFragmentListener
override fun onAttach(context: Context) {
updateListener = context as UpdateFragmentListener
}
override fun onViewCreated(v: View, savedInstanceState: Bundle) {
super.onViewCreated(v, savedInstanceState
//use like this by modifying it wherever you need inside FragmentA
updateListener.onUpdate().postValue(Any())
}
Inside FragmentB:
...
val updateListener: UpdateFragmentListener
override fun onAttach(context: Context) {
updateListener = context as UpdateFragmentListener
}
override fun onViewCreated(v: View, savedInstanceState: Bundle) {
super.onViewCreated(v, savedInstanceState
//Observe it and do operation wherever you need inside FragmentB
updateListener.onUpdate().observe(this, Observer {
// implement your logic here
})
}