How to inject activity into another class using da

2019-07-20 07:04发布

问题:

I'm using the new dagger.android method to inject activities, but I wonder what to do if you want to inject Activity to a class? Maybe a Navigator class which needs the current activity:

package com.abydos.messenger.ui

import android.app.Activity
import com.abydos.messenger.ui.register.RegisterActivity
import org.jetbrains.anko.startActivity
import javax.inject.Inject

class Navigator @Inject constructor(private val activity: Activity) {
    fun register() {
        activity.startActivity<RegisterActivity>()
    }

    ...
}

And in ActivityBindingModule.kt

package com.abydos.messenger.di

import com.abydos.messenger.ui.register.RegisterActivity
import dagger.Module
import dagger.android.ContributesAndroidInjector

@Module
abstract class ActivityBindingModule {
    @ContributesAndroidInjector
    abstract fun contributeRegisterActivity(): RegisterActivity

    ...
}

Maybe something like this for each activity might work?

@Binds abstract fun bindActivity(yourActivity: YourActivity): Activity

But I don't like the idea of having to write this for all activities, is there a better way?

回答1:

Unfortunately dagger-android-processor don't create this binding automatically.

You need one more module:

@Module
interface RegisterModule {
    @Binds
    fun bindActivity(activity: RegisterActivity): Activity
}

And in your ActivityBindingModule:

@ContributesAndroidInjector(modules = arrayOf(RegisterModule::class))
abstract fun contributeRegisterActivity(): RegisterActivity