用Volley让GridView加载网络图片

一、布局文件

总共两个布局文件,一个是GridView,还有一个是GridView的item,是NetworkImageView和TextView

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <GridView
        android:id="@+id/photo_wall"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="@dimen/image_thumbnail_size"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:horizontalSpacing="@dimen/image_thumbnail_spacing"
        android:verticalSpacing="@dimen/image_thumbnail_spacing" >
    </GridView>

</RelativeLayout>

 

photo_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/netork_imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentTop="true"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:textSize="18sp"
        android:textColor="#ffffff"
        android:text="TextView" />

</RelativeLayout>

 

二、MainActivity & Application

1.1 MainActivity

MainActivity主要作用是加载GridView,这里做了一个小小的处理(参考自:bitmapfun),通过计算GridView的宽,然后根据GridView的列数和边距,最终计算出GridView中item的宽度。

package com.example.kalephotoswall;


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

import com.kale.photoswall.adapter.PhotoWallAdapter;

public class MainActivity extends Activity {

    /**
     * 用于展示照片墙的GridView
     */
    private GridView mPhotoWall;
    private PhotoWallAdapter mAdapter;
    // 小图片的大小
    int mImageThumbSize;
    // 图片间距
    int mImageThumbSpacing;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
        mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size); // 读取资源文件中的宽度,即:100
        mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing); // 读取资源文件中的itmap边距,即:1
        
        mAdapter = new PhotoWallAdapter(this);

        mPhotoWall = (GridView) findViewById(R.id.photo_wall);
        mPhotoWall.post(new Runnable() {
            
            @Override
            public void run() {
                final int numColumns = (int) Math.floor(mPhotoWall.getWidth() / (mImageThumbSize + mImageThumbSpacing));
                if (numColumns > 0) {
                    int columnWidth = (mPhotoWall.getWidth() / numColumns) - mImageThumbSpacing; // 计算出item的列宽
                    mAdapter.setItemHeight(columnWidth); // 调用适配器中我们自定义的方法,来在getView()中设置好item宽度
                }
                
            }
        });
        
        mPhotoWall.setAdapter(mAdapter); // 设置适配器
    }
}

 

1.2 Application

在应用程序的代码中初始化volley用到的对象,方便以后调用。

package com.kale.photoswall.application;

import android.app.Application;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class KaleApplication extends Application {

    public static RequestQueue requestQueue;
    public static int memoryCacheSize;
    //public static ImageLoader imageLoader;

    @Override
    public void onCreate() {
        super.onCreate();
        // 不必为每一次HTTP请求都创建一个RequestQueue对象,推荐在application中初始化
        requestQueue = Volley.newRequestQueue(this);
        // 计算内存缓存
        memoryCacheSize = getMemoryCacheSize();
    }

    /**
     * @description
     *
     * @param context
     * @return 得到需要分配的缓存大小,这里用八分之一的大小来做
     */
    public int getMemoryCacheSize() {
        // Get memory class of this device, exceeding this amount will throw an
        // OutOfMemory exception.
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        // Use 1/8th of the available memory for this memory cache.
        return maxMemory / 8;
    }

}

 

三、准备图片数据源 & ViewHolder & Cache

3.1 数据源

建立一个用url的string数组—— Images.java

/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.kale.photoswall.provider;


/**
 * Some simple test data to use for this sample app.
 */
public class Images {

