ImageSpan is added twice when added to SpannedString

715 views Asked by At

When I add an ImageSpan to a SpannableString I am seeing the same image twice. The SpannableString has been created from text inserted into a TextView by Html.fromHtml()

The code I am using to add the ImageSpan is below.

    public void updateSpan(URLDrawable tweetImage, int startSpan, int endSpan){

    TextView textView  = (TextView) findViewById(R.id.story_body);
    SpannableString ss = new SpannableString(textView.getText());

    Drawable d = tweetImage.getDrawable();
    d.setBounds(0, 0, (int) (d.getIntrinsicWidth() * 3), (int) (d.getIntrinsicHeight() * 3));

    ImageSpan span = new ImageSpan(d , ImageSpan.ALIGN_BOTTOM);

    ss.setSpan(span, startSpan, endSpan, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

    textView.setText(ss);

}

I have searched and found a couple of similar questions (see below) however nothing suggested in them works in this case.

Picture in spannable edittext display twice

Why does android ImageSpan show my picture twice (when setBounds exceed certain magic width)?

(I tried to post an image of the issue, however lack the rep to do so :) )

1

There are 1 answers

0
simon2211 On

I found the answer..

In a similar vein to Why does android ImageSpan show my picture twice (when setBounds exceed certain magic width)?

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.