简体   繁体   中英

Android ViewModel for a custom view

I would like to refactor my Custom View to use android architecture components. 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. 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. 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. 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.

The point is to try to get an Activity from the context:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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