[Android]Html.from()中ImageGetter异步加载并显示图片和替换标签处理效果

异步加载图片:先返回一个LevelListDrawable,之后加载图片,获取到Bitmap之后转为Drawable,并设置到之前的LevelListDrawable中,更新level。这里要注意,要重新设置一下Textview的text,不然图片显示不出来。

public class HtmlTool {

	public static SpannableStringBuilder fromHtml(String source, final TextView textView){

		textView.setMovementMethod(LinkMovementMethod.getInstance());

		Spanned spanned = Html.fromHtml(source, new Html.ImageGetter() {
			@Override
			public Drawable getDrawable(String source) {
				final LevelListDrawable drawable = new LevelListDrawable();
				Ion.with(TumlodrApp.mContext)
						.load(source)
						.asBitmap()
						.setCallback(new FutureCallback<Bitmap>() {
							@Override
							public void onCompleted(Exception e, Bitmap result) {
								if(result != null) {
									BitmapDrawable bitmapDrawable = new BitmapDrawable(result);
									drawable.addLevel(1, 1, bitmapDrawable);
									drawable.setBounds(0, 0, result.getWidth(), result.getHeight());
									drawable.setLevel(1);
									CharSequence text = textView.getText();
									textView.setText(text);
									textView.refreshDrawableState();
								}
							}
						});
				return drawable;
			}
		}, null);

		SpannableStringBuilder sp = (SpannableStringBuilder) spanned;
		QuoteSpan[] quoteSpans = sp.getSpans(0, sp.length(), QuoteSpan.class);
		for(QuoteSpan quoteSpan : quoteSpans){
			int start = sp.getSpanStart(quoteSpan);
			int end = sp.getSpanEnd(quoteSpan);
			sp.removeSpan(quoteSpan);
			CustomQuoteSpan customQuoteSapan = new CustomQuoteSpan();
			sp.setSpan(customQuoteSapan, start, end, 0);
		}

		return sp;
	}
}
参考: Stack Overflow: Html.ImageGetter TextView


版权声明:本文为hoooooozzz原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。