Why does Locale.getDefault().getLanguage() in Android return the display name instead of the language code?

这一生的挚爱 提交于 2019-12-21 03:57:08

问题


According to the Java reference, Locale.getLanguage() is supposed to return the 2-letters lowercase ISO code of the language (e.g. en), while getDisplayLanguage() is the method for obtaining the readable name (e.g. English).

So how comes that the following code in Android:

Locale.getDefault().getLanguage()

returns English or Español instead of en and es????

I'm completely puzzled...


回答1:


Use

getResources().getConfiguration().locale.getLanguage()

and it will work just fine even though I would consider your observed behaviour a bug worth reporting..




回答2:


I've figured it out. This happened because I had previously called Locale.setDefault() and passed it a Locale which in turn I had created by erroneously passing it the whole language name (I took the language from a preference setting and I mistakenly picked the label of the entry instead of the value).

That is, I did:

String lang= //... here I assigned "English" while I thought
             //    I was assigning it "en"
Locale locale=new Locale(lang);
Locale.setDefault(locale);       // (*)

// and later
Locale.getLocale().getLanguage();   //returns "english"

So when I queried for the default locale, it actually was the locale I had created whose language code I had erroneously set to "english".

There are a couple of funny things, though:

  1. The line (*) actually works and actually does change the locale to English (or to Spanish when I used "Spanish"), that is, setDefault() seems to accept a "malformed" locale and even understands it. But it doesn't fix it.
  2. Note I used uppercase English when wrongly setting the locale, but at the end it returns "english" all lowercase.



回答3:


I don't know why this issue appears, but another standard for languages is the ISO3 code. You can call Locale.getDefault().getISO3Language() and it should return "eng" or "esp".




回答4:


Android is returning the readable names instead of the codes.

Locale.getDefault() has the string. So if you call any prints or Logs on that it'll work... meaning Locale.getDefault().toString() has your locale code.



来源:https://stackoverflow.com/questions/8747423/why-does-locale-getdefault-getlanguage-in-android-return-the-display-name-in

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