Android GridView 异步加载图片

网上的资源普遍上是ListView异步加载图片,比较少有GirdView异步加载图片,参考了ListView异步加载图片的做法把GridView的异步加载图片功能做出来,方法和思想大同小异,本文章把GridView异步加载内存卡和网络图片希望对大家有用。效果图如下:


一、主界面代码:

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.GridView;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        GridView gridView=(GridView)findViewById(R.id.gridview);
        List<ImageAndText> list = new ArrayList<ImageAndText>();
        String[] paths=new String[15];
        for(int i=0;i<15;i++){
        	int index=i;
        	paths[i]="/sdcard/"+String.valueOf(index+1)+".jpg";//自己动手向SD卡添加15张图片,如:1.jpg
        }
        for(int i=0;i<15;i++){
        	list.add(new ImageAndText(paths[i], String.valueOf(i)));
        }
        gridView.setAdapter(new ImageAndTextListAdapter(this, list, gridView));
    }
}

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

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import android.R.drawable;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ImageView;

public class AsyncImageLoader {

     private HashMap<String, SoftReference<Drawable>> imageCache;
     public AsyncImageLoader() {
             imageCache = new HashMap<String, SoftReference<Drawable>>();
         }
      
     public Drawable loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
             if (imageCache.containsKey(imageUrl)) {
                 SoftReference<Drawable> softReference = imageCache.get(imageUrl);
                 Drawable drawable = softReference.get();
                 if (drawable != null) {
                     return drawable;
                 }
             }
             final Handler handler = new Handler() {
                 public void handleMessage(Message message) {
                     imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
                 }
             };
             new Thread() {
                 @Override
                 public void run() {
                     Drawable drawable = loadImageFromUrl(imageUrl);
                     imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
                     Message message = handler.obtainMessage(0, drawable);
                     handler.sendMessage(message);
                 }
             }.start();
             return null;
         }
       
    public static Drawable loadImageFromUrl(String url) {
//    	/**
//    	 * 加载网络图片
//    	 */
//            URL m;
//            InputStream i = null;
//            try {
//                m = new URL(url);
//                i = (InputStream) m.getContent();
//            } catch (MalformedURLException e1) {
//                e1.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            Drawable d = Drawable.createFromStream(i, "src");
    	
    	/**
    	 * 加载内存卡图片
    	 */
    	    Options options=new Options();
    	    options.inSampleSize=2;
    	    Bitmap bitmap=BitmapFactory.decodeFile(url, options);
    	    Drawable drawable=new BitmapDrawable(bitmap);
            return drawable;
        }
      
    public interface ImageCallback {
             public void imageLoaded(Drawable imageDrawable, String imageUrl);
             
         }
}

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

import java.util.List;

import cn.wangmeng.test.AsyncImageLoader.ImageCallback;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class ImageAndTextListAdapter extends ArrayAdapter<ImageAndText> {

        private GridView gridView;
        private AsyncImageLoader asyncImageLoader;
        public ImageAndTextListAdapter(Activity activity, List<ImageAndText> imageAndTexts, GridView gridView1) {
            super(activity, 0, imageAndTexts);
            this.gridView = gridView1;
            asyncImageLoader = new AsyncImageLoader();
        }

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

            // Inflate the views from XML
            View rowView = convertView;
            ViewCache viewCache;
            if (rowView == null) {
                LayoutInflater inflater = activity.getLayoutInflater();
                rowView = inflater.inflate(R.layout.griditem, null);
                viewCache = new ViewCache(rowView);
                rowView.setTag(viewCache);
            } else {
                viewCache = (ViewCache) rowView.getTag();
            }
            ImageAndText imageAndText = getItem(position);

            // Load the image and set it on the ImageView
            String imageUrl = imageAndText.getImageUrl();
            ImageView imageView = viewCache.getImageView();
            imageView.setTag(imageUrl);
            Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback() {
                public void imageLoaded(Drawable imageDrawable, String imageUrl) {
                    ImageView imageViewByTag = (ImageView) gridView.findViewWithTag(imageUrl);
                    if (imageViewByTag != null) {
                        imageViewByTag.setImageDrawable(imageDrawable);
                    }
                }
            });
            if (cachedImage == null) {
                imageView.setImageResource(R.drawable.icon);
            }else{
                imageView.setImageDrawable(cachedImage);
            }
            // Set the text on the TextView
            TextView textView = viewCache.getTextView();
            textView.setText(imageAndText.getText());
            return rowView;
        }

}

四、2个辅助类:

public class ImageAndText {
	    private String imageUrl;
	    private String text;

	    public ImageAndText(String imageUrl, String text) {
	        this.imageUrl = imageUrl;
	        this.text = text;
	    }
	    public String getImageUrl() {
	        return imageUrl;
	    }
	    public String getText() {
	        return text;
	    }
}

public class ViewCache {

	    private View baseView;
	    private TextView textView;
	    private ImageView imageView;

	    public ViewCache(View baseView) {
	        this.baseView = baseView;
	    }

	    public TextView getTextView() {
	        if (textView == null) {
	            textView = (TextView) baseView.findViewById(R.id.text);
	        }
	        return textView;
	    }

	    public ImageView getImageView() {
	        if (imageView == null) {
	            imageView = (ImageView) baseView.findViewById(R.id.image);
	        }
	        return imageView;
	    }

}

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

1griditem:

<?xml version="1.0" encoding="UTF-8"?>    
<RelativeLayout    
         xmlns:android="http://schemas.android.com/apk/res/android"  
         android:layout_height="100dip"    
         android:paddingBottom="4dip" android:layout_width="fill_parent">
         <ImageView 
               android:id="@+id/image"
               android:layout_height="80dip"
               android:layout_width="80dip"
               android:layout_centerHorizontal="true"
               android:scaleType="centerCrop">
         </ImageView>
         <TextView
               android:id="@+id/text"   
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_below="@+id/image"
               android:layout_centerHorizontal="true"
               >
         </TextView>
