免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3583 | 回复: 1
打印 上一主题 下一主题

[转载]Android实现ListView异步加载图片 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-01-11 16:46 |只看该作者 |倒序浏览
[转载]Android实现ListView异步加载图片







原文分享地址:http://apps.hi.baidu.com/share/detail/34554080

ListView异步加载图片是非常实用的方法,凡是是要通过网络获取图片资源一般使用这种方法比较好,用户体验好,不用让用户等待下去,下面就说实现方法,先贴上主方法的代码:


Java代码
  1. 1.package  cn.wangmeng.test;   
  2. 2.  
  3. 3.import  Java.io.IOException;   
  4. 4.import  java.io.InputStream;   
  5. 5.import  java.lang.ref.SoftReference;   
  6. 6.import  java.NET.MalformedURLException;   
  7. 7.import  java.net.URL;   
  8. 8.import  java.util.HashMap;   
  9. 9.  
  10. 10.import  Android.graphics.drawable.Drawable;   
  11. 11.import  android.os.Handler;   
  12. 12.import  android.os.Message;   
  13. 13.  
  14. 14.public   class  AsyncImageLoader {   
  15. 15.  
  16. 16.      private  HashMap < String, SoftReference < Drawable >>  imageCache;   
  17. 17.         
  18. 18.      public  AsyncImageLoader() {   
  19. 19.             imageCache  =   new  HashMap < String, SoftReference < Drawable >> ();   
  20. 20.         }   
  21. 21.         
  22. 22.      public  Drawable loadDrawable( final  String imageUrl,  final  ImageCallback imageCallback) {   
  23. 23.              if  (imageCache.containsKey(imageUrl)) {   
  24. 24.                 SoftReference < Drawable >  softReference  =  imageCache.get(imageUrl);   
  25. 25.                 Drawable drawable  =  softReference.get();   
  26. 26.                  if  (drawable  !=   null ) {   
  27. 27.                      return  drawable;   
  28. 28.                 }   
  29. 29.             }   
  30. 30.              final  Handler handler  =   new  Handler() {   
  31. 31.                  public   void  handleMessage(Message message) {   
  32. 32.                     imageCallback.imageLoaded((Drawable) message.obj, imageUrl);   
  33. 33.                 }   
  34. 34.             };   
  35. 35.              new  Thread() {   
  36. 36.                 @Override  
  37. 37.                  public   void  run() {   
  38. 38.                     Drawable drawable  =  loadImageFromUrl(imageUrl);   
  39. 39.                     imageCache.put(imageUrl,  new  SoftReference < Drawable > (drawable));   
  40. 40.                     Message message  =  handler.obtainMessage( 0 , drawable);   
  41. 41.                     handler.sendMessage(message);   
  42. 42.                 }   
  43. 43.             }.start();   
  44. 44.              return   null ;   
  45. 45.         }   
  46. 46.         
  47. 47.     public   static  Drawable loadImageFromUrl(String url) {   
  48. 48.            URL m;   
  49. 49.            InputStream i  =   null ;   
  50. 50.             try  {   
  51. 51.                m  =   new  URL(url);   
  52. 52.                i  =  (InputStream) m.getContent();   
  53. 53.            }  catch  (MalformedURLException e1) {   
  54. 54.                e1.printStackTrace();   
  55. 55.            }  catch  (IOException e) {   
  56. 56.                e.printStackTrace();   
  57. 57.            }   
  58. 58.            Drawable d  =  Drawable.createFromStream(i,  " src " );   
  59. 59.             return  d;   
  60. 60.        }   
  61. 61.         
  62. 62.     public   interface  ImageCallback {   
  63. 63.              public   void  imageLoaded(Drawable imageDrawable, String imageUrl);   
  64. 64.         }   
  65. 65.  
  66. 66.}   
  67. package  cn.wangmeng.test;

  68. import  Java.io.IOException;
  69. import  java.io.InputStream;
  70. import  java.lang.ref.SoftReference;
  71. import  java.NET.MalformedURLException;
  72. import  java.net.URL;
  73. import  java.util.HashMap;

  74. import  Android.graphics.drawable.Drawable;
  75. import  android.os.Handler;
  76. import  android.os.Message;

  77. public   class  AsyncImageLoader {

  78.       private  HashMap < String, SoftReference < Drawable >>  imageCache;
  79.       
  80.       public  AsyncImageLoader() {
  81.              imageCache  =   new  HashMap < String, SoftReference < Drawable >> ();
  82.          }
  83.       
  84.       public  Drawable loadDrawable( final  String imageUrl,  final  ImageCallback imageCallback) {
  85.               if  (imageCache.containsKey(imageUrl)) {
  86.                  SoftReference < Drawable >  softReference  =  imageCache.get(imageUrl);
  87.                  Drawable drawable  =  softReference.get();
  88.                   if  (drawable  !=   null ) {
  89.                       return  drawable;
  90.                  }
  91.              }
  92.               final  Handler handler  =   new  Handler() {
  93.                   public   void  handleMessage(Message message) {
  94.                      imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
  95.                  }
  96.              };
  97.               new  Thread() {
  98.                  @Override
  99.                   public   void  run() {
  100.                      Drawable drawable  =  loadImageFromUrl(imageUrl);
  101.                      imageCache.put(imageUrl,  new  SoftReference < Drawable > (drawable));
  102.                      Message message  =  handler.obtainMessage( 0 , drawable);
  103.                      handler.sendMessage(message);
  104.                  }
  105.              }.start();
  106.               return   null ;
  107.          }
  108.       
  109.      public   static  Drawable loadImageFromUrl(String url) {
  110.             URL m;
  111.             InputStream i  =   null ;
  112.              try  {
  113.                 m  =   new  URL(url);
  114.                 i  =  (InputStream) m.getContent();
  115.             }  catch  (MalformedURLException e1) {
  116.                 e1.printStackTrace();
  117.             }  catch  (IOException e) {
  118.                 e.printStackTrace();
  119.             }
  120.             Drawable d  =  Drawable.createFromStream(i,  " src " );
  121.              return  d;
  122.         }
  123.       
  124.      public   interface  ImageCallback {
  125.               public   void  imageLoaded(Drawable imageDrawable, String imageUrl);
  126.          }

  127. }   
