首页 > 解决方案 > 如何更改片段的语言运行时

问题描述

我正在使用navigation component单活动架构。我正在尝试在运行时更改我的应用程序的语言,我正在使用这篇文章来这样做。

所以我有以下文件:

运行时LocaleChanger

object RuntimeLocaleChanger {

    fun wrapContext(context: Context): Context {

        val savedLocale = Locale(PreferencesHelper.readLanguageCode()) // load the user language from SharedPreferences

        // as part of creating a new context that contains the new locale we also need to override the default locale.
        Locale.setDefault(savedLocale)

        // create new configuration with the saved locale
        val newConfig = Configuration()
        newConfig.setLocale(savedLocale)

        return context.createConfigurationContext(newConfig)
    }

    fun overrideLocale(context: Context) {

        val savedLocale = Locale(PreferencesHelper.readLanguageCode()) // load the user language from SharedPreferences

        // as part of creating a new context that contains the new locale we also need to override the default locale.
        Locale.setDefault(savedLocale)

        // create new configuration with the saved locale
        val newConfig = Configuration()
        newConfig.setLocale(savedLocale)

        // override the locale on the given context (Activity, Fragment, etc...)
        context.createConfigurationContext(newConfig)

        // override the locale on the application context
        if (context != context.applicationContext) {
            context.applicationContext.run { createConfigurationContext(newConfig) }
        }
    }
}

应用

override fun attachBaseContext(base: Context) {
    super.attachBaseContext(RuntimeLocaleChanger.wrapContext(base))
}

主要活动

override fun attachBaseContext(base: Context) {
    super.attachBaseContext(RuntimeLocaleChanger.wrapContext(base))
}

override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    RuntimeLocaleChanger.overrideLocale(this)
}

我改变这样的语言:

// PreferencesHelper.readLanguageCode() is the language code saved in SharedPreferences
if(PreferencesHelper.readLanguageCode() == "en") {
    PreferencesHelper.writeLanguageCode("he")
} else {
    PreferencesHelper.writeLanguageCode("en")
}

我觉得有什么东西不见了,但我无法理解它

标签: androidkotlinandroid-architecture-navigation

解决方案


我找到了一个解决方案:

主要活动

override fun onAttachedToWindow() {
    super.onAttachedToWindow()
    // Will give the direction of the layout depending of the Locale you've just set
    window.decorView.layoutDirection = Locale.getDefault().layoutDirection
}

分段

// PreferencesHelper.readLanguageCode() is the language code saved in SharedPreferences
if(PreferencesHelper.readLanguageCode() == "en") {
    PreferencesHelper.writeLanguageCode("he")
} else {
    PreferencesHelper.writeLanguageCode("en")
}
(activity as? MainActivity)?.recreate()

我还找到了一个不错的图书馆locale-helper


推荐阅读