Android Activity Inheritance with Dagger 2

Setting up Dagger 2 injection for inheritance situations with Android activities or fragments can be a pain. This article explains it simply with an example.

Suppose you have a BaseActivity that you need to extend. Let’s call the extending class SubClassedActivity.

Steps

@Module
abstract class UiModule {

@[ActivityScope ContributesAndroidInjector(modules = [SubClassedActivityModule::class])]
abstract fun contributeSubClassedActivityInjector(): SubClassedActivity
}

Define the baseActivityModule.

@Module
abstract class BaseActivityModule {
@Binds
abstract fun bindBaseActivity(instance: BaseActivity): FragmentActivity
}

Install the BaseActivityModulein the SubClassedActivityModule.

@Module(includes = [BaseActivityModule::class])
abstract class SubClassedActivityModule {

@Binds
abstract fun bindSubClassedActivity(instance: SubClassedActivity): BaseActivity

Now, let’s define the BaseActivity.

abstract class BaseActivity : Activity(), HasAndroidInjector {
@Inject
lateinit var fragmentInjector: DispatchingAndroidInjector<Any>

override fun androidInjector(): AndroidInjector<Any> = fragmentInjector

override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
...
}

Finally, define the SubClassedActivity.

class SubClassedActivity : BaseActivity() {
// no need to call AndroidInjector.inject(this)
}

Software Engineer