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基本使用,有问题欢迎大家留言,我会及时和大家回复的,谢谢!
上一篇: Javacsv实现Java读写csv文件
下一篇: java实现简单扫雷小游戏