简体   繁体   English

用于自定义视图的 Android ViewModel

[英]Android ViewModel for a custom view

I would like to refactor my Custom View to use android architecture components.我想重构我的自定义视图以使用 android 架构组件。 However, I see that然而,我看到

ViewModelProviders.of(...)

takes only Activity or fragment.只需要活动或片段。 Any idea how to make it work?知道如何使它工作吗? Should I use fragment instead of Custom View?我应该使用片段而不是自定义视图吗?

It is possible to get obtain a ViewModel instance in View, although it's not recommended.可以在 View 中获取 ViewModel 实例,但不推荐这样做。 As per this post :根据这篇文章

While it is easy enough to obtain the ViewModels inside an Activity or a Fragment, it is not straightforward to obtain this instance inside a View.虽然在 Activity 或 Fragment 中获取 ViewModel 很容易,但在 View 中获取此实例并不简单。 The main reason behind this is because Views are supposed to be independent of all processing and even if all your logic is inside a ViewModel, the fact that you are accessing that ViewModel inside the View makes it reliant on something that it shouldn't.这背后的主要原因是因为 Views 应该独立于所有处理,即使您的所有逻辑都在 ViewModel 内,您在 View 内访问该 ViewModel 的事实使它依赖于它不应该依赖的东西。 The recommended way of controlling a View is to pass parameters to it based on the state of the ViewModel from the Fragment or the Activity.控制视图的推荐方法是根据来自 Fragment 或 Activity 的 ViewModel 的状态将参数传递给它。

The point is to try to get an Activity from the context:重点是尝试从上下文中获取 Activity:

override val activity: FragmentActivity by lazy {  
    try {
        context as FragmentActivity
    } catch (exception: ClassCastException) {
        throw ClassCastException("Please ensure that the provided Context is a valid FragmentActivity")
    }
}
override var viewModel = ViewModelProvider(activity).get(SharedViewModel::class.java)

As mentioned thought, I'd try to avoid this approach if possible.如前所述,如果可能的话,我会尽量避免这种方法。

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

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