ListView异步加载图片是非常实用的方法,凡是是要通过网络获取图片资源一般使用这种方法比较好,用户体验好,下面就说实现方法,先贴上主方法的代码:

Java代码 复制代码  收藏代码
  1. package cn.wangmeng.test;   
  2.   
  3. import java.io.IOException;   
  4. import java.io.InputStream;   
  5. import java.lang.ref.SoftReference;   
  6. import java.net.MalformedURLException;   
  7. import java.net.URL;   
  8. import java.util.HashMap;   
  9.   
  10. import android.graphics.drawable.Drawable;   
  11. import android.os.Handler;   
  12. import android.os.Message;   
  13.   
  14. public class AsyncImageLoader {   
  15.   
  16.      private HashMap<String, SoftReference<Drawable>> p_w_picpathCache;   
  17.          
  18.          public AsyncImageLoader() {   
  19.              p_w_picpathCache = new HashMap<String, SoftReference<Drawable>>();   
  20.          }   
  21.          
  22.          public Drawable loadDrawable(final String p_w_picpathUrl, final ImageCallback p_w_picpathCallback) {   
  23.              if (p_w_picpathCache.containsKey(p_w_picpathUrl)) {   
  24.                  SoftReference<Drawable> softReference = p_w_picpathCache.get(p_w_picpathUrl);   
  25.                  Drawable drawable = softReference.get();   
  26.                  if (drawable != null) {   
  27.                      return drawable;   
  28.                  }   
  29.              }   
  30.              final Handler handler = new Handler() {   
  31.                  public void handleMessage(Message message) {   
  32.                      p_w_picpathCallback.p_w_picpathLoaded((Drawable) message.obj, p_w_picpathUrl);   
  33.                  }   
  34.              };   
  35.              new Thread() {   
  36.                  @Override  
  37.                  public void run() {   
  38.                      Drawable drawable = loadImageFromUrl(p_w_picpathUrl);   
  39.                      p_w_picpathCache.put(p_w_picpathUrl, new SoftReference<Drawable>(drawable));   
  40.                      Message message = handler.obtainMessage(0, drawable);   
  41.                      handler.sendMessage(message);   
  42.                  }   
  43.              }.start();   
  44.              return null;   
  45.          }   
  46.          
  47.         public static Drawable loadImageFromUrl(String url) {   
  48.             URL m;   
  49.             InputStream i = null;   
  50.             try {   
  51.                 m = new URL(url);   
  52.                 i = (InputStream) m.getContent();   
  53.             } catch (MalformedURLException e1) {   
  54.                 e1.printStackTrace();   
  55.             } catch (IOException e) {   
  56.                 e.printStackTrace();   
  57.             }   
  58.             Drawable d = Drawable.createFromStream(i, "src");   
  59.             return d;   
  60.         }   
  61.          
  62.          public interface ImageCallback {   
  63.              public void p_w_picpathLoaded(Drawable p_w_picpathDrawable, String p_w_picpathUrl);   
  64.          }   
  65.   
  66. }  
