本文介绍了在TabLayout片段之间进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用带有片段的选项卡布局.情况是这样的.
I used a tab layout with fragment. The scenario goes like this.
活动:
片段1,片段2,片段3
Fragment 1 , Fragment2 , Fragment3
从Fragment2更新Fragment1的用户界面.
From Fragment2 Updating the UI of Fragment1.
我尝试从片段访问方法,但导致空指针异常.
I tried to access the methods from fragment but resulting null pointer exception.
推荐答案
- 您可以使用
Observer Pattern
来实现.为此,您必须在MainActivity
中创建一个MutableLiveData
,并将其通过interface
传递给fragment
. - 然后从 FragmentA 发布值,并从 FragmentB 观察值,并在更改时进行操作
- 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
创建界面:
interface UpdateFragmentListener {
fun onUpdate(): MutableLiveData<Any>
}
在Activity
中实现:
class MainActivity: AppCompatActivity, UpdateFragmentListener {
val fragmentUpdate: MutableLiveData<Any> = MutableLiveData()
...
override fun onUpdate(): MutableLiveData<Any> = fragmentUpdate
}
在FragmentA内部:
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())
}
在FragmentB内部:
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
})
}
这篇关于在TabLayout片段之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!