我正在尝试在运行时更改我的应用程序语言。我检查了几篇文章,我的代码现在看起来像:
if(position == 0){//Position 0 of an array to select the language
val locale = Locale("es_ES")
val config = applicationContext.resources.configuration
config.setLocale(locale)
applicationContext.createConfigurationContext(config)
}
我有一个 values-es 目录,其中有我自己的 strings.xml 文件,其中包含已翻译的字符串。无论如何,它似乎没有改变任何东西。
我重复一遍,我尝试并检查了 Stack Overflow 中的很多帖子,但我不知道我在哪里失败了。 在此先感谢,由于我的英语不好,我愿意接受任何问题。
第二次尝试:
我一直在尝试,现在我的代码如下所示:
val locale = Locale("es")
Locale.setDefault(locale)
val config = applicationContext.resources.configuration
config.setLocale(locale)
applicationContext.resources.configuration.setTo(config)
Log.d("Configuration",config.toString())
Log.d("Language",config.locales.toLanguageTags())
调试信息是:
D/Configuration: {1.0 310mcc260mnc [es] ldltr sw411dp w683dp h387dp 420dpi nrml land finger qwerty/v/v -nav/h winConfig={ mBounds=Rect(0, 0 - 1794, 1080) mAppBounds=Rect(0, 0 - 1794, 1080) mWindowingMode=fullscreen mActivityType=undefined} s.40}
D/Language: es
但我的字符串没有改变,我的应用程序继续使用 strings(en) 文件。
最佳答案
请试试这段代码
String languageToLoad = "es"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
Intent refresh = new Intent(DashboardActivity.this, DashboardActivity.class);
startActivity(refresh);
finish();
关于android - 更改应用程序语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56408853/