【问题标题】:How to share data between two fragments? Having trouble with the MVVM architecture如何在两个片段之间共享数据? MVVM 架构有问题
【发布时间】:2020-08-10 13:41:55
【问题描述】:

目前我有两个片段,一个显示一个地方的天气,另一个让您在地图中选择一个点并将您重定向到另一个显示该点天气的片段。

我想要实现的是默认情况下拥有用户的位置,并通过转到选择任何其他地方的地图为用户提供选项。所以我想:

  • 通过 GPS 获取 lat/lng,然后将其“上传”到可以在此片段和地图片段之间共享这些值的某个地方(可能是活动?)
  • 如果选择了地图中的某个点,则更新这些值 - 两个片段都可以随时读取,只有地图片段可以更新

我相信我可以粗略地将 getter/setter 添加到我的活动中,然后在片段中将活动投射到我的特定活动中。但这似乎很糟糕。正确的方法是什么? 我现在拥有的:

  • MainActivity(通过底部导航栏连接两个片段)
  • ForecastFragment(显示纬度/经度的天气)
  • 预测视图模型
  • 地图片段
  • MapViewModel
  • 天气存储库
  • WeatherAPI(通过 RetroFit 更新值)

我正在使用 dagger 和 kotlin。

谢谢!

【问题讨论】:

标签: android kotlin mvvm retrofit dagger


【解决方案1】:

使用活动范围在ForecastFragmentMapFragment 之间共享一个公共视图模型

看看这里提供的例子Share data between fragments

class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Item>()

    fun select(item: Item) {
        selected.value = item
    }
}

class MasterFragment : Fragment() {

    private lateinit var itemSelector: Selector

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    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() {

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    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
        })
    }
}

注意:

两个片段都必须处理另一个片段所在的场景 尚未创建或可见。

【讨论】:

  • 感谢您的回答!一个问题,你是建议只有一个视图模型还是三个(天气、预测、共享)?
  • 两者都很好,取决于您的用例。任何对你有意义的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-31
  • 1970-01-01
  • 2020-07-31
  • 2013-02-25
  • 1970-01-01
相关资源
最近更新 更多