Android TextView显示文章详情

1  Spanned android.text.Html.fromHtml(String source)
             输入的参数为(html格式的文本)
       2  Spanned android.text.Html.fromHtml(String source, ImageGetter imageGetter, TagHandler tagHandler)
          Source:    需处理的html文本
         imageGetter :对图片处理

  tagHandler  :对标签进行处理


CImageGetter.java

package com.texthtml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.Html.ImageGetter;
import android.widget.TextView;

public class CImageGetter implements ImageGetter {
	
	private Context context;
	private TextView tv;
	
	public CImageGetter(Context context, TextView tv) {
		this.context = context;
		this.tv = tv;
	}
	
	@Override
	public Drawable getDrawable(String source) {

		String imageName = Common.md5(source);
		String sdcardPath = Environment.getExternalStorageDirectory().toString();
		String[] ss = source.split("\\.");
		String ext = ss[ss.length - 1];
		String savePath = sdcardPath + "/" + context.getPackageName() + "/" + imageName + "." + ext;
		File file = new File(savePath);
		if (file.exists()) {
			Drawable drawable = Drawable.createFromPath(savePath);
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
			return drawable;
		}
		Resources res = context.getResources();
		URLDrawable drawable = new URLDrawable(res.getDrawable(R.drawable.ic_launcher));
		new ImageAsync(drawable).execute(savePath, source);
		return drawable;	
	}

	private class ImageAsync extends AsyncTask {

		private URLDrawable drawable;
		
		public ImageAsync(URLDrawable drawable) {
			this.drawable = drawable;
		}
		
		@Override
		protected Drawable doInBackground(String... params) {
			String savePath = params[0];
			String url = params[1];
			
			InputStream in = null;
			try {
				HttpGet http = new HttpGet(url);
				HttpClient client = new DefaultHttpClient();
				HttpResponse response = client.execute(http);
				BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(response.getEntity());
				in = bufferedHttpEntity.getContent();
			} catch (Exception e) {
				try {
					if (in != null)
						in.close();
				} catch (Exception e2) {
					// TODO: handle exception
				}
			}

			if (in == null) return drawable;
			
			try {
				File file = new File(savePath);
				String basePath = file.getParent();
				File basePathFile = new File(basePath);
				if (!basePathFile.exists()) {
					basePathFile.mkdirs();
				}
				file.createNewFile();
				FileOutputStream fileout = new FileOutputStream(file);
				byte[] buffer = new byte[4*1024];
				while (in.read(buffer) != -1) {
					fileout.write(buffer);
				}
				fileout.flush();
				fileout.close();  //关闭流
				Drawable mDrawable = Drawable.createFromPath(savePath);
				return mDrawable;
			} catch (Exception e) {
				// TODO: handle exception
			}
			return drawable;
		}

		@Override
		protected void onPostExecute(Drawable result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result != null) {
				drawable.setDrawable(result);
				tv.setText(tv.getText()); // 更新UI
			}
		}
		
	}

	public class URLDrawable extends BitmapDrawable {
		
		private Drawable drawable;
		
		public URLDrawable(Drawable defaultDraw) {
			setDrawable(defaultDraw);
		}
		
		private void setDrawable(Drawable nDrawable) {
			drawable = nDrawable;
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
			setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
		}

		@Override
		public void draw(Canvas canvas) {
			drawable.draw(canvas);
		}
		
	}
}

CTagHandler.java
package com.texthtml;

import java.io.File;

import org.xml.sax.XMLReader;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.Editable;
import android.text.Html.TagHandler;
import android.text.Spanned;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.View;

public class CTagHandler implements TagHandler {

	private Context context;
	
	public CTagHandler(Context context) {
		this.context = context;
	}
	
	@Override
	public void handleTag(boolean opening, String tag, Editable output,
			XMLReader xmlReader) {
		if (tag.toLowerCase().equals("img")) {
			int len = output.length();
			ImageSpan[] images = output.getSpans(len-1, len, ImageSpan.class);
			String imgURL = images[0].getSource();
			output.setSpan(new ImageClick(context, imgURL), len-1, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
	}
	
	private class ImageClick extends ClickableSpan {

		private String url;
		private Context context;
		
		public ImageClick(Context context, String url) {
			this.context = context;
			this.url = url;
		}
		
		@Override
		public void onClick(View widget) {
			String imageName = Common.md5(url);
			String sdcardPath = Environment.getExternalStorageDirectory().toString(); // 获取SDCARD的路径
			String[] ss = url.split("\\.");
			String ext = ss[ss.length - 1];
			String savePath = sdcardPath + "/" + context.getPackageName() + "/" + imageName + "." + ext;
			
			File file = new File(savePath);
			if (file.exists()) {
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(file), "image/*");
				context.startActivity(intent);
				Log.i("Load","data");
			}
		}
		
	}

}

Common.java

package com.texthtml;

import java.security.MessageDigest;

public class Common {
	
	public static String md5(String sourceStr) {
		
		byte[] source = sourceStr.getBytes();

		String s = null;
		
		char hexDigits[] = {
				'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
		};
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest();
			char[] str = new char[16 * 2];
			int k = 0;
			for (int i = 0; i < 16; i++) {
				byte byte0 = tmp[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			s = new String(str);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return s;
	}
}

MainActivity.java

package com.texthtml;





import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;

public class MainActivity extends Activity {
	
	private final static String HTML_CONTENT = "legougo.com" +
			"legou

www.legougo.com

" + "

www.legougo.com

" + "

文章详情图片发大效果

乐够go," + "可以有多张图片:
" + "" + "

www.hongshengpeng.com

"+ "" ; private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); Spanned spanned = Html.fromHtml(HTML_CONTENT, new CImageGetter(this, tv), new CTagHandler(this)); tv.setText(spanned); tv.setMovementMethod(LinkMovementMethod.getInstance()); } }

Android TextView显示文章详情_第1张图片

原文地址 http://hongshengpeng.com/article/show/199.aspx


你可能感兴趣的:(Android开发)