在 Android 中以编程方式更改应用语言

新手上路,请多包涵

是否可以在仍使用 Android 资源的同时以编程方式更改应用程序的语言?

如果没有,是否可以请求特定语言的资源?

我想让用户从应用程序更改应用程序的语言。

原文由 hpique 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 733
2 个回答

这是可能的。您可以设置区域设置。但是,我不建议这样做。我们已经在早期阶段尝试过,它基本上是在与系统作斗争。

我们对更改语言有相同的要求,但决定接受 UI 应该与手机 UI 相同的事实。它是通过设置语言环境工作的,但是太麻烦了。根据我的经验,每次输入活动(每个活动)时都必须设置它。如果您仍然需要此代码,这是一个代码(同样,我不建议这样做)

 Resources res = context.getResources();
// Change locale settings in the app.
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration conf = res.getConfiguration();
conf.setLocale(new Locale(language_code.toLowerCase())); // API 17+ only.
// Use conf.locale = new Locale(...) if targeting lower versions
res.updateConfiguration(conf, dm);

如果您有特定语言的内容 - 您可以根据设置进行更改。


2020 年 3 月 26 日更新

    public static void setLocale(Activity activity, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);
        Resources resources = activity.getResources();
        Configuration config = resources.getConfiguration();
        config.setLocale(locale);
        resources.updateConfiguration(config, resources.getDisplayMetrics());
    }

  • 注意:语言代码不能有 ‘-’ & 只能是 2 个小写字母

原文由 Alex Volovoy 发布,翻译遵循 CC BY-SA 4.0 许可协议

此功能由 Google 为 Android 13 正式推出(并且也具有向后支持)。 Android 现在允许您为每个应用选择语言。

这里的官方文档 - https://developer.android.com/guide/topics/resources/app-languages

要设置用户的首选语言,您会要求用户在语言选择器中选择区域设置,然后在系统中设置该值:

 // 1. Inside an activity, in-app language picker gets an input locale "xx-YY"
// 2. App calls the API to set its locale
mContext.getSystemService(LocaleManager.class
    ).setApplicationLocales(newLocaleList(Locale.forLanguageTag("xx-YY")));
// 3. The system updates the locale and restarts the app, including any configuration updates
// 4. The app is now displayed in "xx-YY" language

要让用户当前的首选语言显示在语言选择器中,您的应用可以从系统取回值:


// 1. App calls the API to get the preferred locale
LocaleList currentAppLocales =
    mContext.getSystemService(LocaleManager.class).getApplicationLocales();
// 2. App uses the returned LocaleList to display languages to the user

原文由 Mayuri Khinvasara 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题