Android异步加载学习笔记之二:实现ListView中的图片数据从网络加载

来源:互联网 发布:java中的集合 编辑:程序博客网 时间:2024/05/01 10:23

      在上篇笔记http://blog.csdn.net/true100/article/details/47402773中,我们用AsyncTask异步任务实现了从网络获取json数据,并把获取到的数据展示到了ListView中,但是我们并没有把从网络获取到的图片数据加载到ListView中,而是统一使用的本地图片。接着学习,今天的目的就是实现把网络图片加载到ListView中。

    接着上面的代码,我们的Activity代码不用改变,主要是新增了一个从网络地址url中获取图片的工具类:

/**
 * 图片加载工具类
 * @description:
 * @author ldm
 * @date 2015-8-11 下午1:54:00
 */
public class ImageLoader {
private ImageView imageView;
private String mUrl="";
@SuppressLint("HandlerLeak")
public Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(imageView.getTag().equals(mUrl)){//根据tag来判断图片加载,防止图片加载错位
imageView.setImageBitmap((Bitmap) msg.obj);
}
}
};


/**
* 用线程的方式来获取图片数据
* @description:
* @author ldm
* @date 2015-8-11 下午1:54:57
*/
public void loaderImageThread(ImageView iv, final String url) {
imageView = iv;
mUrl=url;
new Thread() {
@Override
public void run() {
super.run();
getBitmapByUrl(url);
}
}.start();
}


/**
*从url中获取到Bitmap
* @description:
* @author ldm
* @date 2015-8-11 下午1:55:12
*/
public Bitmap getBitmapByUrl(String urlStr) {
Bitmap bitmap = null;
InputStream is = null;
try {
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
is = new BufferedInputStream(con.getInputStream());
bitmap = BitmapFactory.decodeStream(is);
Message msg = Message.obtain();
msg.obj = bitmap;
handler.sendMessage(msg);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}
}

然后我们就要有ListView的数据适配器类DataAdapter中,把holder.iv.setImageResource(R.drawable.ic_launcher);这句代码改成以下两句代码就可以了:

                 holder.iv.setTag(list.get(arg0).getImgUrl());//为ImageView设置tag
new ImageLoader().loaderImageThread(holder.iv, list.get(arg0).getImgUrl());//用线程加载图片

通过以上的相关操作,就实现了ListView中展示的所有数据都来自我们从网络请求的数据。

1 0
原创粉丝点击