Fit ImageSpan to TextView line height

filippo picture filippo · Oct 24, 2013 · Viewed 12k times · Source

I need to put some icons inside my textview, but they don't fit the line height (look at the arrows):

screenshoot

I tried this:

spannable.setSpan(new ImageSpan(context, entry.getValue(), ImageSpan.ALIGN_BOTTOM), Matcher.start(), matcher.end(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
t.setText(spannable, BufferType.SPANNABLE);

and this:

    Drawable myIcon = c.getResources().getDrawable(R.drawable.myicon);
    myIcon.setBounds(0, 0, myIcon.getIntrinsicWidth(), myIcon.getIntrinsicHeight());
    spannable.setSpan(new ImageSpan(myIcon, ImageSpan.ALIGN_BASELINE), matcher.start(), matcher.end(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
t.setText(spannable, BufferType.SPANNABLE);

and in both cases i had the same result.

I keep the icon in /res/drawable folder, and its size is 75x75px. I tried to lower the image resolution but they look blurred

Answer

Jay Soyer picture Jay Soyer · Mar 6, 2014

You need to set the image's bounds to the TextView's line height. Eg:

myIcon.setBounds(0, 0, t.getLineHeight(),t.getLineHeight());

This of course assumes you want a square image. If not square, then you'll need to manually determine what the width value should be based off the line height.