TextView & <img>

Aleksei Shcherbakov
2 min readMar 27, 2021

In one of my projects we was getting some text in html format from API and displaying it to user. It was implemented with WebView for each html piece, and this was too heavy and glitchy. Html texts had only basic formatting and images, so I had idea migrating to TextView.

Sample code displaying html:

It was surprise, that TextView can’t load images like WebView does. You have to do this by yourself, implementing ImageGetter interface.

And getDrawable() method is synchronous, but we load images with Glide asynchronously. So we need create drawable, and then update it after image loaded. For this we use DrawableWrapper class. The one from android.graphics requires API 23, another from AppCompat is library restricted for some reason. So I wrote own minimal class:

It’s interesting that ImageGetter takes only URL argument, you don’t get any size parameter from <img>. So you should set sizes for images. In this sample I used original image size.

This is what I got on screen:

Image was loaded, and displayed in right size. But text layout was wrong. Invaidate() doesn’t refresh html layout, neither requestLayout(). I found one solution to reset text.

Finally I got good result:

This worked, but if you have many images in html you will get many updates, and sometimes layout could be broken. I solved this adding delay before updating text.

Some time later I read article about TextViews, and found better solution. For every image in html ImageSpan is creating. TextView listens for changes in all including spans using SpanWatcher. So we can update only one span, instead of resetting entire text.

--

--