Textview显示Html 图文混排

Textview显示Html,图文混排,支持图片点击放大

2015-06-30 11:47:03 CSDN- u010403463- 点击数:1360
id="iframeu848856_0" src="http://pos.baidu.com/ycmm?rdid=848856&dc=2&di=u848856&dri=0&dis=0&dai=2&ps=230x520&dcb=BAIDU_SSP_define&dtm=BAIDU_DUP_SETJSONADSLOT&dvi=0.0&dci=-1&dpt=none&tsr=0&tpr=1465615384562&ti=Textview%E6%98%BE%E7%A4%BAHtml%EF%BC%8C%E5%9B%BE%E6%96%87%E6%B7%B7%E6%8E%92%EF%BC%8C%E6%94%AF%E6%8C%81%E5%9B%BE%E7%89%87%E7%82%B9%E5%87%BB%E6%94%BE%E5%A4%A7-HTML%2FCSS-%E7%AC%AC%E4%B8%83%E5%9F%8E%E5%B8%82&ari=1&dbv=2&drs=1&pcs=1920x905&pss=1920x231&cfv=0&cpl=28&chi=1&cce=true&cec=UTF-8&tlm=1465615384&ltu=http%3A%2F%2Fwww.th7.cn%2Fweb%2Fhtml-css%2F201506%2F107679.shtml&ecd=1&psr=1920x1080&par=1920x1050&pis=-1x-1&ccd=24&cja=true&cmi=82&col=zh-CN&cdo=-1&tcn=1465615385&qn=322d6f0d244d74b7&tt=1465615384523.105.215.216" width="336" height="280" align="center,center" vspace="0" hspace="0" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" allowtransparency="true" style="border-width: 0px; border-style: initial; vertical-align: bottom; margin: 0px; display: none !important;">

    对于呈现Html文本来说,Android提供的Webview控件可以得到很好的效果,但使用Webview控件的弊端是效率相对比较低,对于呈现简单的html文本的话,杀鸡不必使用牛刀。另外如果是在Listview中使用的Webview的话,效率则更是低下。

    然而,Android还提供了android.text.Html类来支持Html的解析,利用这个类,我们可以通过Textview来呈现Html文件。不过Html类并不是只是所有的标签。Html的描述如下:

This class processes HTML strings into displayable styledtext.

Not all HTML tags are supported.

一、解析Html标签

对于纯文字的Html文本来说,使用Textview来呈现很方便,一行代码就可以轻松搞定了,具体如下:

contentTextView.setText(Html.formHtml(htmlString));

二、处理img图片标签,实现图文混排

一般来说,html文件常常是含有图片,如果需要在Textview中实现文字和图片的混排,需要使用ImageGetter。ImageGetter是Html类中一个接口,作用是给img标签获取图片内容,主要提供了一个getDrawable的方法。

/*** Retrieves images for HTML <img> tags.*/public static interface ImageGetter {        /**         * This methos is called when the HTML parser encounters an         * <img> tag.  The <code>source</code> argument is the         * string from the "src" attribute; the return value should be         * a Drawable representation of the image or <code>null</code>         * for a generic replacement image.  Make sure you call         * setBounds() on your Drawable if it doesn't already have         * its bounds set.         */        public Drawable getDrawable(String source);}
解析来需要实现一个ImageGetter,具体如下:
public class MyImageGetter implements ImageGetter {		WeakReference<TextView> mTextViewReference;	Context mContext;	public MyImageGetter(Context context, TextView textView, int with) {		mContext = context.getApplicationContext();		mTextViewReference = new WeakReference<TextView>(textView);	}	@Override	public Drawable getDrawable(String url) {		URLDrawable urlDrawable = new URLDrawable(mContext);				// 异步获取图片,并刷新显示内容		new ImageGetterAsyncTask(url, urlDrawable).execute();		return urlDrawable;	}		public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {				WeakReference<URLDrawable> mURLDrawableReference;		String mUrl;		public ImageGetterAsyncTask(String url, URLDrawable drawable) {			mURLDrawableReference = new WeakReference<URLDrawable>(drawable);			mUrl = url;		}		@Override		protected Drawable doInBackground(String... params) {			// 下载图片,并且使用缓存			Bitmap bitmap = DownlaodUtils.getNetworkImageWithCache(mContext, mUrl);     			BitmapDrawable bitmapDrawable = new BitmapDrawable(mContext.getResources(), bitmap);						Rect bounds = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());						if (mURLDrawableReference.get() != null) {				mURLDrawableReference.get().setBounds(bounds);			}			bitmapDrawable.setBounds(bounds);			return bitmapDrawable;		}		@Override		protected void onPostExecute(Drawable result) {			if (null != result) {				if (mURLDrawableReference.get() != null) {					mURLDrawableReference.get().drawable = result;				}				if (mTextViewReference.get() != null) {					// 加载完一张图片之后刷新显示内容					mTextViewReference.get().setText(mTextViewReference.get().getText());				}			}		}	}			public class URLDrawable extends BitmapDrawable {		protected Drawable drawable;		public URLDrawable(Context context) {			// 设置默认大小和默认图片			Rect bounds = new Rect(0, 0, 100, 100);			setBounds(bounds);			drawable = context.getResources().getDrawable(R.drawable.default_image);			drawable.setBounds(bounds);		}		@Override		public void draw(Canvas canvas) {			if (drawable != null) {				drawable.draw(canvas);			}		}	}}

实现了MyImageGetter之后,则需要实现图文混排就轻而易举了

MyImageGetter imageGetter = new MyImageGetter(this, contentTextView);contentTextView.setText(Html.formHtml(htmlString, imageGetter, null));

三、图片的点击放大

前面已经实现了Textview呈现html文本,并且能够图文混排。但很多情况下,需要支持点击图片后将图片放大显示。这样,我们需要支持img标签的点击处理,能够监听到点击事件就可以实现这个功能了。这里我们可以通过实现TagHandler接口来实现这个功能。首先看下android.text.Html类中的Taghandler接口:

/**     * Is notified when HTML tags are encountered that the parser does     * not know how to interpret.     */    public static interface TagHandler {        /**         * This method will be called whenn the HTML parser encounters         * a tag that it does not know how to interpret.         */        public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader);}

我们只需实现TagHandler的handleTag方法来处理img标签则可,主要是给内容设置一个ClickableSpan,具体如下:

public class MyTagHandler implements TagHandler {	private mContext;		public MyTagHandler(Context context) {		mContext = context.getApplicationContext();	}		@Override	public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {		// 处理标签<img>		if (tag.toLowerCase(Locale.getDefault()).equals("img")) {			// 获取长度			int len = output.length();			// 获取图片地址			ImageSpan[] images = output.getSpans(len-1, len, ImageSpan.class);			String imgURL = images[0].getSource();						// 使图片可点击并监听点击事件			output.setSpan(new ClickableImage(mContext, imgURL), len-1, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);		}	}		private class ClickableImage extends ClickableSpan {		private String url;		private Context context;				public ClickableImage(Context context, String url) {			this.context = context;			this.url = url;		}				@Override		public void onClick(View widget) {			// 进行图片点击之后的处理		}	}}

实现了TagHandler之后,在formHtml传入实例则可:

MyImageGetter imageGetter = new MyImageGetter(this, contentTextView);MyTagHandler tagHandler = new MyTagHandler(this);contentTextView.setText(Html.formHtml(htmlString, imageGetter, tagHandler));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值