30

I have a list of language codes (as in "en", "es"...) I need to display in those language like this:

English
Español
Français
Deutsch
日本語

Is there any built-in API to get these in Android or should I map them myself?

Charlie-Blake
  • 10,832
  • 13
  • 55
  • 90
  • 2
    http://developer.android.com/reference/java/util/Locale.html#getDisplayName(java.util.Locale) or http://developer.android.com/reference/java/util/Locale.html#getDisplayLanguage(java.util.Locale) –  Mar 17 '16 at 12:55

1 Answers1

58

The Locale class have a method for this: public String getDisplayLanguage(Locale locale), as the documentation says:

Returns the name of this locale's language, localized to locale. The exact output form depends on whether this locale corresponds to a specific language, script, country and variant.

So you can get language names for locales like this:

String lng = "en";
Locale loc = new Locale(lng);
String name = loc.getDisplayLanguage(loc); // English

lng = "es";
loc = new Locale(lng);
name = loc.getDisplayLanguage(loc); // español

//...
nvi9
  • 1,733
  • 2
  • 15
  • 20
  • This is almost exactly what I needed. I had to capitalize the first letter because "es" returns "español" insead of "Español" but it's almost perfect. Thank you! – Charlie-Blake Mar 18 '16 at 08:43
  • 2
    @razielsarafan it's easy to capitalize: `name = name.substring(0, 1).toUpperCase() + name.substring(1);` – nvi9 Mar 21 '16 at 21:17
  • To get all the country codes: https://stackoverflow.com/a/30028371/3527024 – matteoh Aug 17 '17 at 10:02
  • 3
    Also, I want to additionally mention that Locale needs to be instanced with the language code only in this case. If you try doing this using the language+country code (like for example, `es_MX` - Spanish from Mexico) you will have to do: `Locale auxLocale = new Locale(languageCode, countryCode);` Otherwise it won't work. I'm posting this for anyone to be on the lookout - it took me a bit to realize in my case, since I needed to use language and country codes. Thanks all for your answers! – evaldeslacasa Jun 27 '18 at 15:20
  • Android 9 - it returns country in English – user924 Dec 30 '19 at 10:28