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.


abstract class UiModule {

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

Define the baseActivityModule.

abstract class BaseActivityModule {
abstract fun bindBaseActivity(instance: BaseActivity): FragmentActivity

Install the BaseActivityModulein the SubClassedActivityModule.

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

abstract fun bindSubClassedActivity(instance: SubClassedActivity): BaseActivity

Now, let’s define the BaseActivity.

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

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

override fun onCreate(savedInstanceState: Bundle?) {

Finally, define the SubClassedActivity.

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

Software Engineer