【问题标题】:Koin Update Android Context After Configuration Changed配置更改后 Koin 更新 Android 上下文
【发布时间】:2019-10-31 12:52:08
【问题描述】:

我正在开发一个支持多种语言的应用程序,因此当用户更改语言时,我们会使用 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 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 contextAppResources 类开始,已经用旧的 context 初始化。 所以有任何解决这个问题的建议。

【问题讨论】:

    标签: android kotlin dependency-injection koin onconfigurationchanged


    【解决方案1】:

    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))
    }
    

    【讨论】:

    • 配置已更改成功问题是Koin androidContext()没有更改,因为我们启动Koin的Application.onCreate()在配置更改后没有被调用。
    • 是的,这就是为什么您也需要在 koin factory 中应用配置更改。就我个人而言,我不会使用任何类型的应用程序上下文来访问 UI 资源(而是使用 Activity 而不是在 koin 中使用它),但考虑一下,你可能对字符串资源没问题。
    • 在您编辑答案后我明白了您的意思,这就是我所做的factory(named(LOCALIZED_CONTEXT)) { ApplyLanguage().applyLanguage(androidContext(), get&lt;PreferenceDataSource&gt;().getCurrentLanguage()) } 然后factory&lt;IAppResources&gt; { AppResources(get(named(LOCALIZED_CONTEXT))) }
    猜你喜欢
    • 2018-03-15
    • 2012-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    相关资源
    最近更新 更多