我尝试使用以下代码段使用 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))
}
}
语言片段.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 工作版本,其中一个按钮可将语言保存在共享首选项中(如给定的代码片段所示)并使用更新后的本地重新创建。请随意使用 LocaleHelper 实用程序类并像其 MainActivity 中所示那样调用它,如果有帮助的话:
LocaleHelper().setLocale(this@MainActivity, "en")
recreate()
在应用程序中更改语言的新方法。
val languageTag = "ur"
AppCompatDelegate.setApplicationLocales(
LocaleListCompat.create(Locale.forLanguageTag(languageTag))
)