TextView with ImageSpan messes up line height

天大地大妈咪最大 提交于 2020-01-01 12:31:34

问题


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:


This is the wrong situation:

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...


回答1:


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


来源:https://stackoverflow.com/questions/39729004/textview-with-imagespan-messes-up-line-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!