android - 在Kotlin和Android中以MVVM模式保持应用程序状态的正确方法

标签 android kotlin mvvm

将实际的应用程序状态保留在MVVM中的正确方法是什么?一个简单的例子来描述我的意思:我有两个片段和一个Class的全局变量或对象。我可以在两个片段上更改此变量或对象。我应该在哪里将其保留在代码中?

最佳答案

最简单的方法是使用KTX扩展功能activityViewModels<VM : ViewModel> 参见here

从文档中:

Returns a property delegate to access parent activity's ViewModel ...



它将检索片段附加到的 Activity 的ViewModel提供的ViewModelProviders实例。
因此, View 模型实例上的任何更改都将反射(reflect)在所有片段上。

这里有个简单的例子:
class MVModel: ViewModel() {
    var count = MutableLiveData(0)

    fun increment() {
        count.value = count.value!!.plus(1)
    }
}
class MFragment: Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val binding = FragmentMBinding.inflate(inflater, container, false)
        val viewModel by activityViewModels<MVModel>()
        binding.lifecycleOwner = this // <-- this enables MutableLiveData update the UI
        binding.vm = viewModel
        return binding.root
    }

}

关于android - 在Kotlin和Android中以MVVM模式保持应用程序状态的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61087801/

相关文章:

android - 如何将用户同意传递给 AdMob (GDPR)

android - 如何在 Android 中实现 RESTFUL 服务?

kotlin - 如何将自动生成的ID添加到Cloud Firestore数据库

c# - 在WPF中设置listview ItemContainerStyle

c# - MVVM 中的绑定(bind)错误

ios - SwiftUI决定放置逻辑的最佳viewModel

javascript - React Native Switch on Android 报错

android - android 的 scala 应用程序如何减小文件大小?

android - 设置 View 以在可用空间中扩展至最大尺寸

java - Android MotionLayout 在真实设备上不显示动画