Get Emoji Count In String

前端 未结 5 1730
暗喜
暗喜 2021-01-15 17:01

I would like to find how many emojis the user has input into an EditText. If the user only enters emojis, and uses 3 or less, I want to be able to display that

5条回答
  •  迷失自我
    2021-01-15 17:24

    Another approach would be to take advantage of EmojiCompat. This code presumes you initialized EmojiCompat when your app was starting up. The basic idea here is to have EmojiCompat process your CharSequence, inserting instances of EmojiSpan wherever any emoji appear, and then examine the results, returning a count of the EmojiSpan instances in the processed Spannable.

    public static int getEmojiCount(CharSequence charSequence) {
        int count = 0;
        CharSequence processed = EmojiCompat.get().process(charSequence, 0, charSequence.length() -1, Integer.MAX_VALUE, EmojiCompat.REPLACE_STRATEGY_ALL);
        if (processed instanceof Spannable) {
            Spannable spannable = (Spannable) processed;
            count = spannable.getSpans(0, spannable.length() - 1, EmojiSpan.class).length;
        }
        return count;
    }
    

    Do not forget to add dependency in app gradle:

    implementation 'androidx.emoji:emoji:1.1.0'
    

提交回复
热议问题