在2023年,以编程方式更改应用程序区域设置的正确解决方案是什么?我尝试过不同的方法,但都不起作用。这是我找到的解决方案之一,但它不起作用。object LocaleHelper {
fun setLocale(context: Context, language: String): Context {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
updateResources(context, language)
} else {
updateResourcesLegacy(context, language)
}
}
private fun updateResources(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val configuration = Configuration(context.resources.configuration)
configuration.setLocale(locale)
return context.createConfigurationContext(configuration)
}
private fun updateResourcesLegacy(context: Context, language: String): Context {
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.resources
val configuration = resources.configuration
configuration.locale = locale
resources.updateConfiguration(configuration, resources.displayMetrics)
return context
}
}
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(LocaleHelper.setLocale(newBase, "kk"))
}
val newContext = LocaleHelper.setLocale(this, "kk")
ActivityCompat.recreate(this)
参考资料中有翻译成其他语言的版本。请告诉我如何更改应用程序中的语言环境
2条答案
按热度按时间cbeh67ev1#
我认为这是一个可能的解决办法。
在您的活动中:
如果希望在运行时切换语言,请不要忘记调用
Activity.recreate()
4nkexdtk2#
试试这个:
public void setLanguage(上下文elContexto,区域设置myLocale){
你叫它:
setLanguage(获取应用程序上下文(),新建区域设置("us"));
然后,重置应用程序。