首页 > 解决方案 > 配置更改后 Koin 更新 Android 上下文

问题描述

我正在开发一个支持多种语言的应用程序,因此当用户更改语言时,我们使用 、 和标志启动启动活动Intent.FLAG_ACTIVITY_CLEAR_TOPFLAG_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。所以任何解决这个问题的建议。

标签: androidkotlindependency-injectionkoinonconfigurationchanged

解决方案


in koinandroidContext()通常是Application Context.

我相信您为多语言支持而拥有的配置覆盖代码仅适用于Activity.

您需要Configurationfactory. 例如像

factory<IAppResources> {
    val original = androidContext()
    val config = Configuration().apply {
        setTo(original.resources.configuration)
        setLocale(yourLocale)
    }
    return@factory AppResources(original.createConfigurationContext(config))
}

推荐阅读