Java 如何为 Android 应用设置默认语言?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23838646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:30:59  来源:igfitidea点击:

How To Set Default Language for Android app?

javaandroid

提问by user3053246

I've created an app in two languages. The second one (english), is used when user's default system language is english. If it's not, then the first one is used.

我用两种语言创建了一个应用程序。第二个(英语),当用户的默认系统语言是英语时使用。如果不是,则使用第一个。

I want to set the second language (that's english) as a DEFAULT language, which means that when user opens my app and his system language is not the first one, nor English, the English language will appear as a default one.

我想将第二种语言(即英语)设置为默认语言,这意味着当用户打开我的应用程序并且他的系统语言不是第一种语言,也不是英语时,英语将显示为默认语言。

I tried:

我试过:

    Locale locale = new Locale("en_US");
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale;
    context.getApplicationContext.getResources().updateConfiguration(config, null);

But got "context cannot be resolved" error everytime.. Is this piece of code right or..?

但是每次都出现“上下文无法解决”错误..这段代码是对的还是..?

回答by ashishduh

You should define all languages you support using res folders, i.e res/values, res/values-en, res/values-fr. The system will take care of everything else, you don't need any code.

您应该使用 res 文件夹定义您支持的所有语言,即res/valuesres/values-enres/values-fr。系统会处理其他一切,您不需要任何代码。

回答by MJ93

If you are in an activity you can do:

如果您正在参加一项活动,您可以:

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

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

...to fix your error. Otherwise you need to pass in the context.

...修复你的错误。否则,您需要传入上下文。

Make sure you add the parenthesis at the end of getApplicationContext(). You didn't do so in your code.

确保在末尾添加括号getApplicationContext()。您没有在代码中这样做。

回答by user3053246

Okay,

好的,

to make everything clear, I realized res/valuesis a DEFAULT directory and the others are just "in case of language". So everything I had to do was to switch the english to /res/values and the other language goes to res/values-es

为了让一切都清楚,我意识到res/values是一个 DEFAULT 目录,而其他目录只是“以防万一”。所以我所要做的就是将英语切换到 /res/values 而另一种语言转到res/values-es