【问题标题】:Can't change language in Android device无法在 Android 设备中更改语言
【发布时间】:2014-01-11 14:39:13
【问题描述】:

我正在尝试在我的应用中更改设备的语言。我有这个代码:

Locale locale = new Locale("en_US"); 
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getApplicationContext().getResources().updateConfiguration(config, null);
Log.i("some","Well, I tried!");

但是这段代码不会改变我设备的状态,并且在 LogCat 中我可以看到“嗯,我试过了”消息。这种奇怪行为的可能原因是什么?

【问题讨论】:

    标签: android


    【解决方案1】:

    编辑这一行

    getApplicationContext().getResources().updateConfiguration(config, null);
    

    像这样:

    context.getApplicationContext().getResources().updateConfiguration(config, null);
    

    【讨论】:

    【解决方案2】:

    如果您是因为 2021 年夏季之后的构建语言问题来到这里,那可能与您的代码无关。我们遇到了同样的问题,问题在于新的捆绑包 (.aab) 要求(自 2021 年夏季起要求)。

    使用 app bundle,设备只下载运行您的应用所需的代码和资源。因此,对于语言资源,用户的设备只会下载与设备设置中当前选择的一种或多种语言相匹配的应用语言资源。 Read further

    基本上,如果设备不支持该语言,则不会下载该语言文件。有两种方法可以解决:

    选项 1(最简单):只需禁用捆绑优化

    将此添加到您的 build.gradle 文件中:

    android {
        bundle {
            language {
                enableSplit = false
            }
        }
    // ...
    // Other configuration
    }
    

    选项 2:按需下载语言文件

    使用here描述的方法。

    如何调试

    在应用这些方法之前,

    1. 删除应用
    2. 在设备设置中添加新语言
    3. 再次下载应用

    如果应用程序支持新语言,那么问题肯定是包优化,上述解决方案将起作用。

    【讨论】:

      【解决方案3】:

      手动更改应用程序区域设置。

      您需要使用以下代码设置区域设置。

      Locale locale = new Locale("AR"); // AR here is for arabic
      Locale.setDefault(locale);
      Configuration config = new Configuration();
      config.locale = locale;
      getBaseContext().getResources().updateConfiguration(config, 
      getBaseContext().getResources().getDisplayMetrics());
      

      确保在调用“setContentView”方法之前在活动“onCreate”方法中设置它。

      另请参阅为所需语言指定了资源文件。

      【讨论】:

      • 我是否需要为我的每项活动都这样做?
      • 这只会更改您活动的区域设置。它不会更改设备区域设置。
      猜你喜欢
      • 2015-11-17
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多