用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"
}; }
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来实现的照片墙,效果挺不错的。
下载地址:
用Volley让GridView加载网络图片的更多相关文章
- Android Volley入门到精通:使用Volley加载网络图片
在上一篇文章中,我们了解了Volley到底是什么,以及它的基本用法.本篇文章中我们即将学习关于Volley更加高级的用法,如何你还没有看过我的上一篇文章的话,建议先去阅读Android Volley完 ...
- android官方开源的高性能异步加载网络图片的Gridview例子
这个是我在安卓安卓巴士上看到的资料,放到这儿共享下.这个例子android官方提供的,其中讲解了如何异步加载网络图片,以及在gridview中高效率的显示图片此代码很好的解决了加载大量图片时,报OOM ...
- Google官方网络框架-Volley的使用解析Json以及加载网络图片方法
Google官方网络框架-Volley的使用解析Json以及加载网络图片方法 Volley是什么? Google I/O 大会上,Google 推出 Volley的一个网络框架 Volley适合什么场 ...
- Android Volley完全解析(二),使用Volley加载网络图片
转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/17482165 在上一篇文章中,我们了解了Volley到底是什么,以及它的基本用法. ...
- Android三种基本的加载网络图片方式(转)
Android三种基本的加载网络图片方式,包括普通加载网络方式.用ImageLoader加载图片.用Volley加载图片. 1. [代码]普通加载网络方式 ? 1 2 3 4 5 6 7 8 9 10 ...
- volley中图片加载
volley图片加载有三种方式: 记得:Volley中已经实现了磁盘缓存了,查看源码得知通过 context.getCacheDir()获取到了 /data/data/<application ...
- Android中用双缓存技术,加载网络图片
最近在学校参加一个比赛,写的一个Android应用,里面要加载大量的网络图片,可是用传统的方法图片一多就会造成程序出现内存溢出而崩溃.因为自己也在学习中,所以看了很多博客和视频,然后参照这些大神的写源 ...
- wemall app商城源码Android之ListView异步加载网络图片(优化缓存机制)
wemall-mobile是基于WeMall的android app商城,只需要在原商城目录下上传接口文件即可完成服务端的配置,客户端可定制修改.本文分享wemall app商城源码Android之L ...
- 【WPF】wpf image控件加载网络图片不显示问题,
1.加载网络图片到内存system.drawing.image对象中2.内存中的image 转Bitmap 再转适合system.windows.controls.image 的BitmapImage ...
随机推荐
- RTC系统
http://blog.csdn.net/fanqipin/article/details/8089995 一. RTC及驱动简介 RTC即real time clock实时时钟,主要用于为操作系统提 ...
- 【转】SVN 查看历史信息
转载地址:http://lee2013.iteye.com/blog/1074457 SVN 查看历史信息 通过svn命令可以根据时间或修订号去除过去的版本,或者某一版本所做的具体的修改.以下四个命令 ...
- Emag eht htiw Em Pleh 分类: POJ 2015-06-29 18:54 10人阅读 评论(0) 收藏
Emag eht htiw Em Pleh Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 2937 Accepted: ...
- Tautology 分类: POJ 2015-06-28 18:40 10人阅读 评论(0) 收藏
Tautology Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 10428 Accepted: 3959 Descri ...
- JAVA基础知识之Set集合
Set集合的基本特征是不记录添加顺序,不允许元素重复(想想是为什么).最常用的实现类是HashSet. 本文将要介绍以下内容 HashSet类 HashSe的特征 HashSet的equals和has ...
- Solr开发文档
转载:http://www.cnblogs.com/hoojo/archive/2011/10/21/2220431.html Solr 是一种可供企业使用的.基于 Lucene 的搜索服务器,它支持 ...
- 2016 ACM/ICPC Asia Regional Qingdao Online HDU5882
链接:http://acm.hdu.edu.cn/showproblem.php?pid=5882 解法:一个点必须出度和入度相同就满足题意,所以加上本身就是判断奇偶性 #include<std ...
- 实现的时钟(time)
<!doctype html><html lang="en"><head> <script type="text/javascr ...
- MySQL的事务
MySQL的事务 1.事务:事务是由一步或者几步数据库操作序列组成的逻辑执行单元,这一系列操作要么全部执行,要么全部放弃执行. 2.事务具备的四个特性(简称为ACID性): (1)原子性(Atomic ...
- Statement和PreparedStatement批量更新
优势:1.节省传递时间. 2.并发处理. PreparedStatement: 1) addBatch()将一组参数添加到PreparedStatement对象内部. 2) executeBatch( ...