Search code examples
androidandroid-architecture-componentsandroid-sdk-2.1

MVVM architecture with custom view


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?


Solution

  • Q: Can we get ViewModel from ViewModel provider in a custom view?

    Ans: Simple answer would be yes you can !

    But How? (Further explanation) ViewModelProviders required either context as Activity or Fragment. So you can retrieve context from your CustomView class using getContext() which would be Activity/Fragment where you're using it.

    Cast that context to either of type & provide it to ViewModelProviders which will give you object of that Activity/Fragment container.

    Hence using like this, you can share ViewModel between your CustomView and Activity/Fragment.


    Side Note: You can also make your CustomView implement LifeCycleObserver, in such way you can also make your view respect lifecycle of Activity/Fragment for initialization/destruction stuffs.