如何使用Hilt访问attachBaseContext中注入的属性?

时间:2020-10-01 16:21:09

标签: android dependency-injection dagger-hilt

为了更改应用程序的默认Locale,我必须在 Activity (活动)内的WrapContext方法中访问attachBaseContext类:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    @Inject lateinit var wrapper: WrapContext

    .
    .
    .

    override fun attachBaseContext(newBase: Context?) {
        super.attachBaseContext(wrapper.setLocale(newBase!!))
    }
}

但是您可以想象得到nullPointerException,因为在调用attachBaseContext之后注入了该字段。

这是 WrapContext 类:

@Singleton
class WrapContext @Inject constructor() {

    fun setLocale(context: Context): Context {
        return setLocale(context, language)
    }

    .
    .
    .
}

我还尝试将 WrapContext 注入 MyApp 类中,以便在 Activity 中调用该字段时应初始化该字段。

@HiltAndroidApp
class MyApp : Application() {
    @Inject lateinit var wrapper: WrapContext
}

attachBaseContext内部活动:

override fun attachBaseContext(newBase: Context?) {
    super.attachBaseContext((applicationContext as MyApp).wrapper.setLocale(newBase!!))
}

但是我仍然遇到相同的错误。我调试了代码,发现该方法中applicationContext Null

我在线搜索,发现有人遇到与dagger here相同的问题。但是没有可以接受的答案,也许可以在hilt中给我一些实现的机会。

是否有办法在活动内部的WrapContext方法中获取此attachBaseContext类?

1 个答案:

答案 0 :(得分:3)

一旦将ApplicationComponent附加到应用程序,就可以使用entry pointContext获取依赖项。幸运的是,这样的上下文被传递到attachBaseContext


    @EntryPoint
    @InstallIn(ApplicationComponent::class)
    interface WrapperEntryPoint {
        val wrapper: WrapContext
    }

    override fun attachBaseContext(newBase: Context) {
        val wrapper = EntryPointAccessors.fromApplication(newBase, WrapperEntryPoint::class).wrapper
        super.attachBaseContext(wrapper.setLocale(newBase))
    }