设为首页 加入收藏

TOP

Android自动解析html带图片,实现图文混排
2019-09-01 23:12:58 】 浏览:25
Tags: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.html

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

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇安卓开发笔记(十三):SQLite数.. 下一篇Retrofit的初次使用

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目