开发者

Asynchronous Html.ImageGetter for setting multiple images in a TextView

开发者 https://www.devze.com 2023-02-08 14:16 出处:网络
I\'m writing an application that takes HTML pages and parses them to display on the screen. Specifically, this application pulls HTML from a message board and lists posts made by users.

I'm writing an application that takes HTML pages and parses them to display on the screen. Specifically, this application pulls HTML from a message board and lists posts made by users.

The problem is that a lot of the content in posts are pictures in <img> tags, so I need to write a Html.ImageGetter to handle the downloading of the images.

My textView.setText() method will look like this:

myTextView.setText(Html.fromHtml(myText, new ImageGetter() {                 
        @Override
        public Drawable getDrawable(String so开发者_如何学Gource) {
        Drawable d;

        // Need to async download image here 

         return d;
        }
    }, null));

Doing this synchronously is trivial, but is there a suggested way to do this asynchronously so that it doesn't lock up my UI thread? I would also like to eventually build in caching of these images, but I imagine that would be pretty simple once the async downloading was there.


Doing this synchronously is trivial, but is there a suggested way to do this asynchronously so that it doesn't lock up my UI thread?

That will be difficult, perhaps impossible. You have to return something immediately. Even if that is a placeholder, you then have the challenge of how to replace the placeholder once the download is complete. Since you lack access to the ImageView rendering the image (if there is an ImageView), I don't know how you would arrange to replace the placeholder.


I'd use either an AsyncTask or a Thread/Handler combination.

  • AsyncTask
  • Painless threading
  • Threading
  • Designing for responsiveness
  • Thread documentation
  • Handler documentation


How about extract all the urls before displaying the html by using an invisible Html.fromHtml, putting those urls in a list, asynchronously downloading all images, storing them in an in memory cache, then implementing the ImageGetter to just do a cache lookup using the url as a key and the drawable as the value.


for downloading asynchronously the images and storing them in memory cache there is a mini-library here :) https://github.com/koush/UrlImageViewHelper

0

精彩评论

暂无评论...
验证码 换一张
取 消