使用TextView显示网页中的图片
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; } } }
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!