首页 > 解决方案 > 如何使用 Hilt 访问 attachBaseContext 中的注入属性?

问题描述

为了更改应用程序的默认值,我必须在Activity内的方法中Locale访问我的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)
    }

    .
    .
    .
}

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

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

attachBaseContext内部活动:

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

但我仍然得到同样的错误。我调试了代码,发现方法中applicationContextNull

我在网上搜索,我发现有人在dagger 这里遇到了同样的问题。但是没有公认的答案可以让我在hilt.

有没有办法在活动内部的方法中获取这个WrapContextattachBaseContext

标签: androiddependency-injectiondagger-hilt

解决方案


一旦附加到应用程序,您就可以使用入口点获取依赖项。幸运的是,这样的上下文被传递到:ApplicationComponentContextattachBaseContext


    @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))
    }

推荐阅读