Sobes.tech
Middle

Wie fügt man einen Kontext in eine Methode mit Dagger Hilt hinzu?

sobes.tech KI

Antwort von AI

Injektieren des Contexts über @ApplicationContext oder @ActivityContext.

class MyViewModel @Inject constructor(
    @ApplicationContext private val context: Context // Injektion des Anwendungskontexts
) : ViewModel() {
    // Verwendung des Kontexts
}
class MyFragment @Inject constructor() : Fragment() {

    @Inject
    lateinit var myPresenter: MyPresenter // Injektion des Presenters, das den Activity-Kontext verwendet

    override fun onAttach(context: Context) {
        super.onAttach(context)
        // Dagger Hilt führt die Injektion durch
    }
}

class MyPresenter @Inject constructor(
    @ActivityContext private val context: Context // Injektion des Activity-Kontexts
) {
    // Verwendung des Kontexts
}