android listview 加载图片错乱(错位)
2、内存缓存+文件缓存
3、内存缓存中网上很多是采用SoftReference来防止堆溢出,这儿严格限制只能使用最大JVM内存的1/4
4、对下载的图片进行按比例缩放,以减少内存的消耗
具体的代码里面说明。先放上内存缓存类的代码MemoryCache.java:
public class MemoryCache {
- private static final String TAG = "MemoryCache";
- // 放入缓存时是个同步操作
- // LinkedHashMap构造方法的最后一个参数true代表这个map里的元素将按照最近使用次数由少到多排列,即LRU
- // 这样的好处是如果要将缓存中的元素替换,则先遍历出最近最少使用的元素来替换以提高效率
- private Map<String, Bitmap> cache = Collections
- , 1.5f, true));
- // 缓存中图片所占用的字节,初始0,将通过此变量严格控制缓存所占用的堆内存
- ;// current allocated size
- // 缓存只能占用的最大堆内存
- ;// max memory in bytes
- public MemoryCache() {
- // use 25% of available heap size
- );
- }
- public void setLimit(long new_limit) {
- limit = new_limit;
- . / 1024. + "MB");
- }
- public Bitmap get(String id) {
- try {
- if (!cache.containsKey(id))
- return null;
- return cache.get(id);
- } catch (NullPointerException ex) {
- return null;
- }
- }
- public void put(String id, Bitmap bitmap) {
- try {
- if (cache.containsKey(id))
- size -= getSizeInBytes(cache.get(id));
- cache.put(id, bitmap);
- size += getSizeInBytes(bitmap);
- checkSize();
- } catch (Throwable th) {
- th.printStackTrace();
- }
- }
- /**
- * 严格控制堆内存,如果超过将首先替换最近最少使用的那个图片缓存
- *
- */
- private void checkSize() {
- Log.i(TAG, "cache size=" + size + " length=" + cache.size());
- if (size > limit) {
- // 先遍历最近最少使用的元素
- Iterator<Entry<String, Bitmap>> iter = cache.entrySet().iterator();
- while (iter.hasNext()) {
- Entry<String, Bitmap> entry = iter.next();
- size -= getSizeInBytes(entry.getValue());
- iter.remove();
- if (size <= limit)
- break;
- }
- Log.i(TAG, "Clean cache. New size " + cache.size());
- }
- }
- public void clear() {
- cache.clear();
- }
- /**
- * 图片占用的内存
- *
- * @param bitmap
- * @return
- */
- long getSizeInBytes(Bitmap bitmap) {
- if (bitmap == null)
- ;
- return bitmap.getRowBytes() * bitmap.getHeight();
- }
- 也可以使用SoftReference,代码会简单很多,但是推荐上面的方法。
- public class MemoryCache {
- private Map<String, SoftReference<Bitmap>> cache = Collections
- .synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());
- public Bitmap get(String id) {
- if (!cache.containsKey(id))
- return null;
- SoftReference<Bitmap> ref = cache.get(id);
- return ref.get();
- }
- public void put(String id, Bitmap bitmap) {
- cache.put(id, new SoftReference<Bitmap>(bitmap));
- }
- public void clear() {
- cache.clear();
- }
- }
- 下面是文件缓存类的代码FileCache.java
- public class FileCache {
- private File cacheDir;
- public FileCache(Context context) {
- // 如果有SD卡则在SD卡中建一个LazyList的目录存放缓存的图片
- // 没有SD卡就放在系统的缓存目录中
- if (android.os.Environment.getExternalStorageState().equals(
- android.os.Environment.MEDIA_MOUNTED))
- cacheDir = new File(
- android.os.Environment.getExternalStorageDirectory(),
- "LazyList");
- else
- cacheDir = context.getCacheDir();
- if (!cacheDir.exists())
- cacheDir.mkdirs();
- }
- public File getFile(String url) {
- // 将url的hashCode作为缓存的文件名
- String filename = String.valueOf(url.hashCode());
- // Another possible solution
- // String filename = URLEncoder.encode(url);
- File f = new File(cacheDir, filename);
- return f;
- }
- public void clear() {
- File[] files = cacheDir.listFiles();
- if (files == null)
- return;
- for (File f : files)
- f.delete();
- }
- }
最后最重要的加载图片的类,ImageLoader.java
- public class ImageLoader {
- MemoryCache memoryCache = new MemoryCache();
- FileCache fileCache;
- private Map<ImageView, String> imageViews = Collections
- .synchronizedMap(new WeakHashMap<ImageView, String>());
- // 线程池
- ExecutorService executorService;
- public ImageLoader(Context context) {
- fileCache = new FileCache(context);
- );
- }
- // 当进入listview时默认的图片,可换成你自己的默认图片
- final int stub_id = R.drawable.stub;
- // 最主要的方法
- public void DisplayImage(String url, ImageView imageView) {
- imageViews.put(imageView, url);
- // 先从内存缓存中查找
- Bitmap bitmap = memoryCache.get(url);
- if (bitmap != null)
- imageView.setImageBitmap(bitmap);
- else {
- // 若没有的话则开启新线程加载图片
- queuePhoto(url, imageView);
- imageView.setImageResource(stub_id);
- }
- }
- private void queuePhoto(String url, ImageView imageView) {
- PhotoToLoad p = new PhotoToLoad(url, imageView);
- executorService.submit(new PhotosLoader(p));
- }
- private Bitmap getBitmap(String url) {
- File f = fileCache.getFile(url);
- // 先从文件缓存中查找是否有
- Bitmap b = decodeFile(f);
- if (b != null)
- return b;
- // 最后从指定的url中下载图片
- try {
- Bitmap bitmap = null;
- URL imageUrl = new URL(url);
- HttpURLConnection conn = (HttpURLConnection) imageUrl
- .openConnection();
- );
- );
- conn.setInstanceFollowRedirects(true);
- InputStream is = conn.getInputStream();
- OutputStream os = new FileOutputStream(f);
- CopyStream(is, os);
- os.close();
- bitmap = decodeFile(f);
- return bitmap;
- } catch (Exception ex) {
- ex.printStackTrace();
- return null;
- }
- }
- // decode这个图片并且按比例缩放以减少内存消耗,虚拟机对每张图片的缓存大小也是有限制的
- private Bitmap decodeFile(File f) {
- try {
- // decode image size
- BitmapFactory.Options o = new BitmapFactory.Options();
- o.inJustDecodeBounds = true;
- BitmapFactory.decodeStream(new FileInputStream(f), null, o);
- // Find the correct scale value. It should be the power of 2.
- ;
- int width_tmp = o.outWidth, height_tmp = o.outHeight;
- ;
- while (true) {
- < REQUIRED_SIZE
- < REQUIRED_SIZE)
- break;
- ;
- ;
- ;
- }
- // decode with inSampleSize
- BitmapFactory.Options o2 = new BitmapFactory.Options();
- o2.inSampleSize = scale;
- return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
- } catch (FileNotFoundException e) {
- }
- return null;
- }
- // Task for the queue
- private class PhotoToLoad {
- public String url;
- public ImageView imageView;
- public PhotoToLoad(String u, ImageView i) {
- url = u;
- imageView = i;
- }
- }
- class PhotosLoader implements Runnable {
- PhotoToLoad photoToLoad;
- PhotosLoader(PhotoToLoad photoToLoad) {
- this.photoToLoad = photoToLoad;
- }
- @Override
- public void run() {
- if (imageViewReused(photoToLoad))
- return;
- Bitmap bmp = getBitmap(photoToLoad.url);
- memoryCache.put(photoToLoad.url, bmp);
- if (imageViewReused(photoToLoad))
- return;
- BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
- // 更新的操作放在UI线程中
- Activity a = (Activity) photoToLoad.imageView.getContext();
- a.runOnUiThread(bd);
- }
- }
- /**
- * 防止图片错位
- *
- * @param photoToLoad
- * @return
- */
- boolean imageViewReused(PhotoToLoad photoToLoad) {
- String tag = imageViews.get(photoToLoad.imageView);
- if (tag == null || !tag.equals(photoToLoad.url))
- return true;
- return false;
- }
- // 用于在UI线程中更新界面
- class BitmapDisplayer implements Runnable {
- Bitmap bitmap;
- PhotoToLoad photoToLoad;
- public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
- bitmap = b;
- photoToLoad = p;
- }
- public void run() {
- if (imageViewReused(photoToLoad))
- return;
- if (bitmap != null)
- photoToLoad.imageView.setImageBitmap(bitmap);
- else
- photoToLoad.imageView.setImageResource(stub_id);
- }
- }
- public void clearCache() {
- memoryCache.clear();
- fileCache.clear();
- }
- public static void CopyStream(InputStream is, OutputStream os) {
- ;
- try {
- byte[] bytes = new byte[buffer_size];
- for (;;) {
- , buffer_size);
- )
- break;
- , count);
- }
- } catch (Exception ex) {
- }
- }
- }
写道
- a.runOnUiThread(...);
- 在你的程序中的基本用法:
- ImageLoader imageLoader=new ImageLoader(context);
- ...
- imageLoader.DisplayImage(url, imageView);
- 比如你的放在你的ListView的adapter的getView()方法中,当然也适用于GridView。
- adapter的代码:
- class MyAdapter extends BaseAdapter{
- private String urls[];
- private Context context;
- public int getCount() {
- return urls.length;
- }
- public void setData(String[] urls) {
- this.urls = urls;
- }
- public Object getItem(int position) {
- return urls[position];
- }
- public long getItemId(int position) {
- return position;
- }
- public View getView(int position, View convertView, ViewGroup parent) {
- ViewHolder holder = null;
- if(convertView == null){
- holder = new ViewHolder();
- convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.listview_item, null);
- holder.imageView = (ImageView) convertView.findViewById(R.id.imageview);
- convertView.setTag(holder);
- }else{
- holder = (ViewHolder) convertView.getTag();
- }
- System.out.println("开始下载图片 --------------position--------==== " + position);
- //把imageLoader传进adapter里面来
- imageLoader.displayImage(urls[position], holder.imageView);
- return convertView;
- }
- class ViewHolder{
- ImageView imageView;
- }
- }
写道
android listview 加载图片错乱(错位)的更多相关文章
- Android Glide加载图片时转换为圆形、圆角、毛玻璃等图片效果
Android Glide加载图片时转换为圆形.圆角.毛玻璃等图片效果 附录1简单介绍了Android开源的图片加载框架.在实际的开发中,虽然Glide解决了快速加载图片的问题,但还有一个问题悬 ...
- 演化理解 Android 异步加载图片(转)
演化理解 Android 异步加载图片(转)http://www.cnblogs.com/CJzhang/archive/2011/10/20/2218474.html
- 【Android】ListView、RecyclerView异步加载图片引起错位问题
今天在RecyclerView列表里遇到一个情况,它包含300条数据,每项包含一个图片,发现在首次载入时,由于本地没图,请求网络的时候:快速滑动导致了图片错位.闪烁的问题. 原理的话有一篇已经说的很清 ...
- 解决ListView异步加载图片错乱问题 .
发一个异步图片加载控件.网上也有大把的异步网络加载图片的控件,但是有一个问题,异步加载会造成列表中的图片混乱,因为列表的每一项的View都可能被重用,异步加载的时候多个异步线程引用到了同一个View将 ...
- [Android]异步加载图片,内存缓存,文件缓存,imageview显示图片时增加淡入淡出动画
以下内容为原创,欢迎转载,转载请注明 来自天天博客:http://www.cnblogs.com/tiantianbyconan/p/3574131.html 这个可以实现ImageView异步加载 ...
- listview加载图片显示
Adapter: ---- //adapter的构造方法: 参数1 为url数组: public static String[] mList;// 讲url保村在静态的String[] 中 在 ...
- 实例演示Android异步加载图片
本文给大家演示异步加载图片的分析过程.让大家了解异步加载图片的好处,以及如何更新UI.首先给出main.xml布局文件:简单来说就是 LinearLayout 布局,其下放了2个TextView和5个 ...
- 实例演示Android异步加载图片(转)
本文给大家演示异步加载图片的分析过程.让大家了解异步加载图片的好处,以及如何更新UI.首先给出main.xml布局文件:简单来说就是 LinearLayout 布局,其下放了2个TextView和5个 ...
- 演化理解 Android 异步加载图片
原文:http://www.cnblogs.com/ghj1976/archive/2011/05/06/2038738.html#3018499 在学习"Android异步加载图像小结&q ...
随机推荐
- Linux下cron的使用
cron是一个linux下的定时执行工具,可以在无需人工干预的情况下运行作业.由于Cron 是Linux的内置服务,但它不自动起来,可以用以下的方法启动.关闭这个服务: /sbin/service c ...
- python 安装scrapy
1. 首先你先得安装PYTHON...还是推荐2.7吧,之前装了3.3似乎和这个世界格格不入...先装个2.7. 并将python加入系统的环境变量. 2. 去scrapy 官网下载最新版本的scra ...
- mysql 字段编码该为utf8mb4
alter table c_comment modify column content varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unico ...
- heap size eclipse 堆内存
可以根据eclipse 或 myeclipse heapstats 使用情况调整堆内存大小,heap size 设置,-vmargs-Xms256-Xmx1024 ,其中Xms表示初始值,Xmx表示最 ...
- Android -- TabHost、Fragment、状态保存、通信
工程结构 TabAFm到Ta ...
- 团队项目——二手书店(NABC分析)
特色:可发布 N:登陆用户可自行发布售书信息,为学生提供一个网上交易旧书的平台. A:后台数据库管理,对于新登陆的用户信息加以整合,统一发布. B:想出手旧书的学生可从中获取不小的利益,而且也可以实现 ...
- JS获取字符串长度(英文占1个字符,中文汉字占2个字符)
方法一: String.prototype.gblen = function() { var len = 0; for (var i = 0; i < this.length; i++) { i ...
- Html5 Canvas动画旋转的小方块;
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...
- [转载]ubuntu的版本
http://bbs.chinaunix.net/thread-2126589-2-1.html 希望他说的是对的 ubuntu 发布的linux里面有一个非常具有迷惑性的版本-desktop.因为 ...
- xml基础学习笔记04
今天继续xml学习,主要是:SimpleXML快速解析文档.xml与数组相互转换 .博客中只是简单的做一个学习记录.积累.更加详细的使用方法,可以查看php手册 1.SimpleXML快速解析文档 前 ...