Android TextView and Image loading from URL — Part 3

If you’ve ended up in a situation where you need to give super powers to your humble TextView and this super power includes :

  1. Displaying HTML content which includes <img> tag.
  2. Click actions on the displayed image.
  3. Center aligning the loaded image with the adjacent text.

Search no more, this article is for you.

Super Power 3: Center aligning the loaded image with the adjacent text.

So our humble TextView is now loaded with capabilities to recognize and deal with <img> tag as well as attach click listener to it.

But, there’s a problem. Remember ImageSpan ? (Son of DynamicDrawableSpan) ? Well, during birth it came with limited capabilities.

It can only align the image either with BASELINE or BOTTOM of textview.

The pic below is a primer on various alignment related to text :

The issue with this is that sometimes the images can be mis aligned Eg: If you’re displaying a formula.

In order for them to be in sync with the surrounding text, they need to CENTRE Aligned. Unfortunately, the ImageSpan doesn’t provide them out of box.

Hence a couple of stackoverflow answers and blog articles helped me arrive me at the following custom Image Span which when used gives the desired result :