这个在Listview 上异步刷新缓存图片弄了一天还没搞定,我原先的想法是在getview里开一个new Thread来获取缩略图,但是引起的问题是只会在listview的最后一行进行图片刷新。于是在网上找了下资料,也尝试了很多,终于在看到这篇文章时让我眼前一亮,最后试验成功。
参考的文章地址:http://blog.csdn.net/onerain88/article/details/7008409
先看截图
上面的qq.jpg和yu.jpg就是效果的实现,因为美工还没有发过来合适的图片。所以有些图片看上去很难看。。。
下面是主要的实现代码。
首先是一个处理网络图片的类AsyncBitmapLoader,这个类有两个缓存,如果两个缓存都没有找到,才去网络下载
- package cn.jtang.netdisk.utils;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.lang.ref.SoftReference;
- import java.util.HashMap;
- import java.util.Map;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.Handler;
- import android.os.Message;
- import android.widget.ImageView;
- import cn.jtang.netdisk.mode.NotLoginException;
- public class AsyncBitmapLoader {
- //Map<String, String> filemap=new HashMap<String, String>();
- /**
- * 内存图片软引用缓冲
- */
- private HashMap<String, SoftReference<Bitmap>> imageCache = null;
- public AsyncBitmapLoader() {
- imageCache = new HashMap<String, SoftReference<Bitmap>>();
- }
- public Bitmap loadBitmap(final ImageView imageView, final String fileNameURL,
- final ImageCallBack imageCallBack) {
- // 在内存缓存中,则返回Bitmap对象
- if (imageCache.containsKey(fileNameURL)) {
- SoftReference<Bitmap> reference = imageCache.get(fileNameURL);
- Bitmap bitmap = reference.get();
- if (bitmap != null) {
- return bitmap;
- }
- } else {
- /**
- * 加上一个对本地缓存的查找
- */
- String bitmapName = fileNameURL
- .substring(fileNameURL.lastIndexOf("/") + 1);
- File cacheDir = new File("/mnt/sdcard/");
- File[] cacheFiles = cacheDir.listFiles();
- int i = 0;
- for (; i < cacheFiles.length; i++) {
- if (bitmapName.equals(cacheFiles[i].getName())) {
- break;
- }
- }
- if (i < cacheFiles.length) {
- return BitmapFactory.decodeFile("/mnt/sdcard/"
- + bitmapName);
- }
- }
- final Handler handler = new Handler() {
- /*
- * (non-Javadoc)
- *
- * @see android.os.Handler#handleMessage(android.os.Message)
- */
- @Override
- public void handleMessage(Message msg) {
- // TODO Auto-generated method stub
- imageCallBack.imageLoad(imageView, (Bitmap) msg.obj);
- }
- };
- // 如果不在内存缓存中,也不在本地(被jvm回收掉),则开启线程下载图片
- new Thread() {
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Thread#run()
- */
- @Override
- public void run() {
- // TODO Auto-generated method stub
- //InputStream bitmapIs = HttpUtils.getStreamFromURL(imageURL);
- HttpCookieUtils httpCookieUtils=new HttpCookieUtils();
- String imgName = null;
- try {
- imgName = httpCookieUtils.preview(fileNameURL, "40", "40");
- } catch (NotLoginException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- } catch (IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- //这里是我根据我自己的需求,改变的,如果你有自己的需求,都在下面进行处理
- Bitmap bitmap=BitmapUtils.getHttpBitmap(Constants.API_HOST+Constants.API_SHOW+imgName);
- imageCache.put(fileNameURL, new SoftReference<Bitmap>(bitmap));
- Message msg = handler.obtainMessage(0, bitmap);
- handler.sendMessage(msg);
- File dir = new File("/mnt/sdcard/");
- if (!dir.exists()) {
- dir.mkdirs();
- }
- File bitmapFile = new File("/mnt/sdcard/"
- + fileNameURL.substring(fileNameURL.lastIndexOf("/") + 1));
- if (!bitmapFile.exists()) {
- try {
- bitmapFile.createNewFile();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- FileOutputStream fos;
- try {
- fos = new FileOutputStream(bitmapFile);
- bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
- fos.close();
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }.start();
- return null;
- }
- /**
- * 回调接口
- *
- * @author onerain
- *
- */
- public interface ImageCallBack {
- public void imageLoad(ImageView imageView, Bitmap bitmap);
- }
- }
接下来就是适配器,我创建了FileListAdapter
- public class FileListAdapter extends BaseAdapter {
- private Context context; // 运行上下文
- private List<Files> groupList = new ArrayList<Files>(); // 所有文件及文件夹
- // private List<List<String>> childList = new
- // ArrayList<List<String>>();//文件集合
- private LayoutInflater listContainer; // 视图容器
- private Files files;
- private boolean isOk;
- private boolean isFirst = true;
- private Handler handler;
- private ViewHolder holder;
- private AsyncBitmapLoader asyncLoader = null;
- //原来每个控件都设置为static。导致在绘画和重命名时出现错位,删除就ok了
- static class ViewHolder {
- Button downButton;
- Button friendButton;
- Button shareButton;
- Button renameButton;
- Button deleteButton;
- Button select_img;
- ImageView img_isView, imgfile;
- TextView fileName, fileDate;
- }
- public FileListAdapter(Context context, List<Files> groups) {
- this.context = context;
- this.groupList = groups;
- listContainer = LayoutInflater.from(context);
- this.asyncLoader = new AsyncBitmapLoader();
- }
- @Override
- public int getCount() {
- // TODO Auto-generated method stub
- return groupList.size();
- }
- @Override
- public Object getItem(int position) {
- // TODO Auto-generated method stub
- return groupList.get(position);
- }
- @Override
- public long getItemId(int position) {
- // TODO Auto-generated method stub
- return position;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- // TODO Auto-generated method stub
- if (convertView == null) {
- convertView = listContainer.inflate(R.layout.item_filelist, null);
- holder = new ViewHolder();
- // 初始化绑定控件
- holder.imgfile = (ImageView) convertView
- .findViewById(R.id.img_fileimg);
- holder.deleteButton = (Button) convertView
- .findViewById(R.id.btn_delete);
- holder.downButton = (Button) convertView
- .findViewById(R.id.btn_download);
- holder.friendButton = (Button) convertView
- .findViewById(R.id.btn_friend);
- holder.renameButton = (Button) convertView
- .findViewById(R.id.btn_rename);
- holder.shareButton = (Button) convertView
- .findViewById(R.id.btn_share);
- holder.fileName = (TextView) convertView
- .findViewById(R.id.txt_fileName);
- holder.fileDate = (TextView) convertView
- .findViewById(R.id.txt_fileDate);
- holder.select_img = (Button) convertView
- .findViewById(R.id.btn_select);
- holder.img_isView = (ImageView) convertView
- .findViewById(R.id.img_checkimg);
- } else {
- holder = (ViewHolder) convertView.getTag();
- }
- // 进行初始化赋值
- initData(convertView, position);
- return convertView;
- }
- private void initData(View convertView, final int position) {
- // TODO Auto-generated method stub
- Files files = new Files();
- files = groupList.get(position);
- holder.fileName.setText(files.getFileName());
- // 初始化为未展开
- if (convertView.getMeasuredHeight() == 95
- || convertView.getMeasuredHeight() == 96) {
- ViewGroup.LayoutParams params = convertView.getLayoutParams();
- params.height = convertView.getMeasuredHeight() - 40;
- convertView.setLayoutParams(params);
- }
- // 判断是文件
- if (files.isFile()) {
- String fileType = files.getFileName().substring(
- files.getFileName().lastIndexOf("."),
- files.getFileName().length());
- holder.fileDate.setText(files.getLastModified() + " "
- + files.getLength());
- holder.downButton.setText("下载");
- holder.downButton.setTag("下载");
- System.out.println("fileType" + fileType);
- if (fileType.equals(".jpg") || fileType.equals(".png")
- || fileType.equals(".gif") || fileType.equals(".Jpeg")
- || fileType.equals(".bmp")) {
- holder.imgfile.setImageBitmap(null);
- // 根据图片URL去查找内存缓存有没有对应的Bitmap对象,并传递回调方法,如果没有,则等下载完毕回调
- Bitmap bitmap = asyncLoader.loadBitmap(holder.imgfile,
- groupList.get(position).getPath(), new ImageCallBack() {
- @Override
- public void imageLoad(ImageView imageView,
- Bitmap bitmap) {
- // TODO Auto-generated method stub
- imageView.setImageBitmap(bitmap);
- }
- });
- if (bitmap == null) {
- holder.imgfile.setImageResource(R.drawable.ic_launcher);
- } else {
- holder.imgfile.setImageBitmap(bitmap);
- }
- }
- } else {
- holder.fileDate.setText(files.getLastModified());
- holder.downButton.setText("打开");
- holder.downButton.setTag("打开");
- groupList.get(position).setFileImg("file");
- holder.imgfile.setBackgroundResource(R.drawable.img_filelist);
- }
- }
- }