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

前端 未结 4 1052
青春惊慌失措
青春惊慌失措 2021-02-14 02:56

According to the Java reference, Locale.getLanguage() is supposed to return the 2-letters lowercase ISO code of the language (e.g. en), while get

4条回答
  •  无人及你
    2021-02-14 03:01

    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.

提交回复
热议问题