服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android开发之ImageLoader使用详解

Android开发之ImageLoader使用详解

2021-05-09 20:32王丰蛋哥 Android

这篇文章主要介绍了Android开发之ImageLoader使用详解的相关资料,需要的朋友可以参考下

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

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[]有数据的时候就不许再请求了

Android开发之ImageLoader使用详解

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

主要的代码如下

布局代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
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基本使用,有问题欢迎大家留言,我会及时和大家回复的,谢谢!

延伸 · 阅读

精彩推荐