在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 implementsHtml.ImageGetter {privateContext c;privateTextView container;publicMImageGetter(TextView text, Context c) {this.c =c;this.container =text;
}
@OverridepublicDrawable getDrawable(String source) {
Drawable drawable= null;
InputStream is= null;
//source便是图片的路径,如果图片在本地,可以这样做is = c.getResources().getAssets().open(source);
try{
TypedValue typedValue= newTypedValue();
typedValue.density=TypedValue.DENSITY_DEFAULT;
drawable= Drawable.createFromResourceStream(null, typedValue, is, "src");
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight());returndrawable;
}catch(Exception e) {
System.out.println(e);return null;
}
}
最终调用:
textView.setText(Html.fromHtml(text, new MImageGetter(textView, this), null));
这样便可以实现图文混排了,在该显示图片的地方显示图片。
如果是要显示网络上的图片,getDrawable方法可以这样
publicDrawable getDrawable(String source) {final LevelListDrawable drawable = newLevelListDrawable();
Glide.with(c).load(source).asBitmap().into(new SimpleTarget() {
@Overridepublic void onResourceReady(Bitmap resource,
GlideAnimation super Bitmap>glideAnimation) {if(resource != null) {
BitmapDrawable bitmapDrawable= newBitmapDrawable(resource);
drawable.addLevel(1, 1, bitmapDrawable);
drawable.setBounds(0, 0, resource.getWidth(),resource.getHeight());
drawable.setLevel(1);
container.invalidate();
container.setText(container.getText());
}
}
});returndrawable;
}
第三个参数 其作用是把 HTML 带标记的文本内容字符串转化成可以显示效果的的 Spanned 字符串 。由于并非所有的 HTML 标签都可以转化,所以在使用时,用户需要自己添加一些必要的标签和处理方法时才会使用的。