Loading

Android自动解析html带图片,实现图文混排

在android中,如何将html代码转换为text,然后显示在textview中呢,有一个简单直接的方法:

textView.setText(Html.fromHtml(content));

然而用的时候却发现html里面的图片没法被被解析出来,别慌,Html还有一个方法:

public static Spanned fromHtml(String source, ImageGetter imageGetter,TagHandler tagHandler)

其中,我们可以自定义imageGetter,这个对象是用于解析html中的图片。

 

public class MImageGetter implements Html.ImageGetter {
    private Context c;
    private TextView container;

    public MImageGetter(TextView text, Context c) {
        this.c = c;
        this.container = text;
    }

    @Override
    public Drawable getDrawable(String source) {
        Drawable drawable = null;
        InputStream is = null;
        //source便是图片的路径,如果图片在本地,可以这样做        
is = c.getResources().getAssets().open(source);
try { TypedValue typedValue = new TypedValue(); typedValue.density = TypedValue.DENSITY_DEFAULT; drawable = Drawable.createFromResourceStream(null, typedValue, is, "src"); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());
return drawable; } catch (Exception e) { System.out.println(e); return null; } }

最终调用:

textView.setText(Html.fromHtml(text, new MImageGetter(textView, this), null));

这样便可以实现图文混排了,在该显示图片的地方显示图片。

 

如果是要显示网络上的图片,getDrawable方法可以这样

public Drawable getDrawable(String source) {
         final LevelListDrawable drawable = new LevelListDrawable();
         Glide.with(c).load(source).asBitmap().into(new SimpleTarget<Bitmap>() {
             @Override
             public void onResourceReady(Bitmap resource,  
GlideAnimation<? super Bitmap> glideAnimation) { if(resource != null) { BitmapDrawable bitmapDrawable = new BitmapDrawable(resource); drawable.addLevel(1, 1, bitmapDrawable); drawable.setBounds(0, 0, resource.getWidth(),resource.getHeight()); drawable.setLevel(1); container.invalidate(); container.setText(container.getText()); } } }); return drawable; }

第三个参数 其作用是把 HTML 带标记的文本内容字符串转化成可以显示效果的的 Spanned 字符串 。由于并非所有的 HTML 标签都可以转化,所以在使用时,用户需要自己添加一些必要的标签和处理方法时才会使用的。

 

转载请标明出处,维权必究:https://www.cnblogs.com/tangZH/p/10491976.htmlhttp://77blogs.com/?p=304

参考链接:https://blog.csdn.net/qq_30548105/article/details/78031347

posted @ 2019-03-07 20:12  妖久  阅读(5811)  评论(0编辑  收藏  举报