public class HtmlTextView extends TextView {
private static final String TAG = "HtmlTextView";
private String mHtmlStr;
private Html.ImageGetter mNetImageGetter = new Html.ImageGetter() {
@Override
public Drawable getDrawable(final String source) {
Log.i(TAG, "mNetImageGetter source=" + source);
if (!TextUtils.isEmpty(source) && source.startsWith("http")) {
File f = GlideModuleImpl.getDiskCache().get(new StringSignature(source));
Drawable drawable = null;
Log.i(TAG, "mNetImageGetter imgFile=" + f);
if (f != null && f.exists()) {
Log.i(TAG, "mNetImageGetter imgFile path=" + f.getAbsolutePath());
drawable = Drawable.createFromPath(f.getAbsolutePath());
//设置图片边界
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
return drawable;
} else {
Observable.just(source).map(new Func1<String, File>() {
@Override
public File call(String o) {
File file = null;
try {
file = Glide.with(getContext()).load(source).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
Log.i(TAG, "mNetImageGetter new download imgFile=" + file);
return file;
}
}).subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<File>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
Log.i(TAG, "mNetImageGetter download error");
e.printStackTrace();
}
@Override
public void onNext(File file) {
if (file != null && file.exists() && getContext() != null) {
HtmlTextView.this.setText(Html.fromHtml(mHtmlStr, mNetImageGetter, null));
}
}
});
}
}
return null;
}
};
public HtmlTextView(Context context) {
super(context);
}
public HtmlTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public HtmlTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void loadHtml(String htmlStr) {
this.mHtmlStr = htmlStr;
HtmlTextView.this.setText(Html.fromHtml(mHtmlStr, mNetImageGetter, null));
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
}
DEMO: 下载地址