TextView加载Html并且显示图片

设置文本源:

    imageGetter = new PicImageGetter();
    contentView.setText(Html.fromHtml(replaceIMG, imageGetter, null));

获取图片的ImageGetter:

 private class PicImageGetter implements Html.ImageGetter {
        @Override
        public Drawable getDrawable(final String source) {
            // 读取已保存的图片文件
            byte[] bytes = CacheUtils.get(source);
            Drawable drawable = null;
            if (bytes != null) {
                drawable = Drawable.createFromStream(new ByteArrayInputStream(bytes), null);
                System.out.println(drawable.getIntrinsicWidth() + " , " + drawable.getIntrinsicHeight());
                // 计算缩放比例,横向填充,纵向保持比例

                int picWidth = screenWidth /  drawable.getIntrinsicWidth();

                drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * picWidth, drawable.getIntrinsicHeight() * picWidth);
                return drawable;
            } else {
                // 下载图片并保存
                HttpEngine httpEngine = HttpEngine.getInstance();
                httpEngine.get(source, new BinaryHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {
                        CacheUtils.put(source, binaryData);
                        contentView.setText(Html.fromHtml(replaceIMG, imageGetter, null));
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) {
                        contentView.setText(Html.fromHtml(replaceIMG, imageGetter, null));
                    }
                });
                return null;
            }
        }
    }

你可能感兴趣的:(android,textview,显示HTML)