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;
}