一、布局文件
总共两个布局文件,一个是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
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(); } } }