Android Get Country Emoji Flag Использование языка
Я видел, что с Lollipop
у Android встроены флаги Emoji
для разных стран. Можно ли использовать локаль устройств для получения флага Emoji
для этой страны?
Я хотел вставить флаг Emoji
в TextView
, который содержит местоположение пользователя.
Ответы
Ответ 1
Я тоже искал это, но я не думаю, что это возможно.
Посмотрите здесь:
http://developer.android.com/reference/java/util/Locale.html
Нет упоминаний о флажках.
_
В качестве альтернативы вы можете проверить ответ здесь:
Список стран Android с флагами и доступность получения мобильных кодов iso
который может вам помочь.
Ответ 2
Emoji - это символы Unicode. На основе таблицы символов Unicode флаги Emoji состоят из 26 буквенных символов Unicode (AZ), предназначенных для кодирования двухбуквенных кодов ISO 3166-1 alpha-2 (wiki).
Это означает, что можно разделить двухбуквенный код страны и преобразовать каждую букву A-Z в региональную букву символа индикатора:
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));
}
Где 0x41
обозначает прописную букву A
, а 0x1F1E6
- REGIONAL INDICATOR SYMBOL LETTER A
в таблице Unicode.
Примечание. Этот пример кода упрощен и не требует проверок, связанных с кодом страны, которые могут быть недоступны внутри языкового стандарта.
Ответ 3
Основываясь на этом ответе, я написал ниже версию Kotlin, используя функцию расширения.
Я также добавил несколько проверок для обработки неизвестного кода страны.
/**
* This method is to change the country code like "us" into 🇺🇸
* Stolen from /questions/826446/android-get-country-emoji-flag-using-locale/3009217#3009217
* 1. It first checks if the string consists of only 2 characters: ISO 3166-1 alpha-2 two-letter country codes (https://en.wikipedia.org/wiki/Regional_Indicator_Symbol).
* 2. It then checks if both characters are alphabet
* do nothing if it does not fulfil the 2 checks
* caveat: if you enter an invalid 2 letter country code, say "XX", it will pass the 2 checks, and it will return unknown result
*/
fun String.toFlagEmoji(): String {
// 1. It first checks if the string consists of only 2 characters: ISO 3166-1 alpha-2 two-letter country codes (https://en.wikipedia.org/wiki/Regional_Indicator_Symbol).
if (this.length != 2) {
return this
}
val countryCodeCaps = this.toUpperCase() // upper case is important because we are calculating offset
val firstLetter = Character.codePointAt(countryCodeCaps, 0) - 0x41 + 0x1F1E6
val secondLetter = Character.codePointAt(countryCodeCaps, 1) - 0x41 + 0x1F1E6
// 2. It then checks if both characters are alphabet
if (!countryCodeCaps[0].isLetter() || !countryCodeCaps[1].isLetter()) {
return this
}
return String(Character.toChars(firstLetter)) + String(Character.toChars(secondLetter))
}
Выполненный фрагмент кода
Я также включил работающий фрагмент Kotlin, используя Kotlin Playground. Чтобы запустить фрагмент, необходимо:
- нажмите "Показать фрагмент кода"
- нажмите "Запустить фрагмент кода"
- нажмите кнопку воспроизведения в правой верхней части сгенерированной консоли
- прокрутите вниз, чтобы увидеть результат (он скрыт..)
<script src="https://unpkg.com/[email protected]/dist/playground.min.js" data-selector=".code"></script>
<div class="code" style="display:none;">
/**
* This method is to change the country code like "us" into 🇺🇸
* Stolen from /questions/826446/android-get-country-emoji-flag-using-locale/3009217#3009217
* 1. It first checks if the string consists of only 2 characters: ISO 3166-1 alpha-2 two-letter country codes (https://en.wikipedia.org/wiki/Regional_Indicator_Symbol).
* 2. It then checks if both characters are alphabet
* do nothing if it does not fulfil the 2 checks
* caveat: if you enter an invalid 2 letter country code, say "XX", it will pass the 2 checks, and it will return unknown result
*/
fun String.toFlagEmoji(): String {
// 1. It first checks if the string consists of only 2 characters: ISO 3166-1 alpha-2 two-letter country codes (https://en.wikipedia.org/wiki/Regional_Indicator_Symbol).
if (this.length != 2) {
return this
}
val countryCodeCaps = this.toUpperCase() // upper case is important because we are calculating offset
val firstLetter = Character.codePointAt(countryCodeCaps, 0) - 0x41 + 0x1F1E6
val secondLetter = Character.codePointAt(countryCodeCaps, 1) - 0x41 + 0x1F1E6
// 2. It then checks if both characters are alphabet
if (!countryCodeCaps[0].isLetter() || !countryCodeCaps[1].isLetter()) {
return this
}
return String(Character.toChars(firstLetter)) + String(Character.toChars(secondLetter))
}
fun main(args: Array<String>){
println("us".toFlagEmoji())
println("AF".toFlagEmoji())
println("BR".toFlagEmoji())
println("MY".toFlagEmoji())
println("JP".toFlagEmoji())
}
</div>
Ответ 4
Когда я впервые написал этот ответ, я почему-то не заметил, что я работал только на Android через React Native!
В любом случае, здесь мое решение для JavaScript, которое работает с поддержкой ES6 или без нее.
function countryCodeToFlagEmoji(country) {
return typeof String.fromCodePoint === "function"
? String.fromCodePoint(...[...country].map(c => c.charCodeAt() + 0x1f185))
: [...country]
.map(c => "\ud83c" + String.fromCharCode(0xdd85 + c.charCodeAt()))
.join("");
}
console.log(countryCodeToFlagEmoji("au"));
console.log(countryCodeToFlagEmoji("aubdusca"));
Ответ 5
Я использую это так легко.
Получите Юникод из здесь.
Для флага Бангладеш это U+1F1E7 U+1F1E9
Теперь
{...
String flag = getEmojiByUnicode(0x1F1E7)+getEmojiByUnicode(0x1F1E9)+ " Bangladesh";
}
public String getEmojiByUnicode(int unicode){
return new String(Character.toChars(unicode));
}
Это покажет> (флаг Бангладеш) Бангладеш