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