android - 更改应用程序语言

标签 android kotlin setlocale

我正在尝试在运行时更改我的应用程序语言。我检查了几篇文章,我的代码现在看起来像:

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/

相关文章:

java - 如何在从 xml 解析中选择的微调器上显示/烘烤字符串数组的相关项

android - 以编程方式触发 MediaStore 的重新扫描

android - Jetpack 撰写 : Update composable when list changes

android - 如何在不重新创建 Activity 的情况下更改 Android 应用程序中的语言?

android - 存在监听器无法在 asmack 中工作

php - 异常 - 获取请求结果在发布请求 Volley 后未更新

kotlin - kotlin-检查editText内容是否已被用户或以编程方式修改

android - windowSoftInputMode : adjustResize doesn't work properly for numeric keyboard, 当键盘提示文本时

c - 在 C 程序中打印日文字符

linux - float 在 perl 的德语语言环境中不是逗号分隔的