Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace the characters with Image in string and then set to Textview

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;
    }
like image 758
Nency Avatar asked Oct 09 '12 07:10

Nency


1 Answers

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;
}
like image 178
Sachin Arora Avatar answered Nov 14 '22 18:11

Sachin Arora