用字符串中的Image替换字符,然后设置为Textview

Nen*_*ncy 9 android image spannablestring

This is :) and want to :) replace with :D new image.
Run Code Online (Sandbox Code Playgroud)

我有这种类型的字符串,我从EditTextbox.NOW我想用image1替换所有":)"和image2.I"想要做像我一样."我想做像string.replaceall(":)",image1)和string.replaceall(":D",image2).所以任何人都可以建议我如何使用小代码和更好的性能来做到这一点.我已经编写了代码,它工作得很好,但需要很长时间.

textview.setText(getSmiledText(ctx, stringvalue));
private static final HashMap<String, Integer> emoticons = new HashMap<String, Integer>();
    static {
        emoticons.put(":)", R.drawable.j1);
        emoticons.put(":D", R.drawable.j2);}

public static Spannable getSmiledText(Context context, String s) {
        int index;
        SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append(s);

        for (index = 0; index < builder.length(); index++) {
            for (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(context, entry.getValue()),
                            index, index + length,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    index += length - 1;
                    break;
                }
            }
        }
        return builder;
    }
Run Code Online (Sandbox Code Playgroud)

jay*_*jay 0

您需要做的只是提前加载图像,而不是在运行时加载图像并保存在变量中,然后在运行时分配图像。仅供参考,字符不是问题,我之前遇到过同样的问题,我将其理解为接触点问题,但问题是图像加载。