This is :) and want to :) replace with :D new image.
I have this type of string that is i have got from EditTextbox.NOw i want to replace all ":)" with image1 and ":D" with image2.I want to do like string.replaceall(":)",image1) and string.replaceall(":D",image2).So can anybody suggest me how to do this with small code and also better performance.I have write the code and it is working also fine but it takes much time.
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;
}
Check this:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With