项目开发中我们需要从网络获取图片显示到控件中,很多开源框架如Picasso可以实现图片下载和缓存功能。这里介绍的是一种简易的网络图片获取方式并把它显示到ListView中。

本案例实现的效果如下:

项目结构:

根据部分开源代码,我修改并封装了一个网络图片加载的工具类GetImageByUrl,通过调用其中的setImage方法,传入待显示图片的ImageView控件和该图片的url路径这两个参数即可实现获取网络图片的功能。

GetImageByUrl.java

package com.leo.imagelistview.util;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView; /**
* 根据图片url路径获取图片
*
* @author LeoLeoHan
*
*/
public class GetImageByUrl { private PicHandler pic_hdl;
private ImageView imgView;
private String url; /**
* 通过图片url路径获取图片并显示到对应控件上
*
* @param imgView
* @param url
*/
public void setImage(ImageView imgView, String url) {
this.url = url;
this.imgView = imgView;
pic_hdl = new PicHandler();
Thread t = new LoadPicThread();
t.start();
} class LoadPicThread extends Thread {
@Override
public void run() {
Bitmap img = getUrlImage(url);
System.out.println(img + "---");
Message msg = pic_hdl.obtainMessage();
msg.what = 0;
msg.obj = img;
pic_hdl.sendMessage(msg);
}
} class PicHandler extends Handler { @Override
public void handleMessage(Message msg) {
Bitmap myimg = (Bitmap) msg.obj;
imgView.setImageBitmap(myimg);
} } public Bitmap getUrlImage(String url) {
Bitmap img = null;
try {
URL picurl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) picurl
.openConnection();
conn.setConnectTimeout(6000);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.connect();
InputStream is = conn.getInputStream();
img = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return img;
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81

下面的代码就是实现ListView显示网络图片。

首先创建一个自定义的布局文件images_item.xml和自定义的ImageAdapter。

images_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" > <ImageView
android:id="@+id/iv_image"
android:layout_width="80dp"
android:layout_height="80dp" /> <LinearLayout
android:layout_width="0dp"
android:layout_height="80dp"
android:layout_weight="1"
android:orientation="vertical" > <TextView
android:id="@+id/tv_url"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="15sp" />
</LinearLayout> </LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

ImageAdapter.java

package com.leo.imagelistview.adapter;

import java.util.List;
import java.util.Map; import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView; import com.leo.imagelistview.R;
import com.leo.imagelistview.util.GetImageByUrl; /**
*
* @author LeoLeoHan
*
*/
public class ImageAdapter extends BaseAdapter {
// 要显示的数据的集合
private List<Map<String, Object>> data;
// 接受上下文
private Context context;
// 声明内部类对象
private ViewHolder viewHolder; /**
* 构造函数
*
* @param context
* @param data
*/
public ImageAdapter(Context context, List<Map<String, Object>> data) {
this.context = context;
this.data = data;
} // 返回的总个数
@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
} // 返回每个条目对应的数据
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
} // 返回的id
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
} // 返回这个条目对应的控件对象
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 判断当前条目是否为null
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = View.inflate(context, R.layout.images_item, null);
viewHolder.iv_image = (ImageView) convertView
.findViewById(R.id.iv_image);
viewHolder.tv_url = (TextView) convertView
.findViewById(R.id.tv_url);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
} // 获取List集合中的map对象
Map<String, Object> map = data.get(position);
// 获取图片的url路径
String url = map.get("url").toString();
// 这里调用了图片加载工具类的setImage方法将图片直接显示到控件上
GetImageByUrl getImageByUrl = new GetImageByUrl();
getImageByUrl.setImage(viewHolder.iv_image, url);
viewHolder.tv_url.setText(url); return convertView;
} /**
* 内部类 记录单个条目中所有属性
*
* @author LeoLeoHan
*
*/
class ViewHolder {
public ImageView iv_image;
public TextView tv_url;
} }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100

MainActivity.java

