Android开发之ImageLoader使用详解

 更新时间:2016年01月13日 09:53:14   作者:王丰蛋哥  
这篇文章主要介绍了Android开发之ImageLoader使用详解的相关资料,需要的朋友可以参考下

先给大家展示效果图,看看是大家想要的效果吗,如果还满意,请参考以下代码:

前言

UniversalImageLoader是用于加载图片的一个开源项目,在其项目介绍中是这么写的,

•支持多线程图片加载
•提供丰富的细节配置,比如线程池大小,HTPP请求项,内存和磁盘缓存,图片显示时的参数配置等等;
•提供双缓存
•支持加载过程的监听;
•提供图片的个性化显示配置接口;
•Widget支持(这个,个人觉得没必要写进来,不过尊重原文)

其他类似的项目也有很多,但这个作为github上著名的开源项目被广泛使用。第三方的包虽然好用省力,可以有效避免重复造轮子,但是却隐藏了一些开发上的细节,如果不关注其内部实现,那么将不利于开发人员掌握核心技术,当然也谈不上更好的使用它,计划分析项目的集成使用和低层实现。

我从接口拉出来的数据然后将它们展示在界面上

1 先定义布局 我定义了MyGridView来展示商品

2 导入jar包universal-image-loader-1.8.6-with-sources 用来展示商品使用 在使用 ImageLoader应加入

ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(this));不然会报
java.lang.IllegalStateException: ImageLoader must be init with configuration before using字面意思是在使用前要初始化

3 定义适配器在getView中展示产品,不过我在展示的时候发现第一条数据总是在请求数据如下图,重复网址加载太慢也消耗服务器(也不知道是我哪里写错了第0条在重复请求 在网上我也没找到方法)

所以我定义了一个 View arrView[]有数据的时候就不许再请求了

4 开启子线程 在子线程中加载数据,在handler中解析数据并将其展示在界面上

主要的代码如下

布局代码

