Android: Disable emoji on keyboard
Sometimes in client-server applications backend can not accept emoji, in this case mobile developers have to restrict user from entering them. While it is impossible to hide them from keyboard, we still can suppress emojis. For this Android’s InputFilter class will be used.
Java:
private void disableEmojiInTitle() {
InputFilter emojiFilter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int index = start; index < end - 1; index++) {
int type = Character.getType(source.charAt(index));
if (type == Character.SURROGATE) {
return "";
}
}
return null;
}
}; editText.setFilters(new InputFilter[]{ emojiFilter });
}
Kotlin:
private fun disableEmojiInTitle() {
val emojiFilter = InputFilter { source, start, end, dest, dstart, dend ->
for (index in start until end) {
val type = Character.getType(source[index])
when (type) {
'*'.toInt(),
Character.OTHER_SYMBOL.toInt(),
Character.SURROGATE.toInt() -> {
return@InputFilter ""
}
Character.LOWERCASE_LETTER.toInt() -> {
val index2 = index + 1
if (index2 < end && Character.getType(source[index + 1]) == Character.NON_SPACING_MARK.toInt())
return@InputFilter ""
}
Character.DECIMAL_DIGIT_NUMBER.toInt() -> {
val index2 = index + 1
val index3 = index + 2
if (index2 < end && index3 < end &&
Character.getType(source[index2]) == Character.NON_SPACING_MARK.toInt() &&
Character.getType(source[index3]) == Character.ENCLOSING_MARK.toInt()
)
return@InputFilter ""
}
Character.OTHER_PUNCTUATION.toInt() -> {
val index2 = index + 1
if (index2 < end && Character.getType(source[index2]) == Character.NON_SPACING_MARK.toInt()) {
return@InputFilter ""
}
}
Character.MATH_SYMBOL.toInt() -> {
val index2 = index + 1
if (index2 < end && Character.getType(source[index2]) == Character.NON_SPACING_MARK.toInt())
return@InputFilter ""
}
}
}
return@InputFilter null
} editText.filters = arrayOf(emojiFilter)
}
Character.SURROGATE here stands for emojis, as according to documentation it corresponds to
General category “Cs” in the Unicode specification.
If you have any other InputFilter to attach to your EdiText, don’t forget to include them in the final array of filters.