    public final static String[] imageThumbUrls = new String[] {
        "http://static4.photo.sina.com.cn/middle/69670edbx9475f3f01283&690",
        "http://s8.sinaimg.cn/middle/6f78405exa6e437719ea7&690",
        "http://s3.sinaimg.cn/middle/6f78405ex9f4d66911f22&690",
        "http://s8.sinaimg.cn/middle/6f78405exa6e436d8f357&690",
        "http://s4.sinaimg.cn/middle/6f78405exa6e43621ecb3&690",
        "http://s10.sinaimg.cn/middle/6f78405exa0f4f335c589&690",
        "http://s16.sinaimg.cn/middle/6f78405ex9f4d7b2eff0f&690",
        "http://s7.sinaimg.cn/middle/6f78405exa6e2fa1d4ab6&690",
        "http://s8.sinaimg.cn/middle/6f78405exa6e2fa4b19c7&690",
        "http://s6.sinaimg.cn/middle/69670edbx94da12276525&690",
        "http://s2.sinaimg.cn/middle/69670edbx94da117f7c41&690",
        "http://s3.sinaimg.cn/bmiddle/6f78405exa503c5d0a462&690",
        "http://s6.sinaimg.cn/middle/6f78405exa72b24119765&690",
        "http://s11.sinaimg.cn/middle/6f78405ex9f4d5245988a&690",
        "http://s10.sinaimg.cn/middle/6f78405ex9f4d7b107f29&690",
        "http://img0.tech2ipo.com/upload/img/article/2013/03/1364556945327.png",
        "http://s7.sinaimg.cn/middle/6f78405eta77a260b8d96&690",
        "http://s3.sinaimg.cn/middle/6f78405eta77a29344d92&690",
        "http://s10.sinaimg.cn/middle/6f78405exa0f4f250e469&690",
        "http://s3.sinaimg.cn/middle/6f78405eta77a21932632&690",
        "http://s13.sinaimg.cn/middle/6f78405eta77a2c9a0d2c&690",
        "http://s9.sinaimg.cn/middle/6f78405eta77a47b89188&690",
        "http://s16.sinaimg.cn/middle/6f78405exa0f4f11fb58f&690",
        "http://img2.imgtn.bdimg.com/it/u=2449553173,1966285445&fm=23&gp=0.jpg",
        "http://h.hiphotos.baidu.com/baike/w%3D150/sign=406f3d00251f95caa6f596b3f9167fc5/d50735fae6cd7b89493402fd0f2442a7d9330e77.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383299_1976.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383291_6518.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383291_8239.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383290_9329.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383290_1042.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383275_3977.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383265_8550.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383264_3954.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383264_4787.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383264_8243.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383248_3693.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383243_5120.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383242_3127.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383242_9576.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383242_1721.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383219_5806.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383214_7794.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383213_4418.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383213_3557.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383210_8779.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383172_4577.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383166_3407.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383166_2224.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383166_7301.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383165_7197.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383150_8410.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383131_3736.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383130_5094.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383130_7393.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383129_8813.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383100_3554.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383093_7894.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383092_2432.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383092_3071.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383091_3119.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383059_6589.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383059_8814.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383059_2237.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383058_4330.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406383038_3602.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382942_3079.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382942_8125.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382942_4881.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382941_4559.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382941_3845.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382924_8955.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382923_2141.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382923_8437.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382922_6166.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382922_4843.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382905_5804.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382904_3362.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382904_2312.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382904_4960.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382900_2418.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382881_4490.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382881_5935.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382880_3865.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382880_4662.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382879_2553.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382862_5375.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382862_1748.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382861_7618.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382861_8606.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382861_8949.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382841_9821.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382840_6603.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382840_2405.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382840_6354.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382839_5779.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382810_7578.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382810_2436.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382809_3883.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382809_6269.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382808_4179.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382790_8326.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382789_7174.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382789_5170.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382789_4118.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382788_9532.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382767_3184.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382767_4772.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382766_4924.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382766_5762.jpg",
        "//img-my.csdn.net/uploads/201407/26/1406382765_7341.jpg",
        "http://kale/error/201407/26/1406382765_7341.jpg"
    };


}
View Code

 

3.2 ViewHolder

package com.kale.photoswall.util;

import android.util.SparseArray;
import android.view.View;

public class ViewHolder {
    // I added a generic return type to reduce the casting noise in client code
    @SuppressWarnings("unchecked")
    public static <T extends View> T get(View view, int id) {
        SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
        if (viewHolder == null) {
            viewHolder = new SparseArray<View>();
            view.setTag(viewHolder);
        }
        View childView = viewHolder.get(id);
        if (childView == null) {
            childView = view.findViewById(id);
            viewHolder.put(id, childView);
        }
        return (T) childView;
    }
}

 

3.3 设置内存缓存对象

