Android 加载网络图片设置到ImageView

下载图片后显示在ImageView中

//1、定义全局变量
private Handler handler;
private String image_url;
private Bitmap bitmap;

//2、在onCreate初始化
handler = new Handler(Looper.getMainLooper());
image_url= "";
bitmap=null;
imageView=(ImageView)findViewById(R.id.test_img);


//3、为了下载图片资源,开辟一个新的子线程
new Thread(new Runnable() {
    @Override
    public void run() {
            try {
                // 对资源链接
                URL url = new URL(image_url);
                // 打开输入流
                InputStream inputStream = url.openStream();
                // 对网上资源进行下载转换位图图片
                bitmap = BitmapFactory.decodeStream(inputStream);
                //在其他线程更新UI
                handler.post(runnableUi);
            } catch (Exception e) {
                e.printStackTrace();
            }
    }

}).start();


//4、构建Runnable对象,在runnable中更新界面
Runnable runnableUi=new  Runnable(){
    @Override
    public void run() {
        //更新界面
        imageView.setImageBitmap(bitmap);
    }
};

上面这种方法太麻烦了,推荐使用Glide

Glide,一个被google所推荐的图片加载库,作者是bumptech。

AndroidStudio上添加依赖

dependencies {  
    compile 'com.github.bumptech.glide:glide:3.7.0'  
    compile 'com.android.support:support-v4:23.2.1'  
} 

使用

String url = "http://img.zcool.cn/community/01bd7055b1cff56ac725ca509d7844.jpg@1280w_1l_2o_100sh.png";
ImageView imageView = (ImageView) findViewById(R.id.imageView);
Glide.with(context)
    .load(url)
    .into(imageView);

详细介绍请参考: Google推荐——Glide使用详解

原文地址:https://www.cnblogs.com/cralor/p/9391762.html