如何更改片段的语言运行时

How to change language runtime for fragment

我正在为单一 Activity 架构使用 navigation component。我正在尝试在运行时更改我的应用程序的语言,我正在使用 article 来这样做。

所以我有以下文件:

RuntimeLocaleChanger

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

主要Activity

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

总感觉少了点什么,却又想不起来

我找到了解决方案:

MainActivity:

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