Detecting if a character in a String is an emoticon (using Android)

后端 未结 3 1187
庸人自扰
庸人自扰 2021-01-05 07:54

Like the title says. I want to find out if a given java String contains an emoticon.

I can\'t use Character.UnicodeBlock.of(char) == Character.UnicodeBlock.EMO

3条回答
  •  臣服心动
    2021-01-05 08:14

    Four years later...

    At this time, it might make more sense 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.

    public static boolean containsEmoji(CharSequence charSequence) {
        boolean result = false;
        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;
            result = spannable.getSpans(0, spannable.length() - 1, EmojiSpan.class).length > 0;
        }
        return  result;
    }
    

    If you want to collect a list of the unique emoji that appear within a given CharSequence, you could do something like this, iterating over the results of getSpans() and finding the start and end of each span to capture the emoji discovered by EmojiCompat:

    @NonNull
    public static List getUniqueEmoji(CharSequence charSequence) {
        Set emojiList = new HashSet<>();
        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;
    
            EmojiSpan[] emojiSpans = spannable.getSpans(0, spannable.length() - 1, EmojiSpan.class);
            for (EmojiSpan emojiSpan : emojiSpans) {
                int spanStart = spannable.getSpanStart(emojiSpan);
                int spanEnd = spannable.getSpanEnd(emojiSpan);
                CharSequence emojiCharSequence = spannable.subSequence(spanStart, spanEnd);
                emojiList.add(String.valueOf(emojiCharSequence));
            }
        }
        return emojiList.size() > 0 ? new ArrayList<>(emojiList) : new ArrayList();
    }
    

提交回复
热议问题