配置更改后的 Koin 更新 Android 上下文

Koin Update Android Context After Configuration Changed

我正在开发一个支持多种语言的应用程序,因此当用户更改语言时,我们会启动带有 Intent.FLAG_ACTIVITY_CLEAR_TOPFLAG_ACTIVITY_CLEAR_TASKFLAG_ACTIVITY_NEW_TASK 标志的 activity然后完成语言 activity.

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 contextAppResources class 开始已经用旧 context 初始化了。 所以任何解决这个问题的建议。

koin中的androidContext()通常是ApplicationContext.

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

您需要在 factory 中使用 Configuration 覆盖来包装应用程序上下文。例如。像

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