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

我有这种类型的字符串,这是我从 EditTextbox 获得的。现在我想用 image1 替换所有“:)”,用 image2 替换“:D”。我想做类似 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;
    }
4

2 回答 2

2

检查这个:

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;
}
于 2014-06-04T10:31:33.060 回答
0

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

于 2012-10-09T07:58:14.063 回答