我需要SharedPreferences在attachBaseContext我的活动中访问我的实例(所以我可以在那里设置语言环境),但注入的SharedPreferences实例在那里不可用,因为注入发生在调用onCreate后运行的方法中attachBaseContext。我正在使用 dagger2 进行依赖注入。
知道如何避免创建新SharedPreferences实例吗?
编辑:
好的,所以我认为问题是我试图过多地使用匕首,我认为在这种情况下它根本不合适。在attachBaseContext每个活动的我有更新的语言环境,我这个提取更新逻辑到LocaleManager其需要访问SharedPreferences实例和Context我进去attachBaseContext。该SharedPreferences实例已经在 中AppModule,但我仍然无法将@Inject其添加到attachBaseContext调用之前的活动中,因为活动的注入发生在 之后attachBaseContext。
lae*_*ger -2
只要你可以访问你的,Component你就可以添加一个提供方法
@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {
fun inject(myActivity: MyActivity)
fun sharedPreferences(): SharedPreferences
...
}
Run Code Online (Sandbox Code Playgroud)
然后SharedPreferences直接通过以下方式访问您的Component:
class MyActivity : AppCompatActivity() {
override fun attachBaseContext(newBase: Context) {
val sharedPreferences = component.sharedPreferences()
...
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
component.inject(this)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1169 次 |
| 最近记录: |