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;
        }
    }
  • 相关阅读:
    jquery练习(赋予属性值)
    jquery练习
    jquery表单对象属性选择器
    jquery表单选择器
    jquery子元素选择器
    jquery属性选择器(同时匹配多个条件)
    jquery属性选择器
    jquery属性选择器(匹配具有指定属性的元素)
    jquery可见性选择器(综合)
    方法的递归
  • 原文地址:https://www.cnblogs.com/yangcong/p/3363164.html
Copyright © 2011-2022 走看看