package cn.wangmeng.test;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class AsyncImageLoader {

	 private HashMap<String, SoftReference<Drawable>> p_w_picpathCache;
	  
	     public AsyncImageLoader() {
	    	 p_w_picpathCache = new HashMap<String, SoftReference<Drawable>>();
	     }
	  
	     public Drawable loadDrawable(final String p_w_picpathUrl, final ImageCallback p_w_picpathCallback) {
	         if (p_w_picpathCache.containsKey(p_w_picpathUrl)) {
	             SoftReference<Drawable> softReference = p_w_picpathCache.get(p_w_picpathUrl);
	             Drawable drawable = softReference.get();
	             if (drawable != null) {
	                 return drawable;
	             }
	         }
	         final Handler handler = new Handler() {
	             public void handleMessage(Message message) {
	                 p_w_picpathCallback.p_w_picpathLoaded((Drawable) message.obj, p_w_picpathUrl);
	             }
	         };
	         new Thread() {
	             @Override
	             public void run() {
	                 Drawable drawable = loadImageFromUrl(p_w_picpathUrl);
	                 p_w_picpathCache.put(p_w_picpathUrl, new SoftReference<Drawable>(drawable));
	                 Message message = handler.obtainMessage(0, drawable);
	                 handler.sendMessage(message);
	             }
	         }.start();
	         return null;
	     }
	  
		public static Drawable loadImageFromUrl(String url) {
			URL m;
			InputStream i = null;
			try {
				m = new URL(url);
				i = (InputStream) m.getContent();
			} catch (MalformedURLException e1) {
				e1.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			Drawable d = Drawable.createFromStream(i, "src");
			return d;
		}
	  
	     public interface ImageCallback {
	         public void p_w_picpathLoaded(Drawable p_w_picpathDrawable, String p_w_picpathUrl);
	     }

}


以上代码是实现异步获取图片的主方法,SoftReference是软引用,是为了更好的为了系统回收变量,重复的URL直接返回已有的资源,实现回调函数,让数据成功后,更新到UI线程。
几个辅助类文件:

Java代码 复制代码  收藏代码
  1. package cn.wangmeng.test;   
  2.   
  3. public class ImageAndText {   
  4.         private String p_w_picpathUrl;   
  5.         private String text;   
  6.   
  7.         public ImageAndText(String p_w_picpathUrl, String text) {   
  8.             this.p_w_picpathUrl = p_w_picpathUrl;   
  9.             this.text = text;   
  10.         }   
  11.         public String getImageUrl() {   
  12.             return p_w_picpathUrl;   
  13.         }   
  14.         public String getText() {   
  15.             return text;   
  16.         }   
  17. }  
package cn.wangmeng.test;

public class ImageAndText {
	    private String p_w_picpathUrl;
	    private String text;

	    public ImageAndText(String p_w_picpathUrl, String text) {
	        this.p_w_picpathUrl = p_w_picpathUrl;
	        this.text = text;
	    }
	    public String getImageUrl() {
	        return p_w_picpathUrl;
	    }
	    public String getText() {
	        return text;
	    }
}
Java代码 复制代码  收藏代码
  1. package cn.wangmeng.test;   
  2.   
  3. import android.view.View;   
  4. import android.widget.ImageView;   
  5. import android.widget.TextView;   
  6.   
  7. public class ViewCache {   
  8.   
  9.         private View baseView;   
  10.         private TextView textView;   
  11.         private ImageView p_w_picpathView;   
  12.   
  13.         public ViewCache(View baseView) {   
  14.             this.baseView = baseView;   
  15.         }   
  16.   
  17.         public TextView getTextView() {   
  18.             if (textView == null) {   
  19.                 textView = (TextView) baseView.findViewById(R.id.text);   
  20.             }   
  21.             return textView;   
  22.         }   
  23.   
  24.         public ImageView getImageView() {   
  25.             if (p_w_picpathView == null) {   
  26.                 p_w_picpathView = (ImageView) baseView.findViewById(R.id.p_w_picpath);   
  27.             }   
  28.             return p_w_picpathView;   
  29.         }   
  30.   
  31. }  
package cn.wangmeng.test;

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class ViewCache {

	    private View baseView;
	    private TextView textView;
	    private ImageView p_w_picpathView;

	    public ViewCache(View baseView) {
	        this.baseView = baseView;
	    }

	    public TextView getTextView() {
	        if (textView == null) {
	            textView = (TextView) baseView.findViewById(R.id.text);
	        }
	        return textView;
	    }

	    public ImageView getImageView() {
	        if (p_w_picpathView == null) {
	            p_w_picpathView = (ImageView) baseView.findViewById(R.id.p_w_picpath);
	        }
	        return p_w_picpathView;
	    }

}


ViewCache是辅助获取adapter的子元素布局
 

Java代码 复制代码  收藏代码
  1. package cn.wangmeng.test;   
  2.   
  3. import java.util.List;   
  4.   
  5. import cn.wangmeng.test.AsyncImageLoader.ImageCallback;   
  6.   
  7. import android.app.Activity;   
  8. import android.graphics.drawable.Drawable;   
  9. import android.view.LayoutInflater;   
  10. import android.view.View;   
  11. import android.view.ViewGroup;   
  12. import android.widget.ArrayAdapter;   
  13. import android.widget.ImageView;   
  14. import android.widget.ListView;   
  15. import android.widget.TextView;   
  16.   
  17. public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {   
  18.   
  19.         private ListView listView;   
  20.         private AsyncImageLoader asyncImageLoader;   
  21.   
  22.         public ImageAndTextListAdapter(Activity activity, List<ImageAndText> p_w_picpathAndTexts, ListView listView) {   
  23.             super(activity, 0, p_w_picpathAndTexts);   
  24.             this.listView = listView;   
  25.             asyncImageLoader = new AsyncImageLoader();   
  26.         }   
  27.   
  28.         public View getView(int position, View convertView, ViewGroup parent) {   
  29.             Activity activity = (Activity) getContext();   
  30.   
  31.             // Inflate the views from XML   
  32.             View rowView = convertView;   
  33.             ViewCache viewCache;   
  34.             if (rowView == null) {   
  35.                 LayoutInflater inflater = activity.getLayoutInflater();   
  36.                 rowView = inflater.inflate(R.layout.p_w_picpath_and_text_row, null);   
  37.                 viewCache = new ViewCache(rowView);   
  38.                 rowView.setTag(viewCache);   
  39.             } else {   
  40.                 viewCache = (ViewCache) rowView.getTag();   
  41.             }   
  42.             ImageAndText p_w_picpathAndText = getItem(position);   
  43.   
  44.             // Load the p_w_picpath and set it on the ImageView   
  45.             String p_w_picpathUrl = p_w_picpathAndText.getImageUrl();   
  46.             ImageView p_w_picpathView = viewCache.getImageView();   
  47.             p_w_picpathView.setTag(p_w_picpathUrl);   
  48.             Drawable cachedImage = asyncImageLoader.loadDrawable(p_w_picpathUrl, new ImageCallback() {   
  49.                 public void p_w_picpathLoaded(Drawable p_w_picpathDrawable, String p_w_picpathUrl) {   
  50.                     ImageView p_w_picpathViewByTag = (ImageView) listView.findViewWithTag(p_w_picpathUrl);   
  51.                     if (p_w_picpathViewByTag != null) {   
  52.                         p_w_picpathViewByTag.setImageDrawable(p_w_picpathDrawable);   
  53.                     }   
  54.                 }   
  55.             });   
  56.             if (cachedImage == null) {   
  57.                 p_w_picpathView.setImageResource(R.drawable.default_p_w_picpath);   
  58.             }else{   
  59.                 p_w_picpathView.setImageDrawable(cachedImage);   
  60.             }   
  61.             // Set the text on the TextView   
  62.             TextView textView = viewCache.getTextView();   
  63.             textView.setText(p_w_picpathAndText.getText());   
  64.   
  65.             return rowView;   
  66.         }   
  67.   
  68. }  
package cn.wangmeng.test;

import java.util.List;

import cn.wangmeng.test.AsyncImageLoader.ImageCallback;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {

	    private ListView listView;
	    private AsyncImageLoader asyncImageLoader;

	    public ImageAndTextListAdapter(Activity activity, List<ImageAndText> p_w_picpathAndTexts, ListView listView) {
	        super(activity, 0, p_w_picpathAndTexts);
	        this.listView = listView;
	        asyncImageLoader = new AsyncImageLoader();
	    }

	    public View getView(int position, View convertView, ViewGroup parent) {
	        Activity activity = (Activity) getContext();

	        // Inflate the views from XML
	        View rowView = convertView;
	        ViewCache viewCache;
	        if (rowView == null) {
	            LayoutInflater inflater = activity.getLayoutInflater();
	            rowView = inflater.inflate(R.layout.p_w_picpath_and_text_row, null);
	            viewCache = new ViewCache(rowView);
	            rowView.setTag(viewCache);
	        } else {
	            viewCache = (ViewCache) rowView.getTag();
	        }
	        ImageAndText p_w_picpathAndText = getItem(position);

	        // Load the p_w_picpath and set it on the ImageView
	        String p_w_picpathUrl = p_w_picpathAndText.getImageUrl();
	        ImageView p_w_picpathView = viewCache.getImageView();
	        p_w_picpathView.setTag(p_w_picpathUrl);
	        Drawable cachedImage = asyncImageLoader.loadDrawable(p_w_picpathUrl, new ImageCallback() {
	            public void p_w_picpathLoaded(Drawable p_w_picpathDrawable, String p_w_picpathUrl) {
	                ImageView p_w_picpathViewByTag = (ImageView) listView.findViewWithTag(p_w_picpathUrl);
	                if (p_w_picpathViewByTag != null) {
	                    p_w_picpathViewByTag.setImageDrawable(p_w_picpathDrawable);
	                }
	            }
	        });
			if (cachedImage == null) {
				p_w_picpathView.setImageResource(R.drawable.default_p_w_picpath);
			}else{
				p_w_picpathView.setImageDrawable(cachedImage);
			}
	        // Set the text on the TextView
	        TextView textView = viewCache.getTextView();
	        textView.setText(p_w_picpathAndText.getText());

	        return rowView;
	    }

}


ImageAndTextListAdapter是实现ListView的Adapter,里面有个技巧就是p_w_picpathView.setTag(p_w_picpathUrl),setTag是存储数据的,这样是为了保证在回调函数时,listview去更新自己对应item,大家仔细阅读就知道了。
最后贴出布局文件:
 

Xml代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.               android:orientation="horizontal"  
  4.               android:layout_width="fill_parent"  
  5.               android:layout_height="wrap_content">  
  6.   
  7.         <ImageView android:id="@+id/p_w_picpath"  
  8.                    android:layout_width="wrap_content"  
  9.                    android:layout_height="wrap_content"  
  10.                    />  
  11.   
  12.         <TextView android:id="@+id/text"  
  13.                   android:layout_width="wrap_content"  
  14.                   android:layout_height="wrap_content"/>  
  15.   
  16. </LinearLayout>  
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content">

        <ImageView android:id="@+id/p_w_picpath"
                   android:layout_width="wrap_content"
                   android:layout_height="wrap_content"
                   />

        <TextView android:id="@+id/text"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"/>

</LinearLayout>

http://www.iteye.com/topic/685986

原文地址:http://blog.jteam.nl/2009/09/17/exploring-the-world-of-android-part-2