android - 配置更改后 Koin 更新 Android 上下文
问题描述
我正在开发一个支持多种语言的应用程序,因此当用户更改语言时,我们使用 、 和标志启动启动活动Intent.FLAG_ACTIVITY_CLEAR_TOP
,FLAG_ACTIVITY_CLEAR_TASK
然后FLAG_ACTIVITY_NEW_TASK
完成语言活动。
Intent mIntent = new Intent(this, SplashActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mIntent);
finish();
我们创建了包装类来包装应用程序资源
class AppResources(private val context: Context): IAppResources {
override fun getString(resId: Int): String {
Logger.i("Current locale language is: ${context.resources.configuration.locale.language}")
return context.getString(resId)
}
override fun getStringArray(resId: Int): Array<String> {
Logger.i("Current locale language is: ${context.resources.configuration.locale.language}")
return context.resources.getStringArray(resId)
}
}
然后我们像这样使用 Koin 注入这个类
factory<IAppResources> {
Logger.i("Current androidContext language is: ${androidContext().resources.configuration.locale.language}")
AppResources(androidContext())
}
问题是,当我们从资源中获取字符串值时,我们得到了错误的本地化,因为 Koin 已经从早先的 android 开始,context
并且AppResources
类已经用 old 初始化context
。所以任何解决这个问题的建议。
解决方案
in koinandroidContext()
通常是Application
Context
.
我相信您为多语言支持而拥有的配置覆盖代码仅适用于Activity
.
您需要Configuration
在factory
. 例如像
factory<IAppResources> {
val original = androidContext()
val config = Configuration().apply {
setTo(original.resources.configuration)
setLocale(yourLocale)
}
return@factory AppResources(original.createConfigurationContext(config))
}
推荐阅读
- html - Vuetify v-data-table 具有固定的页眉和页脚以及可滚动的正文
- react-native - 无法读取 react-native-image-picker 上未定义的属性“showimagepicker”
- java - 根据查找表添加列表对象中不存在的值
- angular - PrimeNg GlobalFilter :在第一列中找到匹配项后停止搜索(不在后续列中查找值)
- java - 在 PathParam 中使用 PathSegment 测试 POST 请求时断言失败
- python - FileNotFoundError: [Errno 2] 没有这样的文件或目录 (Heroku)
- azure-devops-rest-api - 访问控制条目 - 我在哪里可以获得“令牌”
- bash - 从 git 下载文件的所有版本
- html - 我无法更改从 Google 字体复制的字体样式的字体大小
- javascript - 为什么当我调用我的 api 时我的 json 对象中的空值键被删除