在Textview中异步加载带图片的Html文章很多,使用Picasso来异步加载多张时我遇到了onBitmapLoaded()有时候不执行的问题,在stackoverflow上找到了答案。
http://stackoverflow.com/questions/24180805/onbitmaploaded-of-target-object-not-called-on-first-load
大致意思就是说picasso的Target是一个弱引用,有可能就被回收了,所以没有回调。解决方案也写得很清楚,就是把这个Target设置为view的tag,如果是一张图片这是可以解决的。
但是html很可能会有多张图片,那么这里可用setTag(int key,Object obj)这个方法为View设置多个tag来解决。但是这个setTag(int key,Object obj)的key必须是一个resource id,所以目前我的解决方案是先定义一个最大图片数量,如果超出的话应该还是有图片加载不出来,下面上代码:
<pre>
<resources>
<item type="id" name="img0" />
<item type="id" name="img1" />
<item type="id" name="img2" />
<item type="id" name="img3" />
<item type="id" name="img4" />
<item type="id" name="img5" />
<item type="id" name="img6" />
<item type="id" name="img7" />
<item type="id" name="img8" />
<item type="id" name="img9" />
</resources>
</pre>
<pre>
public class URLDrawable extends BitmapDrawable {
protected Bitmap bitmap;
@Override
public void draw(Canvas canvas) {
if (bitmap != null) {
canvas.drawBitmap(bitmap, 0, 0, getPaint());
}
}
}
</pre>
<pre>
public class URLImageParser implements Html.ImageGetter {
private TextView mTextView;
private Context context;
private int count = 0;
public URLImageParser(Context context, TextView textView) {
this.mTextView = textView;
this.context = context;
}
@Override
public Drawable getDrawable(String source) {
Log.e("下载网络图片", source);
return loadImg(source);
}
private URLDrawable loadImg(final String source) {
final URLDrawable urlDrawable = new URLDrawable();
final Target target = new Target() {
@Override
public void onBitmapLoaded(Bitmap loadedImage, Picasso.LoadedFrom from) {
Log.e("onBitmapLoaded", "onBitmapLoaded");
if (loadedImage != null) {
urlDrawable.bitmap = loadedImage;
urlDrawable.setBounds(0, 0, loadedImage.getWidth(),
loadedImage.getHeight());
mTextView.invalidate();
mTextView.setText(mTextView.getText()); // 解决图文重叠
}
}
@Override public void onBitmapFailed(Drawable errorDrawable) {
Log.e("onBitmapFailed", "onBitmapFailed");
}
@Override public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.e("onPrepareLoad", "onPrepareLoad");
}
};
mTextView.setTag(getId(), target);
count++;
Picasso.with(context)
.load(source)
//图片宽度撑满
.resize(SvenUtils.getInstance().getScreenWidth(context) - 100, 0)
.into(target);
return urlDrawable;
}
private int getId() {
int a = count;
if (count >= 10) {
a = count % 10;
}
switch (a) {
case 0:
return R.id.img0;
case 1:
return R.id.img1;
case 2:
return R.id.img2;
case 3:
return R.id.img3;
case 4:
return R.id.img4;
case 5:
return R.id.img5;
case 6:
return R.id.img6;
case 7:
return R.id.img7;
case 8:
return R.id.img8;
default:
return R.id.img9;
}
}
}
</pre>