Kotlin - 如何更改语言环境
Kotlin - How to change the locale
我正在尝试使用以下代码使用 Kotlin 更改应用程序语言,但这段代码不起作用。谁能告诉我哪里做错了?
BaseFragment.kt
open fun setLocale(lang: String, redirectActivity: Boolean, activity: Activity?){
if(activity != null) {
val configuration = resources.configuration
val locale = Locale(lang)
configuration.setLocale(locale)
configuration.setLayoutDirection(locale)
activity.createConfigurationContext(configuration)
val sharedPref: SharedPreferences =
activity.getSharedPreferences(getString(R.string.app_name), 0)
val editor = sharedPref.edit()
editor.putString("lang", lang)
editor.apply()
activity.finish()
startActivity(activity.intent.putExtra("redirectActivity", redirectActivity))
}
}
LanguageFragment.kt
BaseFragment.setLocale(newLang, true, activity)
需要设置默认区域设置,然后需要更新资源以重新创建视图。此外,对于低于 Android N 的构建版本,您还需要更新资源配置,如下所示:
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.resources
val configuration = resources.configuration
configuration.locale = locale
configuration.setLayoutDirection(locale)
resources.updateConfiguration(configuration, resources.displayMetrics)
这里是demo working version with one button to save the language in shared preference (as the given code snippet does) and recreate with the updated Local. Feel free to use the LocaleHelper utility class and call it like showed in its MainActivity,如果有帮助的话:
LocaleHelper().setLocale(this@MainActivity, "en")
recreate()
我正在尝试使用以下代码使用 Kotlin 更改应用程序语言,但这段代码不起作用。谁能告诉我哪里做错了?
BaseFragment.kt
open fun setLocale(lang: String, redirectActivity: Boolean, activity: Activity?){
if(activity != null) {
val configuration = resources.configuration
val locale = Locale(lang)
configuration.setLocale(locale)
configuration.setLayoutDirection(locale)
activity.createConfigurationContext(configuration)
val sharedPref: SharedPreferences =
activity.getSharedPreferences(getString(R.string.app_name), 0)
val editor = sharedPref.edit()
editor.putString("lang", lang)
editor.apply()
activity.finish()
startActivity(activity.intent.putExtra("redirectActivity", redirectActivity))
}
}
LanguageFragment.kt
BaseFragment.setLocale(newLang, true, activity)
需要设置默认区域设置,然后需要更新资源以重新创建视图。此外,对于低于 Android N 的构建版本,您还需要更新资源配置,如下所示:
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.resources
val configuration = resources.configuration
configuration.locale = locale
configuration.setLayoutDirection(locale)
resources.updateConfiguration(configuration, resources.displayMetrics)
这里是demo working version with one button to save the language in shared preference (as the given code snippet does) and recreate with the updated Local. Feel free to use the LocaleHelper utility class and call it like showed in its MainActivity,如果有帮助的话:
LocaleHelper().setLocale(this@MainActivity, "en")
recreate()