Android textview获取html文字 + 图片显示

1、html元素

<p style="text-align: center;"><a href="http://news.klhpw.com/batch.download.php?aid=52756" target="_blank" title="Smurfit Kappa公司"><img src="http://news.klhpw.com/attachments/2014/03/65625_201403121600231dZAA.jpg" border="0" alt="Smurfit Kappa公司"></a></p><p><br></p><p>  Smurfit Kappa公司近日称,目前,为餐饮服务行业提供奶制品的公司对盒中袋包装的需求在逐步增长。零售业则存在着最大的增长空间。</p><p><br></p>

2、activity

package com.html.src.show;

import java.io.InputStream;
import java.net.URL;
import android.os.Bundle;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.drawable.Drawable;

public class MainActivity extends Activity {

	private TextView tvBody;
	String text;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tvBody = (TextView) findViewById(R.id.tv_about_right);
		tvBody.setMovementMethod(new ScrollingMovementMethod());// textview上下拉
		//获取assets包下html.txt内容
		try {
			InputStream is = getAssets().open("html.txt");
			int size = is.available();
			byte[] buffer = new byte[size];
			is.read(buffer);
			is.close();
			text = new String(buffer, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		//解析html
		ImageGetter imgGetter = new Html.ImageGetter() {
			public Drawable getDrawable(String source) {
				Log.i("RG", "source---?>>>" + source);
				Drawable drawable = null;
				URL url;
				try {
					url = new URL(source);
					Log.i("RG", "url---?>>>" + url);
					// 获取网路图片
					drawable = Drawable.createFromStream(url.openStream(), ""); 
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
				drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
				Log.i("RG", "url---?>>>" + url);
				return drawable;
			}
		};
		tvBody.setText(Html.fromHtml(text, imgGetter, null));
	}
}


发布了19 篇原创文章 · 获赞 12 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/u014051380/article/details/21132665