Reputation: 197
I am working on detecting emojis in editText. When I enter an emoji in EditText, when I do editText.getText().toString() it returns the string without emoji inside it. When I do editText.length(), the length includes the length of emojis as well.
I even tried adding a textWatcher to EditText to read the characters that is entered.
TextWatcher watch = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Log.i(" Print", " s= "+s);
}
@Override
public void afterTextChanged(Editable s) {
}
};
Still its the same, only characters, digits, spaces, punctuations can be seen, But no emoji.
I want to understand how is Emoji present inside EditText. Are emojis stored as ImageSpans or Unicode ? How do I detect if there is an emoji inside editText?
I also want to count 1 emoji entered as 1 character. The idea here is to treat every Emoji entered as 1 character since different emojis are of different length.
Upvotes: 1
Views: 1193
Reputation: 197
Finally, I found an answer and sharing it for others !
Emojis/Different language characters called as Graphemes are saved as Unicode.
java.text.BreakIterator does the magic. Pass the editText.getText().toString() to below function and get the length.
import java.text.BreakIterator;
int getGraphemeCount(String s) {
BreakIterator boundary = BreakIterator.getCharacterInstance(Locale.ROOT);
boundary.setText(s);
boundary.first();
int result = 0;
while (boundary.next() != BreakIterator.DONE) {
++result;
}
return result;
}
Example : getGraphemeCount("π¨βπ©βπ¦βπ¦π¨βπ©βπ§βπ¦π¨βπ©βπ§θ―»εζ±εε¦δΈζ") returns length as 10.
Upvotes: 4