package com.leo.imagelistview;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import com.leo.imagelistview.adapter.ImageAdapter; import android.app.Activity;
import android.os.Bundle;
import android.widget.BaseAdapter;
import android.widget.ListView; public class MainActivity extends Activity { private List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
//声明控件
private ListView lv_images; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // 获取ListView对象
lv_images = (ListView) findViewById(R.id.lv_images);
//获取数据
getData();
BaseAdapter adapter = new ImageAdapter(this, data);
//设置适配器
lv_images.setAdapter(adapter); } /**
* 简单添加一些网络图片的url路径
* 实际开发中url路径是从服务器中解析json数据
*/
public void getData() {
String url1 = "http://my.csdn.net/uploads/avatar/6/A/7/1_leoleohan.jpg";
String url2 = "http://img1.cache.netease.com/men/2014/6/2/2014060213070843617.jpg";
String url3 = "http://static2.businessinsider.com/image/522f7a076da811e1404b39a9-480-/jony-ive-9.png";
String url4 = "http://y0.ifengimg.com/8e16f14474b61551/2013/0731/rdn_51f878236017c.jpg"; Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("url", url1); Map<String, Object> map2 = new HashMap<String, Object>();
map2.put("url", url2); Map<String, Object> map3 = new HashMap<String, Object>();
map3.put("url", url3); Map<String, Object> map4 = new HashMap<String, Object>();
map4.put("url", url4); data.add(map1);
data.add(map2);
data.add(map3);
data.add(map4);
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" > <ListView
android:id="@+id/lv_images"
android:layout_width="match_parent"
android:layout_height="match_parent" /> </RelativeLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

转载来源:https://blog.csdn.net/LeoLeoHan/article/details/46553317

根据url路径获取图片并显示到ListView中的更多相关文章

  1. MVC中根据后台绝对路径读取图片并显示在IMG中

    数据库存取图片并在MVC3中显示在View中 根据路径读取图片: byte[] img = System.IO.File.ReadAllBytes(@"d:\xxxx.jpg"); ...

  2. Java通过图片url地址获取图片base64位字符串的两种方式

    工作中遇到通过图片的url获取图片base64位的需求.一开始是用网上的方法,通过工具类Toolkit,虽然实现的代码比较简短,不过偶尔会遇到图片转成base64位不正确的情况,至今不知道为啥. 之后 ...

  3. 通过url动态获取图片大小方法总结

    很多时候再项目中,我们往往需要先获取图片的大小再加载图片,但是某些特定场景,如用过cocos2d-js的人都知道,在它那里只能按比例缩放大小,是无法设置指定大小的图片的,这就是cocos2d-js 的 ...

  4. 根据图片url地址获取图片的宽高

    /** * 根据img获取图片的宽高 * @param img 图片地址 * @return 图片的对象,对象中图片的真实宽高 */ public BufferedImage getBufferedI ...

  5. 用Seam实现:图片上传 + 保存到数据库 + 从数据库读出图片并显示到页面中

    上传图片并保存到数据库 seam给我们提供了 s:fileUpload 标签以完成文件上传功能.使用该标签时,要在web.xml中声明一个Seam的过滤器: <filter> <fi ...

  6. 【Web】解决简书图片不显示问题“系统维护中,图片暂时无法加载”

    简书不显示图片的解决方法 首次编辑于2019-6-6 最近几天在浏览简书上的文章时,发现图片显示不出来,提示"系统维护中,图片暂时无法加载". 猜测应该是简书由于某种原因暂时屏蔽了 ...

  7. C# 通过URL获取图片并显示在PictureBox上的方法

    , ); System.Net.WebRequest webreq = System.Net.WebRequest.Create(url); System.Net.WebResponse webres ...

  8. vue 相对路径的图片 不显示问题

    例如 data () { return { img: '../../images/jifen/index/img_list_default_pic.jpg' //路径也没问题啊,怎么不显示呢,难道他瞎 ...

  9. 在Android中如何获取视频的第一帧图片并显示在一个ImageView中

    String path  = Environment.getExternalStorageDirectory().getPath(); MediaMetadataRetriever media = n ...

随机推荐

  1. zabbix3.4.7官方解释触发器

    函数   描述 参数 说明 abschange   最近获取值与之前获取值差的绝对值.   支持值的类型: float, int, str, text, log 例如: (最近获取值;之前获取值=ab ...

  2. HTTP的缓存策略

    etag 与 if-match https://www.cnblogs.com/huangzhilong/p/4999207.html https://juejin.im/post/5c136bd16 ...

  3. 使用mybatis generator插件,自动生成dao、dto、mapper等文件

    mybatis generator 介绍 mybatis generator中文文档http://mbg.cndocs.tk/ MyBatis Generator (MBG) 是一个Mybatis的代 ...

  4. Alpha冲刺10

    前言 队名:拖鞋旅游队 组长博客:https://www.cnblogs.com/Sulumer/p/10045588.html 作业博客:https://edu.cnblogs.com/campus ...

  5. 马凯军201771010116《面向对象程序设计(java)》第六周学习总结

    第一部分:理论知识学习部分 枚举是一种特殊的数据类型,之所以特殊是因为它既是一种类(class)类型却又比类型多了些特殊的约束,但是这些约束的存在也造就了枚举类型的简洁,安全性以及便捷性.创建枚举类型 ...

  6. python自学第10天,生成器

    列表生成式 print([i*2 for i in range(10)])#这就是列表生成式 #相当于下面的代码 a=[] for i in range(10): a.append(i*2) prin ...

  7. left join

    left join 是以A表为基础,A表即左表,B表即右表. 左表(A)的记录会全部显示,而右表(B)只会显示符合条件表达式的记录,如果在右表(B)中没有符合条件的记录,则记录不足的地方为NULL. ...

  8. supervisord.conf

    ; Sample supervisor config file.;; For more information on the config file, please see:; http://supe ...

  9. 渲染标签 - v-text

    <!DOCTYPE html><html><head>    <meta charset="utf-8">    <title ...

  10. java-ArrayList中去重复字符串或重复对象、LinkedList集合、泛型、增强for、静态导入、可变参数、asList()方法、集合嵌套

    1.去除ArrayList中重复字符串元素方式 * A:案例演示 * 需求:ArrayList去除集合中字符串的重复值(字符串的内容相同) * 思路:创建新集合方式 /** * A:案例演示 * 需求 ...