我之前做过与您想要做的类似(我想)的事情。当时我需要解析HTML并将其设置回TextView,同时我需要使用
Html.ImageGetter
,并且在主线程上获取图像时遇到了相同的问题。
我基本上采取的步骤如下:
- 创建自己的Drawable子类以便重新绘制,我称其为URLDrawable
- 在
Html.ImageGetter
的getDrawable
方法中返回URLDrawable
- 一旦调用了
onPostExecute
,就会重新绘制Spanned
结果的容器
现在,URLDrawable的代码如下:
public class URLDrawable extends BitmapDrawable {
protected Drawable drawable;
@Override
public void draw(Canvas canvas) {
if(drawable != null) {
drawable.draw(canvas);
}
}
}
很简单,我只需要覆盖draw
方法,这样在AsyncTask完成后,它就会选择我设置的Drawable。
下面这个类是Html.ImageGetter
的实现,它从AsyncTask
中获取图像并更新图像。
public class URLImageParser implements ImageGetter {
Context c;
View container;
public URLImageParser(View t, Context c) {
this.c = c;
this.container = t;
}
public Drawable getDrawable(String source) {
URLDrawable urlDrawable = new URLDrawable();
ImageGetterAsyncTask asyncTask =
new ImageGetterAsyncTask( urlDrawable);
asyncTask.execute(source);
return urlDrawable;
}
public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
@Override
protected Drawable doInBackground(String... params) {
String source = params[0];
return fetchDrawable(source);
}
@Override
protected void onPostExecute(Drawable result) {
urlDrawable.setBounds(0, 0, 0 + result.getIntrinsicWidth(), 0
+ result.getIntrinsicHeight());
urlDrawable.drawable = result;
URLImageParser.this.container.invalidate();
}
public Drawable fetchDrawable(String urlString) {
try {
InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
drawable.setBounds(0, 0, 0 + drawable.getIntrinsicWidth(), 0
+ drawable.getIntrinsicHeight());
return drawable;
} catch (Exception e) {
return null;
}
}
private InputStream fetch(String urlString) throws MalformedURLException, IOException {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(urlString);
HttpResponse response = httpClient.execute(request);
return response.getEntity().getContent();
}
}
}
最后,以下是演示如何运作的样例程序:
String html = "Hello " +
"<img src='http://www.gravatar.com/avatar/" +
"f9dd8b16d54f483f22c0b7a7e3d840f9?s=32&d=identicon&r=PG'/>" +
" This is a test " +
"<img src='http://www.gravatar.com/avatar/a9317e7f0a78bb10a980cadd9dd035c9?s=32&d=identicon&r=PG'/>";
this.textView = (TextView)this.findViewById(R.id.textview);
URLImageParser p = new URLImageParser(textView, this);
Spanned htmlSpan = Html.fromHtml(html, p, null);
textView.setText(htmlSpan);