繁体   English   中英

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

[英]Koin Update Android Context After Configuration Changed

我正在开发一个支持多种语言的应用程序,因此当用户更改语言时,我们使用Intent.FLAG_ACTIVITY_CLEAR_TOPFLAG_ACTIVITY_CLEAR_TASKFLAG_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM