在 Android 中以编程方式更改应用程序语言 [英] Change app language programmatically in Android

查看:28
本文介绍了在 Android 中以编程方式更改应用程序语言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to change the language of an app programmatically while still using Android resources?

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

If not, is it possible to request a resource in an specific language?

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

I would like to let the user change the language of the app from the app.

推荐答案

这是可能的.您可以设置语言环境.但是,我不建议这样做.我们在早期阶段就尝试过,它基本上是在与系统作斗争.

It's possible. You can set the locale. However, I would not recommend that. We've tried it at early stages, it's basically fighting the system.

我们对更改语言有相同的要求,但决定接受 UI 应与手机 UI 相同的事实.它是通过设置语言环境来工作的,但是太有问题了.根据我的经验,每次进入活动(每个活动)时都必须设置它.如果你仍然需要这个,这里有一个代码(同样,我不推荐)

We have the same requirement for changing the language but decided to settle to the fact that UI should be same as phone UI. It was working via setting locale but was too buggy. And you have to set it every time you enter activity (each activity) from my experience. here is a code if you still need this (again, I don't recommend that)

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);

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

If you have language specific content - you can change that base on the setting.

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 个小写字母
  • 这篇关于在 Android 中以编程方式更改应用程序语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