Volley加载图片有两种方式:
  1,ImageRequest 来对网络图片进行请求,放入请求队列,获取后现在在控件上面。
  2,NetworkImageView 最为自定义控件来自动加载网络图片。

  3,imageloader,对图片大小,质量格式控制来按需加载图片。
下面分别举例子说明使用:

ImageRequest的使用来加载图片:
首先设计界面,是个Gridview来加载图片:
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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<GridView android:id="@+id/gvImages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp">
</GridView>
</RelativeLayout>

GridView的item布局文件如下,上面是图片,下面是文字说明:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/ivImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:contentDescription="test" />
<TextView
android:id="@+id/tvDesc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ivImage"
android:layout_centerHorizontal="true" />
</RelativeLayout>

下面是主要的图片加载的逻辑代码,流程如下:

  1,创建请求队列mQueue;
  2,创建ImageRequest 请求,并进行配置,并将请求放入请求队列mqueue中去;
  3,ImageRequest只有一个构造方法:对图片大小和图片格式进行设置;

 /**
* Creates a new image request, decoding to a maximum specified width and
* height. If both width and height are zero, the image will be decoded to
* its natural size. If one of the two is nonzero, that dimension will be
* clamped and the other one will be set to preserve the image's aspect
* ratio. If both width and height are nonzero, the image will be decoded to
* be fit in the rectangle of dimensions width x height while keeping its
* aspect ratio.
*
* @param url URL of the image 网络图片Url
* @param listener Listener to receive the decoded bitmap 接收网络图片的bitmap回调参数
* @param maxWidth Maximum width to decode this bitmap to, or zero for none 宽
* @param maxHeight Maximum height to decode this bitmap to, or zero for 高
* none
* @param decodeConfig Format to decode the bitmap to 编码质量的配置
* @param errorListener Error listener, or null to ignore errors 加载图片失败的回调
*/
public ImageRequest(String url, Response.Listener<Bitmap> listener, int maxWidth, int maxHeight,
Config decodeConfig, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
setRetryPolicy(
new DefaultRetryPolicy(IMAGE_TIMEOUT_MS, IMAGE_MAX_RETRIES, IMAGE_BACKOFF_MULT));
mListener = listener;
mDecodeConfig = decodeConfig;
mMaxWidth = maxWidth;
mMaxHeight = maxHeight;
}
package com.soyoungboy.volleydemo;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
/**
* Volley使用demo
*
* @author soyoungboy
*/
public class MainActivity extends Activity {
private static final String[] URLS = {
"http://img.my.csdn.net/uploads/201403/03/1393854094_4652.jpg",
"http://img.my.csdn.net/uploads/201403/03/1393854084_6138.jpg",
"http://img.my.csdn.net/uploads/201403/03/1393854084_1323.jpg",
"http://img.my.csdn.net/uploads/201403/03/1393854084_8439.jpg",
"http://img.my.csdn.net/uploads/201403/03/1393854083_6511.jpg",
"http://img.my.csdn.net/uploads/201403/03/1393854083_2323.jpg" };
private static final String[] DESCS = { "photo1", "photo2", "photo3",
"photo4", "photo5", "photo6" };
private RequestQueue mQueue;
private GridView gvImages;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gvImages = (GridView) findViewById(R.id.gvImages);
GridAdapter adpater = new GridAdapter();
gvImages.setAdapter(adpater);
mQueue = Volley.newRequestQueue(this);
}
class GridAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
public GridAdapter() {
layoutInflater = LayoutInflater.from(MainActivity.this);
}
@Override
public int getCount() {
return URLS.length;
}
@Override
public Object getItem(int position) {
return URLS[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.grid_item, null);
viewHolder.ivImage = (ImageView) convertView
.findViewById(R.id.ivImage);
viewHolder.tvDesc = (TextView) convertView
.findViewById(R.id.tvDesc);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
loadImgByVolley(URLS[position], viewHolder.ivImage);
viewHolder.tvDesc.setText(DESCS[position]);
return convertView;
}
}
static class ViewHolder {
ImageView ivImage;
TextView tvDesc;
}
public void loadImgByVolley(String imgUrl, final ImageView imageView) {
ImageRequest imgRequest = new ImageRequest(imgUrl,
new Response.Listener<Bitmap>() {
/**
* 加载成功
* @param arg0
*/
@Override
public void onResponse(Bitmap arg0) {
imageView.setImageBitmap(arg0);
}
}, 300, 200, Config.ARGB_8888,
new ErrorListener() {
//加载失败
@Override
public void onErrorResponse(VolleyError arg0) {
imageView.setImageResource(R.drawable.ic_launcher);
}
});
//将图片加载放入请求队列中去
mQueue.add(imgRequest);
}
}

效果:

NetworkImageView加载图片:
首先在布局中使用NetWorkImageView:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.android.volley.toolbox.NetworkImageView
android:id="@+id/load_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>

