Is it possible to display inline images from html in an Android TextView?

If you have a look at the documentation for Html.fromHtml(text) you’ll see it says:

Any <img> tags in the HTML will display as a generic replacement image which your program can then go through and replace with real images.

If you don’t want to do this replacement yourself you can use the other Html.fromHtml() method which takes an Html.TagHandler and an Html.ImageGetter as arguments as well as the text to parse.

In your case you could parse null as for the Html.TagHandler but you’d need to implement your own Html.ImageGetter as there isn’t a default implementation.

However, the problem you’re going to have is that the Html.ImageGetter needs to run synchronously and if you’re downloading images from the web you’ll probably want to do that asynchronously. If you can add any images you want to display as resources in your application the your ImageGetter implementation becomes a lot simpler. You could get away with something like:

private class ImageGetter implements Html.ImageGetter {

    public Drawable getDrawable(String source) {
        int id;

        if (source.equals("stack.jpg")) {
            id = R.drawable.stack;
        }
        else if (source.equals("overflow.jpg")) {
            id = R.drawable.overflow;
        }
        else {
            return null;
        }

        Drawable d = getResources().getDrawable(id);
        d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
        return d;
    }
};

You’d probably want to figure out something smarter for mapping source strings to resource IDs though.

Leave a Comment