将实际的应用程序状态保留在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/