在 super.onCreate() 之前将 Hilt 注入 activity
Hilt injection into activity before super.onCreate()
我在单独的模块中定义了自己的 LayoutInflater.Factory2 class。我想将它注入我应用程序中的每个 activity,但关键是我必须在 activity 的 super.onCreate()[=21 之前设置这个工厂=] 方法。
当我使用 Hilt 时,它会在 super.onCreate() 之后立即进行注入。所以我有一个 UninitializedPropertyAccessException。
在使用 Hilt super.onCreate 之前是否有机会进行注射?
下面是我的模块di的例子。
@Module
@InstallIn(SingletonComponent::class)
object DynamicThemeModule {
@FlowPreview
@Singleton
@Provides
fun provideDynamicThemeConfigurator(
repository: AttrRepository
): DynamicTheme<AttrInfo> {
return DynamicThemeConfigurator(repository)
}
}
您可以像这样使用 Entry Points 在 onCreate 之前注入 class。
@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)
}
}
如果您经常需要这样的东西,我建议您在应用程序启动时 (onCreate
) 在应用程序 class 的伴随对象中创建它的一个实例。那是在创建任何视图之前。所以你不需要一直跳投掷那些箍,而是可以访问已经存在的实例。上面的代码在 attachBaseContext
中不可用,当你需要它时,你必须在你的应用程序中创建它 class 我想。
我在单独的模块中定义了自己的 LayoutInflater.Factory2 class。我想将它注入我应用程序中的每个 activity,但关键是我必须在 activity 的 super.onCreate()[=21 之前设置这个工厂=] 方法。 当我使用 Hilt 时,它会在 super.onCreate() 之后立即进行注入。所以我有一个 UninitializedPropertyAccessException。
在使用 Hilt super.onCreate 之前是否有机会进行注射?
下面是我的模块di的例子。
@Module
@InstallIn(SingletonComponent::class)
object DynamicThemeModule {
@FlowPreview
@Singleton
@Provides
fun provideDynamicThemeConfigurator(
repository: AttrRepository
): DynamicTheme<AttrInfo> {
return DynamicThemeConfigurator(repository)
}
}
您可以像这样使用 Entry Points 在 onCreate 之前注入 class。
@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)
}
}
如果您经常需要这样的东西,我建议您在应用程序启动时 (onCreate
) 在应用程序 class 的伴随对象中创建它的一个实例。那是在创建任何视图之前。所以你不需要一直跳投掷那些箍,而是可以访问已经存在的实例。上面的代码在 attachBaseContext
中不可用,当你需要它时,你必须在你的应用程序中创建它 class 我想。