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,http://77blogs.com/?p=304
参考链接:https://blog.csdn.net/qq_30548105/article/details/78031347
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
2017-03-07 ViewPager实现滑动翻页效果
2017-03-07 ViewPager结合Fragment进行无限滑动
2017-03-07 ViewPager结合view无限滑动