java代码里面实现:

package com.soyoungboy.volleydemo;
import android.app.Activity;
import android.os.Bundle;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import com.android.volley.toolbox.Volley;
public class NetworkImageViewActivity extends Activity {
private NetworkImageView load_img;
private ImageLoader imageLoader;
private RequestQueue requestQueue;
private LruImageCache lruImageCache;
private static final String IMGURL = "http://imgsrc.baidu.com/forum/w%3D580/sign=f96acdfc08f79052ef1f47363cf1d738/cb2fc65c10385343223c39ce9213b07ecb808870.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_networkimageview);
load_img = (NetworkImageView) findViewById(R.id.load_img);
lruImageCache = LruImageCache.getInstance();
requestQueue = Volley.newRequestQueue(this);
imageLoader = new ImageLoader(requestQueue, lruImageCache);
load_img.setImageUrl(IMGURL, imageLoader);
}
}

LruImageCache.java缓存类:

package com.soyoungboy.volleydemo;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache; import com.android.volley.toolbox.ImageLoader.ImageCache; public class LruImageCache implements ImageCache{ private static LruCache<String, Bitmap> mMemoryCache; private static LruImageCache lruImageCache; private LruImageCache(){
// Get the Max available memory
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize){
@Override
protected int sizeOf(String key, Bitmap bitmap){
return bitmap.getRowBytes() * bitmap.getHeight();
}
};
} public static LruImageCache getInstance(){
if(lruImageCache == null){
lruImageCache = new LruImageCache();
}
return lruImageCache;
} @Override
public Bitmap getBitmap(String arg0) {
return mMemoryCache.get(arg0);
} @Override
public void putBitmap(String arg0, Bitmap arg1) {
if(getBitmap(arg0) == null){
mMemoryCache.put(arg0, arg1);
}
} }

其中LruImageCache是个Lru算法类,主要用于处理缓存的大小问题,可以避免加载图片的时候oom的问题,ImaageLoader是volley提供的另外一种加载图片的方式。最后通过setImageUrl(String url, ImageLoader imageLoader)来进行加载。
NetworkImageView的优势在于他能够根据组件的大小自动进行图片的大小缩放处理。后面文章会在源码分析中进行讲解。
效果:

ImageLoader加载图片:
帮我们对图片进行缓存,还可以过滤掉重复的链接,避免重复发送请求。
  1,创建请求队列;
  2,创建imageloader对象,其中imageloader的构造方法第二个参数为imageCache的实现类,实现图片缓存的算法类。
  3,创建imagelistener对象,主要设置图片加载失败和加载过程中的图片设置。
界面如上面第一个的界面activity_main.xml;
这里主要看下逻辑:

package com.soyoungboy.volleydemo.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;
import com.soyoungboy.volleydemo.LruImageCache;
import com.soyoungboy.volleydemo.R;
public class ImageLoaderActivity extends Activity {
private GridView gvImages;
private static final String[] URLS = {
"http://img.my.csdn.net/uploads/201403/03/1393854094_4652.jpg",
"http://img.my.csdn.net/uploads/201403/03/1393854084_6138.jpg",
"http://img.my.csdn.net/uploads/201403/03/1393854084_1323.jpg",
"http://img.my.csdn.net/uploads/201403/03/1393854084_8439.jpg",
"http://img.my.csdn.net/uploads/201403/03/1393854083_6511.jpg",
"http://img.my.csdn.net/uploads/201403/03/1393854083_2323.jpg" };
private static final String[] DESCS = { "photo1", "photo2", "photo3",
"photo4", "photo5", "photo6" };
private RequestQueue mQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gvImages = (GridView) findViewById(R.id.gvImages);
mQueue = Volley.newRequestQueue(this);
GridAdapter adpater = new GridAdapter();
gvImages.setAdapter(adpater);
}
class GridAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private ImageLoader imageLoader;
public GridAdapter() {
layoutInflater = LayoutInflater.from(ImageLoaderActivity.this);
imageLoader = new ImageLoader(mQueue, LruImageCache.getInstance());
}
@Override
public int getCount() {
return URLS.length;
}
@Override
public Object getItem(int position) {
return URLS[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.grid_item, null);
viewHolder.ivImage = (ImageView) convertView
.findViewById(R.id.ivImage);
viewHolder.tvDesc = (TextView) convertView
.findViewById(R.id.tvDesc);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
loadImgByVolley(URLS[position], viewHolder.ivImage);
viewHolder.tvDesc.setText(DESCS[position]);
return convertView;
}
private void loadImgByVolley(String string, ImageView ivImage) {
ImageListener listener = ImageLoader.getImageListener(ivImage,
R.drawable.ic_launcher, R.drawable.ic_launcher);
imageLoader.get(string, listener);
}
}
static class ViewHolder {
ImageView ivImage;
TextView tvDesc;
}
}

