ListView远程加载图片

public class RemoteImageHelper {

    private final Map<String, Drawable> cache = new HashMap<String, Drawable>();

    public void loadImage(final ImageView imageView, final String urlString) {
        loadImage(imageView, urlString, true);
    }

    public void loadImage(final ImageView imageView, final String urlString, boolean useCache) {
        if (useCache && cache.containsKey(urlString)) {
            imageView.setImageDrawable(cache.get(urlString));
        }

        //You may want to show a "Loading" image here
        imageView.setImageResource(R.drawable.ic_launcher);

        Log.d(this.getClass().getSimpleName(), "Image url:" + urlString);

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message message) {
                imageView.setImageDrawable((Drawable) message.obj);
            }
        };

        Runnable runnable = new Runnable() {
            public void run() {
                Drawable drawable = null;
                try {
                    InputStream is = download(urlString);
                    drawable = Drawable.createFromStream(is, "src");

                    if (drawable != null) {
                        cache.put(urlString, drawable);
                    }
                } catch (Exception e) {
                    Log.e(this.getClass().getSimpleName(), "Image download failed", e);
                    //Show "download fail" image 
                    drawable = imageView.getResources().getDrawable(R.drawable.ic_launcher);
                }
                
                //Notify UI thread to show this image using Handler
                Message msg = handler.obtainMessage(1, drawable);
                handler.sendMessage(msg);
            }
        };
        new Thread(runnable).start();

    }

    /**
     * Download image from given url.
     * Make sure you have "android.permission.INTERNET" permission set in AndroidManifest.xml.
     * 
     * @param urlString
     * @return
     * @throws MalformedURLException
     * @throws IOException
     */
    private InputStream download(String urlString) throws MalformedURLException, IOException {
        InputStream inputStream = (InputStream) new URL(urlString).getContent();
        return inputStream;
    }
}

 

posted @ 2013-10-11 13:10  BetterMan-  阅读(271)  评论(0编辑  收藏  举报