Aag1189
Aag1189

Reputation: 197

Android EditText detect emoji entered

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.

  1. 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?

  2. 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

Answers (1)

Aag1189
Aag1189

Reputation: 197

Finally, I found an answer and sharing it for others !

  1. Emojis/Different language characters called as Graphemes are saved as Unicode.

  2. 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

Related Questions