界面效果:

【第二篇】Volley的使用之加载图片的更多相关文章

  1. 【第二篇】xLua中lua加载方式

     xLua中lua文件加载方式 1. 直接执行字符串方式 LuaEnv luaenv = new LuaEnv(); luaenv.DoString("CS.UnityEngine.Debu ...

  2. Android之使用Android-AQuery异步加载图片(一)

    第一节:转载地址(http://www.cnblogs.com/lee0oo0/archive/2012/10/25/2738299.html) // 必须实现AQuery这个类 AQuery aq ...

  3. Android UI开发第三十六篇——使用Volley加载图片列表

    Android开发者可能会使用Universal Image Loader或者Square`s newer Picasso这些第三方的库去处理图片的加载,那么Volley是怎么加载图片列表的呢,这一篇 ...

  4. 利用Volley封装好的图片缓存处理加载图片

    Volley 工具箱中提供了一种通过 DiskBasedCache 类实现的标准缓存.这个类能够缓存文件到磁盘的指定目录.但是为了使用 ImageLoader,我们应该提供一个自定义的内存 LRC b ...

  5. 使用Volley框架中的ImageLoader来异步的加载图片

    Volley框架在请求网络图片方面也做了很多工作,提供了好几种方法.本文介绍使用ImageLoader来进行网络图片的加载.ImageLoader的内部使用ImageRequest来实现,它的构造器可 ...

  6. 安卓新的联网方式 Volley的使用(一)加载图片与 json

    最近刚接触安卓, 以前搞wp ,一对比起来 ,安卓怎么这么麻烦.联网必须要重新开一个线程才可以.而且加载网络图片也很麻烦...花了很久一直卡在快速滑动加载网络图片的listview上面 ,一直很纠结痛 ...

  7. Android框架Volley之:利用Imageloader和NetWorkImageView加载图片

    首先我们在项目中导入这个框架: implementation 'com.mcxiaoke.volley:library:1.0.19' 在AndroidManifest文件当中添加网络权限: < ...

  8. 鸿蒙内核源码分析(进程镜像篇)|ELF是如何被加载运行的? | 百篇博客分析OpenHarmony源码 | v56.01

    百篇博客系列篇.本篇为: v56.xx 鸿蒙内核源码分析(进程映像篇) | ELF是如何被加载运行的? | 51.c.h.o 加载运行相关篇为: v51.xx 鸿蒙内核源码分析(ELF格式篇) | 应 ...

  9. Listview 异步加载图片之优化篇(有图有码有解释)

    在APP应用中,listview的异步加载图片方式能够带来很好的用户体验,同时也是考量程序性能的一个重要指标.关于listview的异步加载,网上其实很多示例了,中心思想都差不多,不过很多版本或是有b ...

随机推荐

  1. Nodejs --我自己的学习笔记

    对于Nodejs,相信客官并不陌生,网上却已众说纷纭,有人说是一个平台,有人说是服务器JavaScript,有人说一个框架… 之前亦有过研究,多怀可远观而不可亵玩也.高效率,I/O操作,异步编程,以及 ...

  2. Python第一天——入门Python(2)字符串的简单操作

    数据的操作 字符串的一些常用操作: 1 1 #!/usr/bin/env python 2 # #coding=utf-8 3 # 4 # test='hello world' 5 # print(t ...

  3. 2015 ACM / ICPC 亚洲区域赛总结(长春站&北京站)

    队名:Unlimited Code Works(无尽编码)  队员:Wu.Wang.Zhou 先说一下队伍:Wu是大三学长:Wang高中noip省一:我最渣,去年来大学开始学的a+b,参加今年区域赛之 ...

  4. 删除style的样式JQuery

      有些页面样式不规范,没有写在一个class里,例如:<div id="show" style="width:100px; padding-top:10px; f ...

  5. session fixation

    转自:session fixation攻击 什么是session fixation攻击 Session fixation有人翻译成"Session完成攻击",实际上fixation ...

  6. CentOS7安装和配置Nginx(https)

    安装Nginx下载安装包# wget http://nginx.org/download/nginx-1.11.7.tar.gz# tar -zxvf nginx-1.11.7.tar.gz# cd ...

  7. leetcode 024

    Given a linked list, swap every two adjacent nodes and return its head. For example,Given 1->2-&g ...

  8. Ansible安装配置

    Ansible工具的安装与配置 Ansible基于SSH,不需要在远程端安装任何软件,只需要在管理端安装ansible及其组件即可. Ansible使用前提是已配置ssh密钥免登陆. 一.安装组件: ...

  9. Qt 打开指定的文件

    最近项目用到使用本地的office打开指定的文件,记录一下代码: QString fileName = QFileDialog::getOpenFileName(this, tr("Open ...

  10. ios UIImageView异步加载网络图片

    方法1:在UI线程中同步加载网络图片 UIImageView *headview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 40, 4 ...