既然用到了volley,那么就需要自定义一个内存缓存对象,用它来缓存图片。

LruBitmapCache.java

package com.kale.photoswall.util;

import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.toolbox.ImageLoader.ImageCache;
import com.kale.photoswall.application.KaleApplication;

public class LruBitmapCache implements ImageCache {

    private LruCache<String, Bitmap> mMemoryCache;
    
    public static Bitmap cacheBitmap;

    public LruBitmapCache() {
        mMemoryCache = new LruCache<String, Bitmap>(KaleApplication.memoryCacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                return bitmap.getRowBytes() * bitmap.getHeight();
            }
        };
    }

    @Override
    public Bitmap getBitmap(String url) {
        return mMemoryCache.get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        mMemoryCache.put(url, bitmap);
    }

}

 

四、设置Adapter

准备工作做好了,现在就来自定义一个adapter。

package com.kale.photoswall.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.example.kalephotoswall.R;
import com.kale.photoswall.application.KaleApplication;
import com.kale.photoswall.provider.Images;
import com.kale.photoswall.util.LruBitmapCache;
import com.kale.photoswall.util.ViewHolder;

public class PhotoWallAdapter extends BaseAdapter implements OnScrollListener{

    private Context mContext;
    private static ImageLoader mImageLoader; // imageLoader对象,用来初始化NetworkImageView
    /**
     * 记录每个子项的高度。
     */
    private int mItemHeight = 0;
    

    public PhotoWallAdapter(Context context) {
        mContext = context;
        // 初始化mImageLoader,并且传入了自定义的内存缓存
        mImageLoader = new ImageLoader(KaleApplication.requestQueue, new LruBitmapCache()); // 初始化一个loader对象,可以进行自定义配置
        // 配置是否进行磁盘缓存
        mImageLoader.setShouldCache(true); // 设置允许磁盘缓存,默认是true
    }

    @Override
    public int getCount() {
        return Images.imageThumbUrls.length; // 返回item的个数
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    /* 
     * 重要的方法。通过viewHolder复用view,并且设置好item的宽度
     * 
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            // init convertView by layout
            LayoutInflater inflater = LayoutInflater.from(mContext);
            convertView = inflater.inflate(R.layout.photo_layout, null);
        }
        // 得到item中显示图片的view
        NetworkImageView networkImageView = ViewHolder.get(convertView, R.id.netork_imageView); 
        // 得到item中的textview
        TextView textView = ViewHolder.get(convertView, R.id.textView); 
        // 设置默认的图片
        networkImageView.setDefaultImageResId(R.drawable.default_photo); 
        // 设置图片加载失败后显示的图片
        networkImageView.setErrorImageResId(R.drawable.error_photo); 
        
        if (networkImageView.getLayoutParams().height != mItemHeight) {
            // 通过activity中计算出的结果,在这里设置networkImageview的高度(得到的是正方形)
            networkImageView.getLayoutParams().height = mItemHeight; 
        }

        // 开始加载网络图片
        networkImageView.setImageUrl(Images.imageThumbUrls[position], mImageLoader);
        textView.setText("" + position); // 简单的设置textview上的文字
        return convertView;
    }
    
    /**
     * 设置item子项的高度。
     */
    public void setItemHeight(int height) {
        if (height == mItemHeight) {
            return;
        }
        mItemHeight = height;
        notifyDataSetChanged();
    }
    


    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount , int totalItemCount ) {
        
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // 仅当GridView静止时才去下载图片,GridView滑动时取消所有正在下载的任务  
        if (scrollState == SCROLL_STATE_IDLE) {  
            // loadBitmaps(mFirstVisibleItem, mVisibleItemCount);  
        } else {  
            // cancelAllTasks();  
        }  
    }
    

}

 

源码下载:http://download.csdn.net/detail/shark0017/8429613

 

其他参考的demo,这个demo是通过LruCache,DiskLruCache来实现的照片墙,效果挺不错的。

下载地址:

posted @ 2015-02-06 19:10  developer_Kale  阅读(3108)  评论(1编辑  收藏  举报
网站流量统计工具