Middle
How to add context to a method using Dagger Hilt?
sobes.tech AI
Answer from AI
Inject the Context via @ApplicationContext or @ActivityContext.
class MyViewModel @Inject constructor(
@ApplicationContext private val context: Context // Injecting application context
) : ViewModel() {
// Using context
}
class MyFragment @Inject constructor() : Fragment() {
@Inject
lateinit var myPresenter: MyPresenter // Injecting presenter that uses Activity context
override fun onAttach(context: Context) {
super.onAttach(context)
// Dagger Hilt will perform injection
}
}
class MyPresenter @Inject constructor(
@ActivityContext private val context: Context // Injecting Activity context
) {
// Using context
}