在 super.onCreate() 之前将 Hilt 注入到 Activity 中

gar*_*ian 6 android dependency-injection android-activity kotlin dagger-hilt

我在单独的模块中定义了自己的LayoutInflater.Factory2类。我想将它注入到我的应用程序中的每个活动中,但要点是我必须在活动的super.onCreate()方法之前设置此工厂。当我使用 Hilt 时,它会在 super.onCreate() 之后立即进行注入。所以我有一个 UninitializedPropertyAccessException。

有没有机会在 super.onCreate 之前用 Hilt 进行注入?

下面是我的模块 di 的示例。

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

Max*_*Max 3

您可以使用这样的入口点在 onCreate 之前注入类。

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

如果您经常需要这样的东西,我建议您在应用程序启动时在 Application 类的伴随对象中创建它的实例 ( onCreate)。那是在您创建任何视图之前。所以你\xc2\xb4不需要一直跳那些圈子,而只需访问已经存在的实例。上面的代码将在 中可用attachBaseContext,当您需要它时,我认为您必须在应用程序类中创建它。

\n