用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",
        "http://img.my.csdn.net/uploads/201407/26/1406383299_1976.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383291_6518.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383291_8239.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383290_1042.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383275_3977.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383265_8550.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383264_3954.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383264_4787.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383264_8243.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383248_3693.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383243_5120.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383242_3127.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383242_9576.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383242_1721.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383219_5806.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383214_7794.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383213_4418.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383213_3557.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383210_8779.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383172_4577.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383166_3407.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383166_2224.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383166_7301.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383165_7197.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383150_8410.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383131_3736.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383130_5094.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383130_7393.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383129_8813.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383100_3554.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383093_7894.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383092_2432.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383092_3071.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383091_3119.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383059_6589.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383059_8814.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383059_2237.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383058_4330.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406383038_3602.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382942_3079.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382942_8125.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382942_4881.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382941_4559.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382941_3845.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382924_8955.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382923_2141.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382923_8437.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382922_6166.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382922_4843.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382905_5804.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382904_3362.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382904_2312.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382904_4960.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382900_2418.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382881_4490.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382881_5935.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382880_3865.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382880_4662.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382879_2553.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382862_5375.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382862_1748.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382861_7618.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382861_8606.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382861_8949.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382841_9821.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382840_6603.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382840_2405.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382840_6354.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382839_5779.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382810_7578.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382810_2436.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382809_3883.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382809_6269.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382808_4179.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382790_8326.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382789_7174.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382789_5170.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382789_4118.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382788_9532.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382767_3184.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382767_4772.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382766_4924.jpg",
        "http://img.my.csdn.net/uploads/201407/26/1406382766_5762.jpg",
        "http://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來實現的照片牆,效果挺不錯的。

下載地址:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM