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

How to access injected properties in attachBaseContext using Hilt?

为了更改应用程序的默认 Locale,我必须在 attachBaseContext 方法中访问我的 WrapContext classActivity:

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    @Inject lateinit var wrapper: WrapContext

    .
    .
    .

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

但正如你想象的那样,我得到了 nullPointerException,因为该字段是在调用 attachBaseContext 之后注入的。

这里是 WrapContext class:

@Singleton
class WrapContext @Inject constructor() {

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

    .
    .
    .
}

我还尝试在 MyApp class 中注入 WrapContext 因此在 [=] 中调用它时应该初始化该字段42=]Activity.

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

attachBaseContext 里面 activity:

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

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

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

中看到一些答案

有没有办法在activity里面的attachBaseContext方法中得到这个WrapContextclass?

只要将 Context 附加到您的应用程序,您就可以使用 entry pointApplicationComponent 获取依赖项。幸运的是,这样的上下文被传递到 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))
    }