</RelativeLayout>
2main: 
<div class="dp-highlighter bg_html"><div class="bar"><div class="tools"><b>[html]</b> <a href="#" class="ViewSource" title="view plain" οnclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">view plain</a><a href="#" class="CopyToClipboard" title="copy" οnclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">copy</a><a href="#" class="PrintSource" title="print" οnclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a><a href="#" class="About" title="?" οnclick="dp.sh.Toolbar.Command('About',this);return false;">?</a><div style="position: absolute; left: 0px; top: 0px; width: 0px; height: 0px; z-index: 99;"><embed id="ZeroClipboardMovie_10" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" name="ZeroClipboardMovie_10" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=10&width=0&height=0" wmode="transparent" align="middle" height="0" width="0"></div></div></div><ol class="dp-xml" start="1"><li class="alt"><span><span class="tag"><?</span><span class="tag-name">xml</span><span> </span><span class="attribute">version</span><span>=</span><span class="attribute-value">"1.0"</span><span> </span><span class="attribute">encoding</span><span>=</span><span class="attribute-value">"utf-8"</span><span class="tag">?></span><span>  </span></span></li><li class=""><span><span class="tag"><</span><span class="tag-name">LinearLayout</span><span> </span><span class="attribute">xmlns:android</span><span>=</span><span class="attribute-value">"http://schemas.android.com/apk/res/android"</span><span>  </span></span></li><li class="alt"><span>    <span class="attribute">android:orientation</span><span>=</span><span class="attribute-value">"vertical"</span><span> </span><span class="attribute">android:layout_width</span><span>=</span><span class="attribute-value">"fill_parent"</span><span>  </span></span></li><li class=""><span>    <span class="attribute">android:layout_height</span><span>=</span><span class="attribute-value">"fill_parent"</span><span class="tag">></span><span>  </span></span></li><li class="alt"><span>      </span></li><li class=""><span>    <span class="tag"><</span><span class="tag-name">GridView</span><span> </span><span class="attribute">xmlns:android</span><span>=</span><span class="attribute-value">"http://schemas.android.com/apk/res/android"</span><span>      </span></span></li><li class="alt"><span>    <span class="attribute">android:id</span><span>=</span><span class="attribute-value">"@+id/gridview"</span><span>     </span></span></li><li class=""><span>    <span class="attribute">android:layout_width</span><span>=</span><span class="attribute-value">"fill_parent"</span><span>      </span></span></li><li class="alt"><span>    <span class="attribute">android:layout_height</span><span>=</span><span class="attribute-value">"fill_parent"</span><span>     </span></span></li><li class=""><span>    <span class="attribute">android:numColumns</span><span>=</span><span class="attribute-value">"4"</span><span>     </span></span></li><li class="alt"><span>    <span class="attribute">android:verticalSpacing</span><span>=</span><span class="attribute-value">"10dp"</span><span>     </span></span></li><li class=""><span>    <span class="attribute">android:horizontalSpacing</span><span>=</span><span class="attribute-value">"10dp"</span><span>     </span></span></li><li class="alt"><span>    <span class="attribute">android:columnWidth</span><span>=</span><span class="attribute-value">"80dp"</span><span>  </span></span></li><li class=""><span>    <span class="attribute">android:stretchMode</span><span>=</span><span class="attribute-value">"columnWidth"</span><span>     </span></span></li><li class="alt"><span>    <span class="attribute">android:gravity</span><span>=</span><span class="attribute-value">"center"</span><span>   </span></span></li><li class=""><span>    <span class="attribute">android:background</span><span>=</span><span class="attribute-value">"#ffffff"</span><span>   </span></span></li><li class="alt"><span><span class="tag">/></span><span>   </span></span></li><li class=""><span><span class="tag"></</span><span class="tag-name">LinearLayout</span><span class="tag">></span><span>  </span></span></li></ol></div><pre style="display: none;" name="code" class="html"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	
	<GridView xmlns:android="http://schemas.android.com/apk/res/android"    
    android:id="@+id/gridview"   
    android:layout_width="fill_parent"    
    android:layout_height="fill_parent"   
    android:numColumns="4"   
    android:verticalSpacing="10dp"   
    android:horizontalSpacing="10dp"   
    android:columnWidth="80dp"
    android:stretchMode="columnWidth"   
    android:gravity="center" 
    android:background="#ffffff" 
/> 
</LinearLayout></pre><br>
<br>
<pre></pre>
<p></p>
<pre></pre>
<div class="dp-highlighter bg_html"><div class="bar"><div class="tools"><b>[html]</b> <a href="#" class="ViewSource" title="view plain" οnclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">view plain</a><a href="#" class="CopyToClipboard" title="copy" οnclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">copy</a><a href="#" class="PrintSource" title="print" οnclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a><a href="#" class="About" title="?" οnclick="dp.sh.Toolbar.Command('About',this);return false;">?</a><div style="position: absolute; left: 0px; top: 0px; width: 0px; height: 0px; z-index: 99;"><embed id="ZeroClipboardMovie_11" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" name="ZeroClipboardMovie_11" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=11&width=0&height=0" wmode="transparent" align="middle" height="0" width="0"></div></div></div><ol class="dp-xml" start="1"><li class="alt"><span><span>六、大功告成,总结方法。  </span></span></li></ol></div><pre style="display: none;" name="code" class="html">六、大功告成,总结方法。</pre><br>
<br>
<p></p>
<p style="text-align:left"><br>
</p>
<p><br>
</p>







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值