转载 GridView异步加载内存卡和网络图片

一、主界面代码:

  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3.   
  4. import android.app.Activity;  
  5. import android.os.Bundle;  
  6. import android.widget.GridView;  
  7.   
  8. public class MainActivity extends Activity {  
  9.     /** Called when the activity is first created. */  
  10.     @Override  
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.main);  
  14.         GridView gridView=(GridView)findViewById(R.id.gridview);  
  15.         List<ImageAndText> list = new ArrayList<ImageAndText>();  
  16.         String[] paths=new String[15];  
  17.         for(int i=0;i<15;i++){  
  18.             int index=i;  
  19.             paths[i]="/sdcard/"+String.valueOf(index+1)+".jpg";//自己动手向SD卡添加15张图片,如:1.jpg  
  20.         }  
  21.         for(int i=0;i<15;i++){  
  22.             list.add(new ImageAndText(paths[i], String.valueOf(i)));  
  23.         }  
  24.         gridView.setAdapter(new ImageAndTextListAdapter(this, list, gridView));  
  25.     }  
  26. }  


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

  1. import java.io.IOException;  
  2. import java.io.InputStream;  
  3. import java.lang.ref.SoftReference;  
  4. import java.net.MalformedURLException;  
  5. import java.net.URL;  
  6. import java.util.HashMap;  
  7.   
  8. import android.R.drawable;  
  9. import android.graphics.Bitmap;  
  10. import android.graphics.BitmapFactory;  
  11. import android.graphics.BitmapFactory.Options;  
  12. import android.graphics.drawable.BitmapDrawable;  
  13. import android.graphics.drawable.Drawable;  
  14. import android.os.Handler;  
  15. import android.os.Message;  
  16. import android.util.Log;  
  17. import android.widget.ImageView;  
  18.   
  19. public class AsyncImageLoader {  
  20.   
  21.      private HashMap<String, SoftReference<Drawable>> imageCache;  
  22.      public AsyncImageLoader() {  
  23.              imageCache = new HashMap<String, SoftReference<Drawable>>();  
  24.          }  
  25.         
  26.      public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {  
  27.              if (imageCache.containsKey(imageUrl)) {  
  28.                  SoftReference<Drawable> softReference = imageCache.get(imageUrl);  
  29.                  Drawable drawable = softReference.get();  
  30.                  if (drawable != null) {  
  31.                      return drawable;  
  32.                  }  
  33.              }  
  34.              final Handler handler = new Handler() {  
  35.                  public void handleMessage(Message message) {  
  36.                      imageCallback.imageLoaded((Drawable) message.obj, imageUrl);  
  37.                  }  
  38.              };  
  39.              new Thread() {  
  40.                  @Override  
  41.                  public void run() {  
  42.                      Drawable drawable = loadImageFromUrl(imageUrl);  
  43.                      imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));  
  44.                      Message message = handler.obtainMessage(0, drawable);  
  45.                      handler.sendMessage(message);  
  46.                  }  
  47.              }.start();  
  48.              return null;  
  49.          }  
  50.          
  51.     public static Drawable loadImageFromUrl(String url) {  
  52. //      /**  
  53. //       * 加载网络图片  
  54. //       */  
  55. //            URL m;  
  56. //            InputStream i = null;  
  57. //            try {  
  58. //                m = new URL(url);  
  59. //                i = (InputStream) m.getContent();  
  60. //            } catch (MalformedURLException e1) {  
  61. //                e1.printStackTrace();  
  62. //            } catch (IOException e) {  
  63. //                e.printStackTrace();  
  64. //            }  
  65. //            Drawable d = Drawable.createFromStream(i, "src");  
  66.           
  67.         /** 
  68.          * 加载内存卡图片 
  69.          */  
  70.             Options options=new Options();  
  71.             options.inSampleSize=2;  
  72.             Bitmap bitmap=BitmapFactory.decodeFile(url, options);  
  73.             Drawable drawable=new BitmapDrawable(bitmap);  
  74.             return drawable;  
  75.         }  
  76.         
  77.     public interface ImageCallback {  
  78.              public void imageLoaded(Drawable imageDrawable, String imageUrl);  
  79.                
  80.          }  
  81. }  

三、ImageAndTextListAdapter是实现ListView的Adapter,里面有个技巧就是 imageView.setTag(imageUrl),setTag是存储数据的,这样是为了保证在回调函数时,listview去更新自己对应 item。

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


四、2个辅助类:

  1. public class ImageAndText {  
  2.         private String imageUrl;  
  3.         private String text;  
  4.   
  5.         public ImageAndText(String imageUrl, String text) {  
  6.             this.imageUrl = imageUrl;  
  7.             this.text = text;  
  8.         }  
  9.         public String getImageUrl() {  
  10.             return imageUrl;  
  11.         }  
  12.         public String getText() {  
  13.             return text;  
  14.         }  
  15. }  

  1. public class ViewCache {  
  2.   
  3.         private View baseView;  
  4.         private TextView textView;  
  5.         private ImageView imageView;  
  6.   
  7.         public ViewCache(View baseView) {  
  8.             this.baseView = baseView;  
  9.         }  
  10.   
  11.         public TextView getTextView() {  
  12.             if (textView == null) {  
  13.                 textView = (TextView) baseView.findViewById(R.id.text);  
  14.             }  
  15.             return textView;  
  16.         }  
  17.   
  18.         public ImageView getImageView() {  
  19.             if (imageView == null) {  
  20.                 imageView = (ImageView) baseView.findViewById(R.id.image);  
  21.             }  
  22.             return imageView;  
  23.         }  
  24.   
  25. }  

五、Xml配置文件,包括griditem和main:

1griditem:

  1. <?xml version="1.0" encoding="UTF-8"?>      
  2. <RelativeLayout      
  3.          xmlns:android="http://schemas.android.com/apk/res/android"    
  4.          android:layout_height="100dip"      
  5.          android:paddingBottom="4dip" android:layout_width="fill_parent">  
  6.          <ImageView   
  7.                android:id="@+id/image"  
  8.                android:layout_height="80dip"  
  9.                android:layout_width="80dip"  
  10.                android:layout_centerHorizontal="true"  
  11.                android:scaleType="centerCrop">  
  12.          </ImageView>  
  13.          <TextView  
  14.                android:id="@+id/text"     
  15.                android:layout_width="wrap_content"  
  16.                android:layout_height="wrap_content"  
  17.                android:layout_below="@+id/image"  
  18.                android:layout_centerHorizontal="true"  
  19.                >  
  20.          </TextView>  
  21. </RelativeLayout>  
  1. </pre><pre name="code" class="html">2main:  
  1. <pre name="code" class="html"><?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent">  
  5.       
  6.     <GridView xmlns:android="http://schemas.android.com/apk/res/android"      
  7.     android:id="@+id/gridview"     
  8.     android:layout_width="fill_parent"      
  9.     android:layout_height="fill_parent"     
  10.     android:numColumns="4"     
  11.     android:verticalSpacing="10dp"     
  12.     android:horizontalSpacing="10dp"     
  13.     android:columnWidth="80dp"  
  14.     android:stretchMode="columnWidth"     
  15.     android:gravity="center"   
  16.     android:background="#ffffff"   
  17. />   
  18. </LinearLayout>  


  1. 六、大功告成,总结方法。 
原文地址:https://www.cnblogs.com/xiao0/p/2172366.html