复制代码
以上代码是实现异步获取图片的主方法,SoftReference是软引用,是为了更好的为了系统回收变量,重复的URL直接返回已有的资源,实现回调函数,让数据成功后,更新到UI线程。


ViewCache是辅助获取adapter的子元素布局


Java代码
  1. 1.package  cn.wangmeng.test;   
  2. 2.  
  3. 3.import  java.util.List;   
  4. 4.  
  5. 5.import  cn.wangmeng.test.AsyncImageLoader.ImageCallback;   
  6. 6.  
  7. 7.import  android.app.Activity;   
  8. 8.import  android.graphics.drawable.Drawable;   
  9. 9.import  android.view.LayoutInflater;   
  10. 10.import  android.view.View;   
  11. 11.import  android.view.ViewGroup;   
  12. 12.import  android.widget.ArrayAdapter;   
  13. 13.import  android.widget.ImageView;   
  14. 14.import  android.widget.ListView;   
  15. 15.import  android.widget.TextView;   
  16. 16.  
  17. 17.public   class  ImageAndTextListAdapter  extends  ArrayAdapter < ImageAndText >  {   
  18. 18.  
  19. 19.         private  ListView listView;   
  20. 20.         private  AsyncImageLoader asyncImageLoader;   
  21. 21.  
  22. 22.         public  ImageAndTextListAdapter(Activity activity, List < ImageAndText >  imageAndTexts, ListView listView) {   
  23. 23.             super (activity,  0 , imageAndTexts);   
  24. 24.             this .listView  =  listView;   
  25. 25.            asyncImageLoader  =   new  AsyncImageLoader();   
  26. 26.        }   
  27. 27.  
  28. 28.         public  View getView( int  position, View convertView, ViewGroup parent) {   
  29. 29.            Activity activity  =  (Activity) getContext();   
  30. 30.  
  31. 31.             //  Inflate the views from XML   
  32. 32.            View rowView  =  convertView;   
  33. 33.            ViewCache viewCache;   
  34. 34.             if  (rowView  ==   null ) {   
  35. 35.                LayoutInflater inflater  =  activity.getLayoutInflater();   
  36. 36.                rowView  =  inflater.inflate(R.layout.image_and_text_row,  null );   
  37. 37.                viewCache  =   new  ViewCache(rowView);   
  38. 38.                rowView.setTag(viewCache);   
  39. 39.            }  else  {   
  40. 40.                viewCache  =  (ViewCache) rowView.getTag();   
  41. 41.            }   
  42. 42.            ImageAndText imageAndText  =  getItem(position);   
  43. 43.  
  44. 44.             //  Load the image and set it on the ImageView   
  45. 45.            String imageUrl  =  imageAndText.getImageUrl();   
  46. 46.            ImageView imageView  =  viewCache.getImageView();   
  47. 47.            imageView.setTag(imageUrl);   
  48. 48.            Drawable cachedImage  =  asyncImageLoader.loadDrawable(imageUrl,  new  ImageCallback() {   
  49. 49.                 public   void  imageLoaded(Drawable imageDrawable, String imageUrl) {   
  50. 50.                    ImageView imageViewByTag  =  (ImageView) listView.findViewWithTag(imageUrl);   
  51. 51.                     if  (imageViewByTag  !=   null ) {   
  52. 52.                        imageViewByTag.setImageDrawable(imageDrawable);   
  53. 53.                    }   
  54. 54.                }   
  55. 55.            });   
  56. 56.             if  (cachedImage  ==   null ) {   
  57. 57.                imageView.setImageResource(R.drawable.default_image);   
  58. 58.            } else {   
  59. 59.                imageView.setImageDrawable(cachedImage);   
  60. 60.            }   
  61. 61.             //  Set the text on the TextView   
  62. 62.            TextView textView  =  viewCache.getTextView();   
  63. 63.            textView.setText(imageAndText.getText());   
  64. 64.  
  65. 65.             return  rowView;   
  66. 66.        }   
  67. 67.  
  68. 68.}  
