![](/img/trans.png)
[英]Android : Using Koin How we can inject Activity context into a Class
[英]Koin Update Android Context After Configuration Changed
我正在开发一个支持多种语言的应用程序,因此当用户更改语言时,我们使用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 来包装应用程序资源
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 注入这个 class
factory<IAppResources> {
Logger.i("Current androidContext language is: ${androidContext().resources.configuration.locale.language}")
AppResources(androidContext())
}
问题是,当我们从资源中获取字符串值时,我们得到了错误的本地化,因为 Koin 已经从之前的 android context
开始,而AppResources
class 已经用旧的context
初始化。 所以任何解决这个问题的建议。
koin 中的androidContext()
通常是一个Application
Context
。
我相信您为多语言支持而拥有的配置覆盖代码仅适用于Activity
。
您需要在factory
中使用您的Configuration
覆盖包装应用程序上下文。 例如像
factory<IAppResources> {
val original = androidContext()
val config = Configuration().apply {
setTo(original.resources.configuration)
setLocale(yourLocale)
}
return@factory AppResources(original.createConfigurationContext(config))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.