zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    TDSCDMA手机(WM系统)信号的采集?
    vc2008 + libpq + postgresql 8.4 配置
    code complete 2阅读笔记(第二章)
    Python 学习笔记(一)语句,变量,函数
    CS通用模型设计,socket,tcp实现()
    VS2005,VS2008编辑器设置
    设计模式之个人理解单例模式
    请教:C#网络编程相关的知识,建立socket服务器时向客户端连接,就建立不了了?
    服务器开发
    年终总结
  • 原文地址:https://www.cnblogs.com/yangcong/p/3363164.html
Copyright © 2011-2022 走看看