views:

622

answers:

4

Given the following HTML:

<p>This is text and this is an image <img src="http://www.example.com/image.jpg" />.</p>

Is it possible to make the image render? When using this snippet: mContentText.setText(Html.fromHtml(text));, I get a cyan box with black borders, leading me to believe that a TextView has some idea of what an img tag is.

A: 

No. TextView does not accept HTML formatted text. If you want to display images in html you probably need to use a WebView. To format text you can check out the api.

BrennaSoft
+2  A: 

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.

Dave Webb
OK. I found it was easier to just use a WebView instead. I can see your technique being useful for other similar scenarios, though. Thanks!
Gunnar Lium
A: 

Also, if you do want to do the replacement yourself, the character you need to look for is [  ].

But if you're using Eclipse, it will freak out when you type that letter into a [replace] statement telling you it conflicts with Cp1252 - this is an Eclipse bug. To fix it, go to Window -> Preferences -> General -> Workspace -> Text file encoding, and select [UTF-8]

splash
A: 

You could also write your own parser to pull the URL of all the images and then dynamically create new imageviews and pass in the urls.

Falmarri