[Android]Html.from()中ImageGetter非同步載入並顯示圖片和替換標籤處理效果
阿新 • • 發佈:2019-02-07
非同步載入圖片:先返回一個LevelListDrawable,之後載入圖片,獲取到Bitmap之後轉為Drawable,並設定到之前的LevelListDrawable中,更新level。這裡要注意,要重新設定一下Textview的text,不然圖片顯示不出來。
參考:Stack Overflow: Html.ImageGetter TextViewpublic 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; } }