Android開發(fā)之ImageLoader使用詳解
先給大家展示效果圖,看看是大家想要的效果嗎,如果還滿意,請參考以下代碼:

前言
UniversalImageLoader是用于加載圖片的一個開源項目,在其項目介紹中是這么寫的,
•支持多線程圖片加載
•提供豐富的細節(jié)配置,比如線程池大小,HTPP請求項,內存和磁盤緩存,圖片顯示時的參數配置等等;
•提供雙緩存
•支持加載過程的監(jiān)聽;
•提供圖片的個性化顯示配置接口;
•Widget支持(這個,個人覺得沒必要寫進來,不過尊重原文)
其他類似的項目也有很多,但這個作為github上著名的開源項目被廣泛使用。第三方的包雖然好用省力,可以有效避免重復造輪子,但是卻隱藏了一些開發(fā)上的細節(jié),如果不關注其內部實現(xiàn),那么將不利于開發(fā)人員掌握核心技術,當然也談不上更好的使用它,計劃分析項目的集成使用和低層實現(xiàn)。
我從接口拉出來的數據然后將它們展示在界面上
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中展示產品,不過我在展示的時候發(fā)現(xiàn)第一條數據總是在請求數據如下圖,重復網址加載太慢也消耗服務器(也不知道是我哪里寫錯了第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(這里是漸現(xiàn)圖片顯示)
.build();
// 創(chuàng)建默認的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);
// 創(chuàng)建個適配器
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開發(fā)之ImageLoader基本使用,有問題歡迎大家留言,我會及時和大家回復的,謝謝!
- Android ListView實現(xiàn)ImageLoader圖片加載的方法
- Android Universal ImageLoader 緩存圖片
- Android Imageloader的配置的實現(xiàn)代碼
- Android ImageLoader第三方框架解析
- Android開發(fā)之ImageLoader本地緩存
- Android圖片加載的緩存類
- 非常實用的Android圖片工具類
- Android開發(fā)之多媒體文件獲取工具類實例【音頻,視頻,圖片等】
- Android開發(fā)之超強圖片工具類BitmapUtil完整實例
- Android開發(fā)之圖片壓縮工具類完整實例
- Android編程圖片加載類ImageLoader定義與用法實例分析
相關文章
Android自定義View實現(xiàn)QQ運動積分轉盤抽獎功能
這篇文章主要為大家詳細介紹了Android自定義View實現(xiàn)QQ運動積分轉盤抽獎功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10
Android user版通過adb_enable開啟adb 調試 不提示對話框的流程分析
這篇文章主要介紹了Android user版通過adb_enable開啟adb 調試 不提示對話框的流程分析,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05
Android解決viewpager嵌套滑動沖突并保留側滑菜單功能
這篇文章主要介紹了 解決viewpager嵌套滑動沖突,并保留側滑菜單功能,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-06-06
Android使用ContentResolver搜索手機通訊錄的方法
這篇文章主要介紹了Android使用ContentResolver搜索手機通訊錄的方法,結合實例形式分析了Android中ContentResolver操作手機通訊錄的具體步驟與相關實現(xiàn)技巧,需要的朋友可以參考下2016-01-01

