AndroidBoy
AndroidBoy

Reputation: 35

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.

Upvotes: 0

Views: 146

Answers (1)

mahdi shahbazi
mahdi shahbazi

Reputation: 2132

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

Upvotes: 0

Related Questions