I have seen that since Lollipop
, Android has built in Emoji
flags for different countries. Is it possible to use the devices locale to retrieve the Emoji
flag for that country?
I wanted to insert the Emoji
flag into a TextView
which contains the user's location.
Emoji is a Unicode symbols. Based on the Unicode character table Emoji flags consist of 26 alphabetic Unicode characters (A-Z) intended to be used to encode ISO 3166-1 alpha-2 two-letter country codes (wiki).
That means it is possible to split two-letter country code and convert each A-Z letter to regional indicator symbol letter:
private String localeToEmoji(Locale locale) {
String countryCode = locale.getCountry();
int firstLetter = Character.codePointAt(countryCode, 0) - 0x41 + 0x1F1E6;
int secondLetter = Character.codePointAt(countryCode, 1) - 0x41 + 0x1F1E6;
return new String(Character.toChars(firstLetter)) + new String(Character.toChars(secondLetter));
}
Or in Kotlin, for example (assuming UTF-8):
val Locale.flagEmoji: String
get() {
val firstLetter = Character.codePointAt(country, 0) - 0x41 + 0x1F1E6
val secondLetter = Character.codePointAt(country, 1) - 0x41 + 0x1F1E6
return String(Character.toChars(firstLetter)) + String(Character.toChars(secondLetter))
}
Where 0x41
represents uppercase A
letter and 0x1F1E6
is REGIONAL INDICATOR SYMBOL LETTER A
in the Unicode table.
Note: This code example is simplified and doesn't have required checks related to country code, that could be not available inside the locale.