3

I have below code slice to insert a bitmap into an EditText widget. With Android 5.x, it works fine, but with Android 4.x, duplicate images will show after insert one bitmap. Dose anyone know how to fix this with Android 4.x?

    insertPicIntoEditText(getBitmapSpannable(resized_bm, upload_uri));

    private SpannableString getBitmapSpannable(Bitmap pic, String uri_string) {
    SpannableString ss = new SpannableString(uri_string);
    ImageSpan span = new ImageSpan(this, pic);
    ss.setSpan(span, 0, uri_string.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    return ss;
}

    private void insertPicIntoEditText(SpannableString ss) {
    Editable et = mContentEditor.getText();
    int start = mContentEditor.getSelectionStart();
    et.insert(start, ss);
    et.insert(start + ss.length(), "\n");
    mContentEditor.setText(et);
    mContentEditor.setSelection(start + ss.length() + 1);
}
N J
  • 27,217
  • 13
  • 76
  • 96
Jerry
  • 31
  • 1

2 Answers2

3

This was being caused by the height set in setBounds being greater than that of the Bitmap the drawable was created from earlier in the activity. When this occurs there are two things that seem to happen..

First, if the size only slightly (I haven't extensively tested this once I got it working so I'm unsure of exact figures) exceeds the size of the Bitmap then a large blank space is added to the span, this blank space is the same size as the bitmap inserted.

Second, an extra copy of the Drawable is added to the span, directly below the blank space.

The resolution was relatively simple.. Ensure that the Bitmap used to create the Drawable was set to the intended final size before creating the Drawable and calling setBounds.

This may not work in all cases but worked for me and hopefully will be helpful for someone.

0

I also noticed images are repeated if the spannable string has line breaks.