Tuesday, June 8, 2010

TextView with HTML content with Images

Handling HTML content on a TextView is simple as far as the HTML coming in contains a few tags that are by default supported by Android. Simple formatting like bold, italics, font sizes can be handled without even coding a single extra line.

Say, if you have a TextView tv, and there's some HTML string with bold and italicized text, bringing it up on the TextView is pretty simple.

One line code for that:

tv.setText(Html.fromHtml(source)); 

where the source is actually your HTML string. This works perfectly. But how do we show images if there are any. Well, it's a bit tricky. You have to use the other method that takes in an ImageGetter and a TagHandler.

fromHtml(String source, Html.ImageGetter imageGetter, Html.TagHandler tagHandler)

The tagHandler is for situations where you wish to handle specific tags differently. I didn't wish to do that, so I just passed null there.

Now comes the main task. How do you get the image on to the TextView!!!!

Implement the Html.ImageGetter's getDrawable method which handles downloading the image, or accessing it from the net, and then create a drawable and return that object.

      static ImageGetter imgGetter = new Html.ImageGetter() {
             @Override
             public Drawable getDrawable(String source) {
                   Drawable drawable = null;
                   drawable = Drawable.createFromPath(source);  // Or fetch it from the URL
                   // Important
                   drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
                                 .getIntrinsicHeight());
                   return drawable;
             }
      };

and use the method on the TextView like this.
tv.setText(Html.fromHtml(source, imgGetter, null);

This will load the TextView with the image. But this call to the getDrawable method is not asynchronous. So, until and unless that method returns, you UI will be blocked. In my case, I am creating the drawable from a local image, so, it didn't take much time. But, if you want to fetch an image from the web, you have to make this call in a separate thread, so that the UI is not blocked.

So, check your HTML string if they contain any images that have to be downloaded. If you find any, create a thread that download that image, saves it somewhere and returns you the location of that file. Now, change the src tags to point to the local images, and call setText method on the TextView.

And that should do it. The important thing to remember is, you have to change the HTML to point it to the file that you have downloaded.

Sample Source code : http://code.google.com/p/myandroidwidgets/source/browse/#svn/trunk/TextViewHTML 

This sample doesn't use threads. So, your UI will be blocked unitl the image here is downloaded. So, keep waiting. :)