复制代码
package  cn.wangmeng.test;

import  java.util.List;

import  cn.wangmeng.test.AsyncImageLoader.ImageCallback;
  1. import  android.app.Activity;
  2. import  android.graphics.drawable.Drawable;
  3. import  android.view.LayoutInflater;
  4. import  android.view.View;
  5. import  android.view.ViewGroup;
  6. import  android.widget.ArrayAdapter;
  7. import  android.widget.ImageView;
  8. import  android.widget.ListView;
  9. import  android.widget.TextView;

  10. public   class  ImageAndTextListAdapter  extends  ArrayAdapter < ImageAndText >  {

  11.          private  ListView listView;
  12.          private  AsyncImageLoader asyncImageLoader;

  13.          public  ImageAndTextListAdapter(Activity activity, List < ImageAndText >  imageAndTexts, ListView listView) {
  14.              super (activity,  0 , imageAndTexts);
  15.              this .listView  =  listView;
  16.             asyncImageLoader  =   new  AsyncImageLoader();
  17.         }

  18.          public  View getView( int  position, View convertView, ViewGroup parent) {
  19.             Activity activity  =  (Activity) getContext();

  20.              //  Inflate the views from XML
  21.             View rowView  =  convertView;
  22.             ViewCache viewCache;
  23.              if  (rowView  ==   null ) {
  24.                 LayoutInflater inflater  =  activity.getLayoutInflater();
  25.                 rowView  =  inflater.inflate(R.layout.image_and_text_row,  null );
  26.                 viewCache  =   new  ViewCache(rowView);
  27.                 rowView.setTag(viewCache);
  28.             }  else  {
  29.                 viewCache  =  (ViewCache) rowView.getTag();
  30.             }
  31.             ImageAndText imageAndText  =  getItem(position);

  32.              //  Load the image and set it on the ImageView
  33.             String imageUrl  =  imageAndText.getImageUrl();
  34.             ImageView imageView  =  viewCache.getImageView();
  35.             imageView.setTag(imageUrl);
  36.             Drawable cachedImage  =  asyncImageLoader.loadDrawable(imageUrl,  new  ImageCallback() {
  37.                  public   void  imageLoaded(Drawable imageDrawable, String imageUrl) {
  38.                     ImageView imageViewByTag  =  (ImageView) listView.findViewWithTag(imageUrl);
  39.                      if  (imageViewByTag  !=   null ) {
  40.                         imageViewByTag.setImageDrawable(imageDrawable);
  41.                     }
  42.                 }
  43.             });
  44.              if  (cachedImage  ==   null ) {
  45.                 imageView.setImageResource(R.drawable.default_image);
  46.             } else {
  47.                 imageView.setImageDrawable(cachedImage);
  48.             }
  49.              //  Set the text on the TextView
  50.             TextView textView  =  viewCache.getTextView();
  51.             textView.setText(imageAndText.getText());

  52.              return  rowView;
  53.         }

  54. }  
复制代码
ImageAndTextListAdapter是实现ListView的Adapter,里面有个技巧就是imageView.setTag(imageUrl),setTag是存储数据的,这样是为了保证在回调函数时,listview去更新自己对应item,大家仔细阅读就知道了。

论坛徽章:
0
2 [报告]
发表于 2012-01-12 10:22 |只看该作者
谢谢分享
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP