4

I have a TextView filled with text that should contain some ImageSpan objects. The images can be taller than the normal line height which causes the following problem:

  • if the image is the last object of a line, the following lines' height is correct
  • if the last object is not an image, the following lines' height is set to the image-containing line's height

Here is the correct situation: enter image description here


This is the wrong situation: enter image description here

What's more interesting is that if there's a new-line character in the text, the line height is good from that point on again.

The TextView is just a pretty basic one:

<TextView
    android:id="@+id/text_02"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="18dp"
    android:text="Text 02" />

(The TextView is located in a LinearLayout which is in a ScrollView.)

This is how I create the spanned text:

TextView textView02 = (TextView) findViewById(R.id.text_02);

SpannableString string = new SpannableString(LOREM_IPSUM);
string.setSpan(new ImageSpan(this, R.mipmap.ic_launcher), 102, 103, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
string.setSpan(new ImageSpan(this, R.mipmap.ic_launcher), 105, 106, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
string.setSpan(new ImageSpan(this, R.mipmap.ic_launcher), 108, 109, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

textView02.setText(string);

Does anybody have any idea about a solution for this? I'd rather not reimplement the TextView's line drawing methods...

Gergely Kőrössy
  • 5,620
  • 3
  • 28
  • 44
  • did you ever figure this out – j2emanue Mar 30 '17 at 06:57
  • Not reall. However, I did test it with multiple emulator images and it seems to me that only the API 23 (6.0) one produces this. Also, if I ran it on an API 23 phone (6.0.2 I think), it would never show this kinda behavior. I think the devs messed up something in the original API 23, but fixed it later on. – Gergely Kőrössy Mar 30 '17 at 09:45
  • @GergelyKőrössy did you find solution for now? Is there any workaround for API 23? – Den Oct 19 '18 at 08:55

1 Answers1

0

Try to set a height to the drawable you want to show with the ImageSpan. For example like this:

Drawable vegetary = mContext.getResources().getDrawable(R.drawable.ic_best_veget);
    vegetary.setBounds(0, 0, vegetary.getIntrinsicWidth(), <yourHeight>);
    ssb.setSpan(new ImageSpan(vegetary, ImageSpan.ALIGN_BASELINE), ssb.length()-1, ssb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
jennymo
  • 1,450
  • 1
  • 18
  • 43