在 Kotlin 中以编程方式更改语言环境

Ara*_*ami 6 android localization kotlin

我有一些代码可以在 Java 中以编程方式更改语言环境。但是当我的应用程序迁移到 Kotlin 时,我无法再更改语言环境。

例如,Java 中的这段代码效果很好:

public static final void setAppLocale(String language, Activity activity) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        Resources resources = activity.getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.setLocale(new Locale(language));
        activity.getApplicationContext().createConfigurationContext(configuration);
    } else {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);
        Configuration config = activity.getResources().getConfiguration();
        config.locale = locale;
        activity.getResources().updateConfiguration(config,
                activity.getResources().getDisplayMetrics());
    }
}
Run Code Online (Sandbox Code Playgroud)

我在 Kotlin 中尝试了很多代码,但没有一个对我有用。这是我最后一次尝试:

fun changeLanguage(context: Context, language : String) {
    val locale = Locale(language)
    Locale.setDefault(locale)

    val config = context.resources.configuration
    config.setLocale(locale)
    context.createConfigurationContext(config)
    context.resources.updateConfiguration(config, context.resources.displayMetrics)
}
Run Code Online (Sandbox Code Playgroud)

如何在 Kotlin 中更改应用程序的本地?用 Java 编写的旧代码在 Kotlin 应用程序中不起作用。

Sed*_*ush 9

创建一个上下文助手类让我们说

class ApplicationLanguageHelper(base: Context) : ContextThemeWrapper(base, R.style.AppTheme) {
companion object {

    fun wrap(context: Context, language: String): ContextThemeWrapper {
        var context = context
        val config = context.resources.configuration
        if (language != "") {
            val locale = Locale(language)
            Locale.setDefault(locale)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                setSystemLocale(config, locale)
            } else {
                setSystemLocaleLegacy(config, locale)
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                config.setLayoutDirection(locale)
                context = context.createConfigurationContext(config)
            } else {
                context.resources.updateConfiguration(config, context.resources.displayMetrics)
            }
        }
        return ApplicationLanguageHelper(context)
    }

    @SuppressWarnings("deprecation")
    fun setSystemLocaleLegacy(config: Configuration, locale: Locale) {
        config.locale = locale
    }

    @TargetApi(Build.VERSION_CODES.N)
    fun setSystemLocale(config: Configuration, locale: Locale) {
        config.setLocale(locale)
    }
}
Run Code Online (Sandbox Code Playgroud)

}

在您的 Activity 中,您可以覆盖 attachBaseContext

    override fun attachBaseContext(newBase: Context?) {
    super.attachBaseContext(ApplicationLanguageHelper.wrap(newBase!!, "fa"))
}
Run Code Online (Sandbox Code Playgroud)

要更改语言,您可以使用 Spinner 或任何其他首选方式,调用以下方法 OnClick

   private fun changeApplicationLanguage(language:String){
    val sharedPreferencesEditor = sharedPreferences.edit()
    when (language) {
        ENGLISH -> sharedPreferencesEditor?.putString(SELECTED_LANGUAGE, ENGLISH)
        PERSIAN -> sharedPreferencesEditor?.putString(SELECTED_LANGUAGE, PERSIAN)
        PASHTO -> sharedPreferencesEditor?.putString(SELECTED_LANGUAGE, PASHTO)
    }
    sharedPreferencesEditor.putBoolean(LANGUAGE_IS_SELECTED, true)
    sharedPreferencesEditor?.apply()
    recreate()
}
Run Code Online (Sandbox Code Playgroud)

请确保您定义sharedPreferencesSELECTED_LANGUAGEENGLISH等等,consts

const val SELECTED_LANGUAGE = "language"
const val ENGLISH = "en"
const val PERSIAN = "fa"
const val PASHTO = "ps"

 private lateinit var sharedPreferences: SharedPreferences
Run Code Online (Sandbox Code Playgroud)

sharedPreferencesonCreate之后的方法中初始化setContent

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this@Your_Activity_Name)
Run Code Online (Sandbox Code Playgroud)

还可以通过添加以下代码来覆盖基本上下文

 // Overwrite the context
override fun attachBaseContext(newBase: Context?) {
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(newBase)
    val lang = sharedPreferences.getString(SELECTED_LANGUAGE, "en")
    super.attachBaseContext(ApplicationLanguageHelper.wrap(newBase!!, lang!!))
}
Run Code Online (Sandbox Code Playgroud)

我确信这种方法不是最佳解决方案,但是,这可能会有所帮助