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

时间:2012-10-09 07:40:26

标签: android image spannablestring

This is :) and want to :) replace with :D new image.

我有这种类型的字符串,我从EditTextbox.NOw得到我想用image1和“:D”替换所有“:)”与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;
    }

2 个答案:

答案 0 :(得分:0)

您需要做的只是在运行时加载图像,加载图像并保存在变量中,并在运行时分配图像。 FYI字符不是问题,我之前遇到同样的问题我把它理解为接触点问题,但问题是加载图像。

答案 1 :(得分:0)

检查一下:

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

    for (Entry<String, Integer> entry : EmoticonsCode.emoticons_code.entrySet())
    {
        try {
           int length = entry.getKey().length();
           for ( index = s.indexOf(entry.getKey()); index >= 0; index = s.indexOf(entry.getKey(), index + 1))
           {
                System.out.println(index);
                builder.setSpan(new ImageSpan(context, entry.getValue()), index, index + length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
           }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
   }
   return builder;
}