Search code examples
androidkotlinandroid-activitydependency-injectiondagger-hilt

Hilt injection into activity before super.onCreate()


I defined my own LayoutInflater.Factory2 class in a separate module. I want to inject it into each activity in my App, but the point is that I have to set this factory before activity's super.onCreate() method. When I using Hilt it makes an injection right after super.onCreate(). So I have an UninitializedPropertyAccessException.

Is there any opportunity to have an injection before super.onCreate with Hilt?

Below is my example of module's di.

@Module
@InstallIn(SingletonComponent::class)
object DynamicThemeModule {
    @FlowPreview
    @Singleton
    @Provides
    fun provideDynamicThemeConfigurator(
        repository: AttrRepository
    ): DynamicTheme<AttrInfo> {
        return DynamicThemeConfigurator(repository)
    }
}

Solution

  • You can inject the class before onCreate by using Entry Points like this.

    @AndroidEntryPoint
    class MainActivity: AppCompatActivity() {
       
       @EntryPoint
       @InstallIn(SingletonComponent::class)
       interface DynamicThemeFactory {
          fun getDynamicTheme() : DynamicTheme<AttrInfo>
       }
    
       override fun onCreate(savedInstanceState: Bundle?) {
          val factory = EntryPointAccessors.fromApplication(this, DynamicThemeFactory::class.java)
          val dynamicTheme = factory.getDynamicTheme()
          super.onCreate(savedInstanceState)
       }
    }
    

    If you need something like this a lot Id recommend creating an instance of it in the companion object of your Application class when your application starts (onCreate). That is before any of your views are created. So you don´t need to jump threw those hoops all the time, but can just access the instance that already exists. This code above won´t be available in attachBaseContext, when you need it there you have to create it in your application class I think.