问题
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:
- You may use
Observer Pattern
to achieve this. To do this, You have to create aMutableLiveData
in yourMainActivity
and pass it tofragment
throughinterface
. - 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