Setting application locale to pt_BR programmatically

拟墨画扇 提交于 2019-12-17 16:44:22

问题


I have an application that has support for the Portuguese language, both for Portugal and Brazil regions. I have created a values-pt (containing the Portugal translation) and values-pt-rBR (containing the Brazilian translation). I then tried changing the application language to Potuguese (Portugal) and the application language changes correctly. When I set it to Portuguese (Brazilian) it does not. I tried changing the phone default language to Portuguese (Brazilian) and it still does not work. It works for Portuguese (Portugal) in both cases (programmatically and system). Does anyone know what the problem is? The code for programmatically changing the application's locale is the following:

Locale locale = new Locale(strLocale);
Locale.setDefault(locale);

config.locale = locale;
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());

and strLocale is set to "pt" or "pt_BR" for Portugal and Brazil language respectively.


回答1:


I assume you're targeting Android OS > 2.2, because both Portuguese languages are supported by Android starting at version 2.3+.
I tested it on the emulator, by swapping language & keyboard and having only 1 string different: app_name, so it appeared in application title and it worked just fine.

The only difference is that I named Portugal region values-pt-rPT insead of values-pt.
I didn't test on the fly-relocalization, but I guess it works as well.
I think that when you work with regions, you MUST specify a region for every localization (i.e. fr-rFR for France and fr-rCA for Canada) and can't use the default (pt in your case, or fr in my second example).

This link illustrates the whole thing more deeply.

[EDIT]

When creating a new locale by code, try:

final Locale myLocale = new Locale("pt", "PT");

and

final Locale myLocale = new Locale("pt", "BR");

Here's another page from the reference site.



来源:https://stackoverflow.com/questions/20527164/setting-application-locale-to-pt-br-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!