先給大家展示效果圖,看看是大家想要的效果嗎,如果還滿意,請參考以下代碼:

前言
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);}@Overridepublic 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" ><ScrollViewandroid:layout_width="match_parent"android:layout_height="match_parent" ><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:background="#eee"android:orientation="vertical" ><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="@string/app_name"android:textColor="#000" /><Viewandroid:layout_width="match_parent"android:layout_height="5dp"android:background="@drawable/btn_normal" /><com.demo.content.MyGridViewandroid: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//";@Overrideprotected void onCreate(Bundle arg) {// TODO Auto-generated method stubsuper.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 exceptione.printStackTrace();System.out.println(e.toString());}return resultTempList;}private View arrView[];private class Adapter extends BaseAdapter {@Overridepublic int getCount() {// TODO Auto-generated method stub// return products.size();if (arrView == null) {arrView = new View[products.size()];}return products.size();}@Overridepublic Object getItem(int arg) {// TODO Auto-generated method stubreturn products.get(arg);}@Overridepublic long getItemId(int arg) {// TODO Auto-generated method stubreturn arg;}@Overridepublic 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;}@Overridepublic void run() {// TODO Auto-generated method stubsuper.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基本使用,有問題歡迎大家留言,我會及時和大家回復的,謝謝!
新聞熱點
疑難解答
圖片精選