使用TextView显示网页中的图片
jopen
10年前
Html类下有一个ImageGetter接口可以帮助我们完成,直接上代码:
MainActivity:
package com.home.testhtml; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Html; import android.text.Html.ImageGetter; import android.text.Spanned; import android.widget.TextView; public class MainActivity extends Activity { private TextView tv; private String htmlStr = "<h1>测试html的img标签</h1><p font='red'>这里是测试内容</p><p><img src='http://xxx.com/test.jpg'></p>"; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { Spanned sp = (Spanned) msg.obj; tv.setText(sp); }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tv = new TextView(this); setContentView(tv); new Thread() { public void run() { Spanned sp = Html.fromHtml(htmlStr, new MyImageGetter(), null); Message msg = new Message(); msg.obj = sp; mHandler.sendMessage(msg); }; }.start(); } class MyImageGetter implements ImageGetter { @Override public Drawable getDrawable(String source) { Drawable mDrawable = null; try { mDrawable = Drawable.createFromStream( new URL(source).openStream(), "test.jpg"); mDrawable.setBounds(0, 0, mDrawable.getIntrinsicWidth(), mDrawable.getIntrinsicHeight()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return mDrawable; } } }