android ListView 异步加载图片

异步加载图片的目的只有一个:让用户体验更好

因为异步加载不利用主线程(UI线程)

一、源码结构:

android ListView 异步加载图片_第1张图片

二、异步图片加载器(实现异步加载的核心)

package com.ning.lazytest;

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>> imageCache;
	  
    public AsyncImageLoader() {
   	 imageCache = new HashMap<String, SoftReference<Drawable>>();
    }
 
    public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
        if (imageCache.containsKey(imageUrl)) {
            SoftReference<Drawable> softReference = imageCache.get(imageUrl);
            Drawable drawable = softReference.get();
            if (drawable != null) {
                return drawable;
            }
        }
        final Handler handler = new Handler() {
            public void handleMessage(Message message) {
                imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
            }
        };
        new Thread() {
            @Override
            public void run() {
                Drawable drawable = loadImageFromUrl(imageUrl);
                imageCache.put(imageUrl, 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 imageLoaded(Drawable imageDrawable, String imageUrl);
    }
}


三、ListView适配器

package com.ning.lazytest;

import java.util.List;

import com.ning.lazytest.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> imageAndTexts, ListView listView) {
        super(activity, 0, imageAndTexts);
        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.image_and_text_row, null);
            viewCache = new ViewCache(rowView);
            rowView.setTag(viewCache);
        } else {
            viewCache = (ViewCache) rowView.getTag();
        }
        ImageAndText imageAndText = getItem(position);

        // Load the image and set it on the ImageView
        String imageUrl = imageAndText.getImageUrl();
        ImageView imageView = viewCache.getImageView();
        imageView.setTag(imageUrl);
        Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback() {
            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
                ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
                if (imageViewByTag != null) {
                    imageViewByTag.setImageDrawable(imageDrawable);
                }
            }
        });
		if (cachedImage == null) {
			imageView.setImageResource(R.drawable.ic_launcher);
		}else{
			imageView.setImageDrawable(cachedImage);
		}
        // Set the text on the TextView
        TextView textView = viewCache.getTextView();
        textView.setText(imageAndText.getText());

        return rowView;
    }
}


四、ViewCache 即ListView的每一个Item

package com.ning.lazytest;

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

public class ViewCache {
	private View baseView;
    private TextView textView;
    private ImageView imageView;

    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 (imageView == null) {
            imageView = (ImageView) baseView.findViewById(R.id.image);
        }
        return imageView;
    }
}


五、Java Bean -> ImageAndText

package com.ning.lazytest;

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

	    public ImageAndText(String imageUrl, String text) {
	        this.imageUrl = imageUrl;
	        this.text = text;
	    }
	    public String getImageUrl() {
	        return imageUrl;
	    }
	    public String getText() {
	        return text;
	    }
}



六、Activity

package com.ning.lazytest;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class LazyLoadActivity extends Activity {
	private String[] myPicUrl = new String[]{
			"http://imguxv.penshow.cn/uploadfile/2010/04/06/thumb/thumb_250_0_20100406094922546.jpg",
			"http://imguxv.penshow.cn/uploadfile/2010/04/06/thumb/thumb_250_0_20100406095559309.jpg",
			"http://imguxv.penshow.cn/uploadfile/2010/04/06/thumb/thumb_250_0_20100406094916270.jpg",
			"http://imguxv.penshow.cn/uploadfile/2010/04/06/thumb/thumb_250_0_20100406085150824.jpg",
			"http://imguxv.penshow.cn/uploadfile/2010/04/18/thumb/thumb_250_0_20100418061054239.jpg",
			"http://imguxv.penshow.cn/uploadfile/2010/04/18/thumb/thumb_250_0_20100418052701708.jpg",
			"http://imguxv.penshow.cn/uploadfile/2010/04/18/thumb/thumb_250_0_20100418050521586.jpg"
	};
	private ImageAndText imageAndText = null;
	private List<ImageAndText> imageAndTexts = null;
	private ListView listView = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        imageAndTexts = new ArrayList<ImageAndText>();
        for(int i = 0;i < myPicUrl.length; i++){
        	imageAndText = new ImageAndText(myPicUrl[i], "Pic " + i);
        	imageAndTexts.add(imageAndText);
        	imageAndText = null;
        }
        listView = (ListView)findViewById(R.id.list);
        listView.setAdapter(new ImageAndTextListAdapter(LazyLoadActivity.this, imageAndTexts, listView));
    }
}


你可能感兴趣的:(android ListView 异步加载图片)