前言
在TextView中要顯示HTML文字是比較輕松的事,但是在其中混上圖片就變的復(fù)雜了起來。本文使用Glide作為圖片加載工具。
上手
一.首先看看需要什么對象
public void onSuccess(String string) {
CharSequence charSequence;
// 這個(gè)是自定義的ImageGetter
DetailImageGetter detailImageGetter = new DetailImageGetter(this,textView);
//因?yàn)閒romHtml在api24開始過時(shí),所以加上版本判斷
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
charSequence = Html.fromHtml(string, Html.FROM_HTML_MODE_LEGACY,
detailImageGetter, null);
} else {
charSequence = Html.fromHtml(string, detailImageGetter, null);
}
textView.setText(charSequence);
}
二.來看看自定義的ImageGetter類:
class DetailImageGetter implements Html.ImageGetter {
private Context context;
private TextView textView;
DetailImageGetter(Context context, TextView textView) {
this.context = context;
this.textView = textView;
}
@Override
public Drawable getDrawable(String source) {
final UrlDrawable drawable = new UrlDrawable();
Glide.with(context)
.load(source)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
drawable.setBitmap(resource);
drawable.setBounds(0, 0, resource.getWidth(), resource.getHeight());
textView.invalidate();
textView.setText(textView.getText());
}
});
return drawable;
}
private class UrlDrawable extends BitmapDrawable {
private Bitmap bitmap;
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (bitmap != null) {
canvas.drawBitmap(bitmap, 0, 0, getPaint());
}
}
void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
}
}
其中包含了一個(gè)自定義的BitmapDrawable類。如果沒有重寫這個(gè)onDraw方法的話,顯示不出圖片來,只會(huì)有一個(gè)圖片大小的空位在那里。
到這里就完成了圖片的下載和顯示,并且利用了Glide進(jìn)行了緩存。但這里還有一個(gè)問題,BitmapDrawable的空構(gòu)造器已經(jīng)過時(shí)了,但是當(dāng)我使用BitmapDrawable(Res,bitmap)這個(gè)構(gòu)造器的時(shí)候圖片無法加載。根據(jù)查看源碼只發(fā)現(xiàn)這個(gè)res的傳入是更新了mTargetDensity,不知道為什么就無法顯示了。希望各位博友能給予一些指導(dǎo)。