• 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;
        }
    }
  • 相关阅读:
    JAVA 设计模式 组合模式
    JAVA 设计模式 模板方法模式
    SpringBoot 数据篇之使用JDBC
    [Spring]01_环境配置
    [spring]03_装配Bean
    [Spring]04_最小化Spring XML配置
    [Quartz笔记]玩转定时调度
    [Spring]支持注解的Spring调度器
    asp.net core 系列 13 日志
    asp.net core 系列 12 选项 TOptions
  • 原文地址:https://www.cnblogs.com/yangcong/p/3363164.html
Copyright © 2020-2023  润新知