Home » Android » android – Replace the characters with Image in string and then set to Textview

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

Posted by: admin June 15, 2020 Leave a comment

Questions:
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;
    }
How to&Answers:

What you need to do is just load the images earlier not at run time, load images and save in variables and just assign the images at run time. FYI characters is not the problem, i came through same issue earlier i understood it as touch points issue, but problem was loading of images.

Answer:

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