Search code examples
androidandroid-databindingandroid-annotationsandroid-mvvm

Can I inject @RootContext in ViewModel class?


I create MVVM android app, and I need context in my ViewModel class. I know that a ViewModel must never reference a view, Lifecycle, or any class that may hold a reference to the activity context. But... does it apply also inject Context by @RootContext annotation?

I'm also wondering if I can use the context from a view object in the onClick method when I use DataBinding in ViewModel class.


Solution

  • so you can pass clicked view add your onclick param.

    <View
    ...
    android:onClick="@{(v)-> viewModel.modelOnClick(v)}"
    ...
    />
    

    class ViewModel

    class ViewModel{
       public void modelOnClick(View v){
       }
    }
    

    so you have your clicked view in your model and can use it's context