简体   繁体   English

如何通知一个片段另一个片段上发生了一些事情

[英]How to notify a fragment that something happened on another fragment

i have 2 fragments on the screen, how can i notify the 2nd that something happened on the 1st?我的屏幕上有 2 个片段,我如何通知第 2 个第 1 个发生的事情? now I am using this solution:现在我正在使用这个解决方案:

    companion object {
    private val onFullScreenPressedEvent = SingleLiveEvent<Boolean>()
    val onFullScreenPressed: LiveData<Boolean> = onFullScreenPressedEvent
}

and observe onFullScreenPressed from second fragment并从第二个片段观察 onFullScreenPressed

Your best bet would be to use a ViewModel tied to the Activity of the Fragments (so shared between fragments), and modify the liveData there.您最好的选择是使用与片段的 Activity 绑定的 ViewModel(在片段之间共享),并在那里修改 liveData。

example Viewmodel示例视图模型

class MyActivityViewModel : ViewModel(){

    private val onFullScreenPressedEvent = SingleLiveEvent<Boolean>()
    val onFullScreenPressed: LiveData<Boolean> = onFullScreenPressedEvent

fun onFullScreen(){
    onFullScreenPressedEvent.call()
}}

For example, by using implementation "androidx.fragment:fragment-ktx:1.4.0" you can do in fragment A例如,通过使用implementation "androidx.fragment:fragment-ktx:1.4.0" ,您可以在片段 A 中执行

private val viewModelA: MyActivityViewModel by activityViewModels()

and call the code that will change the event viewModelA.onFullScreen()并调用将更改事件viewModelA.onFullScreen()的代码

Then in Fragment B然后在片段 B

private val viewModelB: MyActivityViewModel by activityViewModels()

and observe the liveData you trigger in Fragment A viewModelB.onFullScreenPressed.observe(viewLifecycleOwner, myObserver)并观察您在 Fragment A viewModelB.onFullScreenPressed.observe(viewLifecycleOwner, myObserver)中触发的 liveData

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM