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 ...
随机推荐
- Entity Framework 泛型使用
因为增删改查是我们常用到的方法,我们不可能每个数据模型都去完成增删改查,这样的办法太笨拙了.我们可以写个父类(包含增删改查),然后让所有的数据模型类继承该父类.那就要求我们的父类必须使用泛型来实现. ...
- database first表更新一个表会更新所有的model,包括添加验证代码,解决办法
因为model类是自动生成的,重新生成后会覆盖自己的修改.一个比较合理做法,就是用 partial class的方式来实现. 比如有一个Model类: Movie.那我们就可以添加一个局部类文件,局部 ...
- 56.ISE综合,在chipscope信号列表看不到
代码写好后,进行逻辑综合,在chipscope上添加被触发的信号时,发现有些在信号列表里看不到,这是因为这些信号没有参与到逻辑电路设计中,产生不想关的电路,综合器会默认优化资源. 还有一种情况是,对于 ...
- ASP.NET中Global.asax 文件是什么?
Global.asax 文件,有时候叫做 ASP.NET 应用程序文件,提供了一种在一个中心位置响应应用程序级或模块级事件的方法.你可以使用这个文件实现应用程序安全性以及其它一些任务.下面让我们详细看 ...
- spring注解注入失败一个原因
所有的注解看起来都没有任何问题,最后是由于web-xml配置问题. 由于缺少监听器org.springframework.web.context.ContextLoaderListener, 导致无法 ...
- OC学习笔记之属性详解和易错点
属性的概念在OC1.0中就存在,格式是定义实例变量,然后定义setter和getter方法,用点操作符操作属性 举例,类的接口部分 @interface Father : NSObject { NSI ...
- html5+ plus和phoneGap、cordova的比较
偶遇大神言论,摘录 phonegap出的早,自然用的人多.phonegap自己的定位是混合开发hybrid,用原生+js:HBuilder的定位是纯js搞定一切.5+ 和 phonegap在能力.性能 ...
- Careercup - Google面试题 - 5661939564806144
2014-05-06 01:40 题目链接 原题: Give a N*N matrix, print it out diagonally. Follow up, if it is a M*N matr ...
- dp--poj1458最长公共子序列
很水的一题 输入串a与串b: Dp[i][j]表示a串中1~i与b串中1~j的子串的最长公共子序列. Max{dp[i-1][j], dp[i][j-1]} (a[i]!=b[j]) Dp ...
- Asp.net 导入Excel(服务器不带Office)
#region 把excel文件转换为DataSet. /// <summary> /// 把excel文件转换为DataSet. /// </summary> /// < ...