package com.demo.content;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridView;
public class MyGridView extends GridView {
public MyGridView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyGridView(Context context) {
super(context);
}
public MyGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
} 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eee"
android:orientation="vertical" >
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textColor="#000" />
<View
android:layout_width="match_parent"
android:layout_height="5dp"
android:background="@drawable/btn_normal" />
<com.demo.content.MyGridView
android:id="@+id/gg_mygridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="7dp"
android:numColumns="2"
android:verticalSpacing="7dp" />
</LinearLayout>
</ScrollView>
</LinearLayout> 
package com.demo.activity;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import com.demo.content.MyGridView;
import com.demo.entity.Product;
import com.demo.pullrefresh.R;
import com.demo.util.GetThread;
import com.nostra.universalimageloader.core.DisplayImageOptions;
import com.nostra.universalimageloader.core.ImageLoader;
import com.nostra.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra.universalimageloader.core.assist.ImageScaleType;
import com.nostra.universalimageloader.core.display.FadeInBitmapDisplayer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyMainActivity extends Activity {
// 定义的布局
private MyGridView myGridView;
private DisplayImageOptions options;
// 产品
private List<Product> products;
// 地址
private String url = ""
+ "Product/GetProductsByProType//";
@Override
protected void onCreate(Bundle arg) {
// TODO Auto-generated method stub
super.onCreate(arg);
setContentView(R.layout.mymainactivity);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_empty)
// image连接地址为空时
.showImageOnFail(R.drawable.ic_error)
// image加载失败
.resetViewBeforeLoading(true).cacheOnDisc(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_)
.displayer(new FadeInBitmapDisplayer())// 设置用户加载图片task(这里是渐现图片显示)
.build();
// 创建默认的ImageLoader的参数 不加回报java.lang.IllegalStateException
// 但不是每次用到ImageLoader都要加
ImageLoader.getInstance().init(
ImageLoaderConfiguration.createDefault(this));
myGridView = (MyGridView) findViewById(R.id.gg_mygridview);
// 开启线程
new GetThread(url, handler).start();
}
@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case GetThread.SUCCESS:
String jsonString = (String) msg.obj;
// 用JSON来解析数据
products = getJsonProducts(jsonString);
Log.d("jiejie", "DDDDDDD" + products);
// 创建个适配器
Adapter adapter = new Adapter();
myGridView.setAdapter(adapter);
break;
default:
break;
}
};
};
protected List<Product> getJsonProducts(String jsonString) {
List<Product> resultTempList = new ArrayList<Product>();
try {
JSONArray array = new JSONArray(jsonString);
for (int i = ; i < array.length(); i++) {
Product temProductSimple = new Product();
JSONObject object = array.getJSONObject(i);
temProductSimple.setId(object.getInt("id"));
temProductSimple.setProType(object.getInt("ProType"));
temProductSimple.setProOrder(object.getInt("ProOrder"));
temProductSimple.setAddTime(object.getString("AddTime"));
temProductSimple.setTitle(object.getString("Title"));
temProductSimple.setSmallPic(object.getString("SmallPic"));
temProductSimple.setPrice(object.getDouble("Price"));
temProductSimple.setSalePrice(object.getDouble("SalePrice"));
temProductSimple.setZhishubi(object.getString("Zhishubi"));
temProductSimple.setProNo(object.getString("ProNo"));
temProductSimple.setContens(object.getString("Contens"));
temProductSimple.setBuyCount(object.getInt("BuyCount"));
temProductSimple.setReadCount(object.getInt("ReadCount"));
temProductSimple.setProImg(object.getString("ProImg"));
temProductSimple.setShopFlag(object.getString("ShopFlag"));
temProductSimple.setBrandId(object.getInt("BrandId"));
temProductSimple.setStartTime(object.getString("StartTime"));
if (object.get("Score") == null
|| object.get("Score").toString() == "null") {
temProductSimple.setScore();
} else {
temProductSimple.setScore(object.getInt("Score"));
}
temProductSimple.setProductOrigin(object
.getString("ProductOrigin"));
if (object.get("kucun").toString() == "null") {
temProductSimple.setKucun();
} else {
temProductSimple.setKucun(object.getInt("kucun"));
}
resultTempList.add(temProductSimple);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
System.out.println(e.toString());
}
return resultTempList;
}
private View arrView[];
private class Adapter extends BaseAdapter {
@Override
public int getCount() {
// TODO Auto-generated method stub
// return products.size();
if (arrView == null) {
arrView = new View[products.size()];
}
return products.size();
}
@Override
public Object getItem(int arg) {
// TODO Auto-generated method stub
return products.get(arg);
}
@Override
public long getItemId(int arg) {
// TODO Auto-generated method stub
return arg;
}
@Override
public View getView(int arg, View arg, ViewGroup arg) {
if (arrView[arg] == null) {
Product info = products.get(arg);
Holder holder = null;
if (null == arg) {
holder = new Holder();
arg = View.inflate(MyMainActivity.this,
R.layout.product_item, null);
holder.product_cost = (TextView) arg
.findViewById(R.id.product_cost);
holder.product_title = (TextView) arg
.findViewById(R.id.product_title);
holder.product_img = (ImageView) arg
.findViewById(R.id.product_img);
holder.buy_count = (TextView) arg
.findViewById(R.id.buy_count);
arg.setTag(holder);
} else {
holder = (Holder) arg.getTag();
}
holder.product_cost.setText(products.get(arg).getSalePrice()
+ "");
holder.product_title.setText(products.get(arg).getTitle());
holder.buy_count.setText(products.get(arg).getBuyCount() + "");
String urlString = "http://**/UploadImages/ProductImages/"
+ products.get(arg).getSmallPic();
Log.d("jiejie", "dddddd___ " + arg);
Log.d("jiejie", "_________" + info.getTitle());
Log.d("jiejie", "ProducteGridAdapter--" + urlString);
ImageLoader.getInstance().displayImage(urlString,
holder.product_img, options);
arrView[arg] = arg;
}
return arrView[arg];
// return arg;
}
}
static class Holder {
ImageView product_img;
TextView product_title;
TextView product_cost;
TextView buy_count;
}
}
package com.demo.util;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class GetThread extends Thread {
public static final int SUCCESS = 10, FAIL = -11;
private String url;
private Handler handler;
public GetThread(String url, Handler handler) {
this.url = url;
this.handler = handler;
}
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
Message msg = Message.obtain();
Log.v("asdf", httpResponse.getStatusLine().getStatusCode()
+ "返回码 " + url);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String jsonString = EntityUtils.toString(httpResponse
.getEntity());
msg.what = SUCCESS;
msg.obj = jsonString;
handler.sendMessage(msg);
} else {
msg.what = FAIL;
handler.sendMessage(msg);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

以上代码是脚本之家小编给大家介绍的Android开发之ImageLoader基本使用,有问题欢迎大家留言,我会及时和大家回复的,谢谢!

相关文章

最新评论