show emoticon using Spannable on a text view

2019-01-24 19:41发布

问题:

I need to show my emoticon on a text view.

private HashMap<String, Integer> emoticons = new HashMap<String, Integer>();

emoticons.put(":-)", R.drawable.f01);
emoticons.put(":P", R.drawable.f02);
emoticons.put(":D", R.drawable.f03);

Now suppose I have a EditText and I am typing ":-)" in it on click on a button I want to send this to a TextView where it will show the corresponding resource. In this case f01.

How do I do this ?

回答1:

// try this
textview.setText(getSmiledText(text.toString()));

public Spannable getSmiledText(String text) {
        SpannableStringBuilder builder = new SpannableStringBuilder(text);
        if (emoticons.size() > 0) {
            int index;
            for (index = 0; index < builder.length(); index++) {
                if (Character.toString(builder.charAt(index)).equals(":")) {
                    for (Map.Entry<String, Integer> entry : emoticons.entrySet()) {
                        int length = entry.getKey().length();
                        if (index + length > builder.length())
                            continue;
                        if (builder.subSequence(index, index + length).toString().equals(entry.getKey())) {
                            builder.setSpan(new ImageSpan(getContext(), entry.getValue()), index, index + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                            index += length - 1;
                            break;
                        }
                    }
                }
            }
        }
        return builder;
    }