Communicating between the tablayout Fragments [duplicate]

本秂侑毒 提交于 2020-01-22 04:06:00

问题


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

}


来源:https://stackoverflow.com/questions/58535349/communicating-between-the-tablayout-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!