虽然webviwiew可以帮我们轻松的搞定html页面,但是webview诸如内存泄漏,与JS交互的各种繁琐,以及不同手机不同处理器的适配,使得我们需要花费更多的时间适配;
Html工具类可以帮我们搞定解析url里面的标签,拿到我们想要的数据用我们想要的方式去展示和交互,但是当我们需要图文并茂的时候也有办法搞定:
举个例子?
在上面这个新闻详情界面,我们可以看到既有图片,也有文字,在Html工具中给出了4个重载的方法,前两个是针对文本标签
@Deprecated public static Spanned fromHtml(String source) { return fromHtml(source, FROM_HTML_MODE_LEGACY, null, null); }
public static Spanned fromHtml(String source, int flags) { return fromHtml(source, flags, null, null); }
另外两个是针对的image标签,也就是图片
@Deprecated public static Spanned fromHtml(String source, ImageGetter imageGetter, TagHandler tagHandler) { return fromHtml(source, FROM_HTML_MODE_LEGACY, imageGetter, tagHandler); }
public static Spanned fromHtml(String source, int flags, ImageGetter imageGetter, TagHandler tagHandler) { //省略中间代码 return converter.convert(); }
解析含有图片的html文本时,需要我们实现ImageGetter接口,并重写里面的getDrawable()方法,并返回一个Drawable对象进行展示,代码如下:
这里我用的是ImageLoader库进行图片的加载与现实,并且监听图片的加载,解决图文重叠情况,其中需要重测图片宽高,再设置给bitmap对象;其他String source 就是解析到的图片路径,这里是加了服务器地址拼接而来,可以按自己的路径进行更改,然后再看activity的代码,很简单,就一句话public class URLImageGetter implements Html.ImageGetter{ private TextView textView; Context context; private DisplayImageOptions options; public URLImageGetter(Context context, TextView textView, DisplayImageOptions options) { this.context = context; this.textView = textView; this.options = options; } @Override public Drawable getDrawable(String source) { LogUtil.e(source); final URLDrawable urlDrawable = new URLDrawable(); ImageSize imageSize = new ImageSize(480,320); NonViewAware nonViewAware = new NonViewAware(imageSize, ViewScaleType.CROP); ImageLoader.getInstance().displayImage(Constants.IMG_URL+source,nonViewAware,options,new SimpleImageLoadingListener(){ @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { super.onLoadingComplete(imageUri, view, loadedImage); urlDrawable.bitmap = loadedImage; urlDrawable.setBounds(0, 0, loadedImage.getWidth(), loadedImage.getHeight()); textView.invalidate(); textView.setText(textView.getText()); // 解决图文重叠 } }); return urlDrawable; } }
detail_content.setText(Html.fromHtml(contentBean.content,new URLImageGetter(NewsDetailActivity.this,detail_content,options),null)); //文章内容
最后再加上这些:
detail_content.setMovementMethod(ScrollingMovementMethod.getInstance());// 设置可滚动 detail_content.setMovementMethod(LinkMovementMethod.getInstance());//设置超链接可以打开网页大功告成!!