Communicating between the tablayout Fragments [dup

2020-05-10 10:05发布

问题:

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 methods from fragment but resulting null pointer exception.

回答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:

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

}