android - 如何使用 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!!))
}
但我仍然得到同样的错误。我调试了代码,发现方法中applicationContext
为Null。
我在网上搜索,我发现有人在dagger
这里遇到了同样的问题。但是没有公认的答案可以让我在hilt
.
有没有办法在活动内部的方法中获取这个WrapContext
类attachBaseContext
?
解决方案
一旦附加到应用程序,您就可以使用入口点获取依赖项。幸运的是,这样的上下文被传递到:ApplicationComponent
Context
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))
}
推荐阅读
- android - 实现 Apollo 客户端的最佳实践(查询、突变和订阅)
- angular - 在 Android 10+ 中访问硬件序列号?Ionic3/Angular 应用程序
- aws-lambda - 使用无服务器框架和 aws lambda 的带有 aws codepipeline 的 Bitbucket CI/CD 管道获得成功,但不创建 lambda 函数
- c++ - MediaPipe Hands Linux - 程序在尝试获取地标包后冻结
- spring-security - Vault 错误:更正应用程序的类路径,以便包含一个兼容的 org.springframework.vault.support.SslConfiguration 版本
- haskell - 从元组列表中获取函数
- c++ - 这个 C++ 中的主动对象模式示例有什么问题?
- r - 通过比较 R 中的其他两列来选择组
- graphql - 在 GraphQL 中对 Join 表进行批量更新的最佳方法是什么?
- reactjs - 如何加快组件和类的 npm 库的 webpack 重建