分享到:
点击次数:333  更新时间:2016-10-11 16:24:04  【打印此页】  【关闭
澳门新濠天地娱乐场澳门新濠天地娱乐定制
当前位置:主页 > 新闻动态 > 技术交流 > 使用TextView显示网页中的图片

使用TextView显示网页中的图片

责任编辑:admin 发布时间:2016-11-11 09:12 浏览次数:

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; 
            } 
     
        } 
    }