Skip to content Skip to sidebar Skip to footer

Communicating Between The Tablayout Fragments

I used a tab layout with fragment. The scenario goes like this. Activity: Fragment 1 , Fragment2 , Fragment3 From Fragment2 Updating the UI of Fragment1. I tried to access the meth

Solution 1:

  1. 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.
  2. Then post value from FragmentA and observe it from FragmentB and do operation when change

Create interface:

interfaceUpdateFragmentListener{
    funonUpdate(): MutableLiveData<Any>
}

Implements this in Activity:

classMainActivity: AppCompatActivity, UpdateFragmentListener {val fragmentUpdate: MutableLiveData<Any> = MutableLiveData()

   ...

   overridefunonUpdate(): MutableLiveData<Any> = fragmentUpdate
}

Inside FragmentA:

...

val updateListener: UpdateFragmentListener 

overridefunonAttach(context: Context) {
    updateListener = context as UpdateFragmentListener 
}

overridefunonViewCreated(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 

overridefunonAttach(context: Context) {
    updateListener = context as UpdateFragmentListener 
}

overridefunonViewCreated(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
    })

}

Post a Comment for "Communicating Between The Tablayout Fragments"