网上的资源普遍上是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:
- <pre 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>
六、大功告成,总结方法。
转载自:http://blog.csdn.net/lanpy88/article/details/6671915