I want to make a custom view in android with MVVM architecture. First of all, I want to ask, is ViewModel working perfectly with a custom view as it works in case of activity or fragment? Can we get ViewModel from ViewModel provider in a custom view?
If I need to make a separate custom view what will the correct approach?
Q: Can we get
ViewModelfrom ViewModel provider in a custom view?Ans: Simple answer would be yes you can !
But How? (Further explanation)
ViewModelProvidersrequired either context asActivityorFragment. So you can retrievecontextfrom your CustomView class usinggetContext()which would beActivity/Fragmentwhere you're using it.Cast that
contextto either of type & provide it toViewModelProviderswhich will give you object of thatActivity/Fragmentcontainer.Hence using like this, you can share ViewModel between your
CustomViewandActivity/Fragment.Side Note: You can also make your
CustomViewimplementLifeCycleObserver, in such way you can also make your view respect lifecycle ofActivity/Fragmentfor initialization/destruction stuffs.