[英]How can i share data across multiple fragments in application?
I am working on an application where im taking input from users across multiple fragments under same activity, and then i am sending that data to firebase now how can i achieve that using shared viewmodel, if possible please guide me how can i achieve that, I am completely new to android.我正在开发一个应用程序,在该应用程序中,我在同一活动下跨多个片段从用户那里获取输入,然后我将该数据发送到 firebase 现在我如何使用共享视图模型来实现这一点,如果可能的话,请指导我如何实现这一点,我我对 android 完全陌生。 Thank You
谢谢你
Can you please elaborate and share some code?您能否详细说明并分享一些代码? It is very difficult to understand what your question is.
很难理解你的问题是什么。
I'm assuming you want to share data between fragments.我假设您想在片段之间共享数据。 One way to do that is through ViewModels
一种方法是通过 ViewModels
Specifically, you'll need a view model like this:具体来说,您需要这样的视图 model :
class SharedViewModel : ViewModel() {
val selected = MutableLiveData<Item>()
fun select(item: Item) {
selected.value = item
}
}
Then you have your fragments:然后你有你的片段:
class SharedViewModel : ViewModel() {
val selected = MutableLiveData<Item>()
fun select(item: Item) {
selected.value = item
}
}
class ListFragment : Fragment() {
private lateinit var itemSelector: Selector
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
itemSelector.setOnClickListener { item ->
// Update the UI
}
}
}
class DetailFragment : Fragment() {
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
// Update the UI
})
}
}
Notice that both fragments retrieve the activity that contains them.请注意,两个片段都检索包含它们的活动。 That way, when the fragments each get the ViewModelProvider, they receive the same SharedViewModel instance, which is scoped to this activity.
这样,当每个片段都获得 ViewModelProvider 时,它们会收到相同的 SharedViewModel 实例,该实例的范围仅限于此活动。
If you want to know more about this, refer to: https://developer.android.com/topic/libraries/architecture/viewmodel如果您想了解更多相关信息,请参阅: https://developer.android.com/topic/libraries/architecture/viewmodel
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.