Android TextView and Image loading from URL — Part 1

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 1: Displaying <img> tag from remote URL.

By default, TextView does provide a way to display HTML.

Let’s say the html content you want to display is this :

String content = "<center> Infinity plan valid till 30 Jun 2017";

You can do something like this :

Spannable html;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
html = (Spannable) Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY, imageGetter, null);
} else {
html = (Spannable) Html.fromHtml(content, imageGetter, null);
}
mytextView.setText(html);

But, say this html content contains an <img> tag, you’re textview would end up looking like this :

src: https://i.stack.imgur.com/ptjuw.png

From documentation it clearly says that <img> tag will be replaced with a placeholder image like above. Which clearly doesn’t serve our purpose.

Now, the solution for how to display this is all over stackoverflow but surprisingly mixed up. Eg: Most of the solutions involve displaying image from the drawable using an ImageGetter Or others suggested going for WebView. ( We all know how that story will end up. Planning to write about my personal love-affair with WebView soon !).

My requirement was to load the image from a URL. Since I use Picasso to load remote images, I tried checking stackoverflow for solutions related to this and was thankful to find couple of them.

Given below is my implementation of ImageGetter based on couple of stackoverflow answers :

and this can be used in code as :

PicassoImageGetter imageGetter = new PicassoImageGetter(mytextView);
Spannable html;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
html = (Spannable) Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY, imageGetter, null);
} else {
html = (Spannable) Html.fromHtml(content, imageGetter, null);
}
mytextView.setText(html);