Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> ImageLoader簡單使用,imageloader

ImageLoader簡單使用,imageloader

編輯:關於android開發

ImageLoader簡單使用,imageloader


如圖是效果圖

                   

我從接口拉出來的數據然後將它們展示在界面上

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); } } View Code <?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> View Code
  1 package com.demo.activity;
  2 
  3 import java.util.ArrayList;
  4 import java.util.List;
  5 import org.json.JSONArray;
  6 import org.json.JSONObject;
  7 import com.demo.content.MyGridView;
  8 import com.demo.entity.Product;
  9 import com.demo.pullrefresh.R;
 10 import com.demo.util.GetThread;
 11 import com.nostra13.universalimageloader.core.DisplayImageOptions;
 12 import com.nostra13.universalimageloader.core.ImageLoader;
 13 import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
 14 import com.nostra13.universalimageloader.core.assist.ImageScaleType;
 15 import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
 16 import android.annotation.SuppressLint;
 17 import android.app.Activity;
 18 import android.graphics.Bitmap;
 19 import android.os.Bundle;
 20 import android.os.Handler;
 21 import android.util.Log;
 22 import android.view.View;
 23 import android.view.ViewGroup;
 24 import android.widget.BaseAdapter;
 25 import android.widget.ImageView;
 26 import android.widget.TextView;
 27 
 28 public class MyMainActivity extends Activity {
 29     // 定義的布局
 30     private MyGridView myGridView;
 31     private DisplayImageOptions options;
 32     // 產品
 33     private List<Product> products;
 34     // 地址
 35     private String url = ""
 36             + "Product/GetProductsByProType/12000000/20";
 37 
 38     @Override
 39     protected void onCreate(Bundle arg0) {
 40         // TODO Auto-generated method stub
 41         super.onCreate(arg0);
 42         setContentView(R.layout.mymainactivity);
 43         options = new DisplayImageOptions.Builder()
 44                 .showImageForEmptyUri(R.drawable.ic_empty)
 45                 // image連接地址為空時
 46                 .showImageOnFail(R.drawable.ic_error)
 47                 // image加載失敗
 48                 .resetViewBeforeLoading(true).cacheOnDisc(true)
 49                 .imageScaleType(ImageScaleType.EXACTLY)
 50                 .bitmapConfig(Bitmap.Config.RGB_565)
 51                 .displayer(new FadeInBitmapDisplayer(300))// 設置用戶加載圖片task(這裡是漸現圖片顯示)
 52                 .build();
 53         // 創建默認的ImageLoader的參數 不加回報java.lang.IllegalStateException
 54         // 但不是每次用到ImageLoader都要加
 55         ImageLoader.getInstance().init(
 56                 ImageLoaderConfiguration.createDefault(this));
 57         myGridView = (MyGridView) findViewById(R.id.gg_mygridview);
 58         // 開啟線程
 59         new GetThread(url, handler).start();
 60     }
 61 
 62     @SuppressLint("HandlerLeak")
 63     private Handler handler = new Handler() {
 64         public void handleMessage(android.os.Message msg) {
 65             switch (msg.what) {
 66             case GetThread.SUCCESS:
 67                 String jsonString = (String) msg.obj;
 68                 // 用JSON來解析數據
 69                 products = getJsonProducts(jsonString);
 70                 Log.d("jiejie", "DDDDDDD" + products);
 71                 // 創建個適配器
 72                 Adapter adapter = new Adapter();
 73                 myGridView.setAdapter(adapter);
 74                 break;
 75 
 76             default:
 77                 break;
 78             }
 79         };
 80     };
 81 
 82     protected List<Product> getJsonProducts(String jsonString) {
 83         List<Product> resultTempList = new ArrayList<Product>();
 84         try {
 85             JSONArray array = new JSONArray(jsonString);
 86             for (int i = 0; i < array.length(); i++) {
 87                 Product temProductSimple = new Product();
 88                 JSONObject object = array.getJSONObject(i);
 89                 temProductSimple.setId(object.getInt("id"));
 90                 temProductSimple.setProType(object.getInt("ProType"));
 91                 temProductSimple.setProOrder(object.getInt("ProOrder"));
 92                 temProductSimple.setAddTime(object.getString("AddTime"));
 93                 temProductSimple.setTitle(object.getString("Title"));
 94                 temProductSimple.setSmallPic(object.getString("SmallPic"));
 95                 temProductSimple.setPrice(object.getDouble("Price"));
 96                 temProductSimple.setSalePrice(object.getDouble("SalePrice"));
 97                 temProductSimple.setZhishubi(object.getString("Zhishubi"));
 98                 temProductSimple.setProNo(object.getString("ProNo"));
 99                 temProductSimple.setContens(object.getString("Contens"));
100                 temProductSimple.setBuyCount(object.getInt("BuyCount"));
101                 temProductSimple.setReadCount(object.getInt("ReadCount"));
102                 temProductSimple.setProImg(object.getString("ProImg"));
103                 temProductSimple.setShopFlag(object.getString("ShopFlag"));
104                 temProductSimple.setBrandId(object.getInt("BrandId"));
105                 temProductSimple.setStartTime(object.getString("StartTime"));
106                 if (object.get("Score") == null
107                         || object.get("Score").toString() == "null") {
108                     temProductSimple.setScore(0);
109                 } else {
110 
111                     temProductSimple.setScore(object.getInt("Score"));
112                 }
113 
114                 temProductSimple.setProductOrigin(object
115                         .getString("ProductOrigin"));
116                 if (object.get("kucun").toString() == "null") {
117                     temProductSimple.setKucun(0);
118 
119                 } else {
120                     temProductSimple.setKucun(object.getInt("kucun"));
121                 }
122 
123                 resultTempList.add(temProductSimple);
124             }
125         } catch (Exception e) {
126             // TODO: handle exception
127             e.printStackTrace();
128             System.out.println(e.toString());
129 
130         }
131         return resultTempList;
132     }
133 
134     private View arrView[];
135 
136     private class Adapter extends BaseAdapter {
137 
138         @Override
139         public int getCount() {
140             // TODO Auto-generated method stub
141             // return products.size();
142             if (arrView == null) {
143                 arrView = new View[products.size()];
144             }
145             return products.size();
146         }
147 
148         @Override
149         public Object getItem(int arg0) {
150             // TODO Auto-generated method stub
151             return products.get(arg0);
152         }
153 
154         @Override
155         public long getItemId(int arg0) {
156             // TODO Auto-generated method stub
157             return arg0;
158         }
159 
160         @Override
161         public View getView(int arg0, View arg1, ViewGroup arg2) {
162             if (arrView[arg0] == null) {
163                 Product info = products.get(arg0);
164                 Holder holder = null;
165                 if (null == arg1) {
166                     holder = new Holder();
167 
168                     arg1 = View.inflate(MyMainActivity.this,
169                             R.layout.product_item, null);
170                     holder.product_cost = (TextView) arg1
171                             .findViewById(R.id.product_cost);
172                     holder.product_title = (TextView) arg1
173                             .findViewById(R.id.product_title);
174                     holder.product_img = (ImageView) arg1
175                             .findViewById(R.id.product_img);
176                     holder.buy_count = (TextView) arg1
177                             .findViewById(R.id.buy_count);
178                     arg1.setTag(holder);
179                 } else {
180                     holder = (Holder) arg1.getTag();
181                 }
182                 holder.product_cost.setText(products.get(arg0).getSalePrice()
183                         + "");
184                 holder.product_title.setText(products.get(arg0).getTitle());
185                 holder.buy_count.setText(products.get(arg0).getBuyCount() + "");
186                 String urlString = "http://**/UploadImages/ProductImages/"
187                         + products.get(arg0).getSmallPic();
188 
189                 Log.d("jiejie", "dddddd___   " + arg0);
190                 Log.d("jiejie", "_________" + info.getTitle());
191                 Log.d("jiejie", "ProducteGridAdapter--" + urlString);
192                 ImageLoader.getInstance().displayImage(urlString,
193                         holder.product_img, options);
194 
195                 arrView[arg0] = arg1;
196             }
197             return arrView[arg0];
198             // return arg1;
199 
200         }
201 
202     }
203 
204     static class Holder {
205         ImageView product_img;
206         TextView product_title;
207         TextView product_cost;
208         TextView buy_count;
209     }
210 }
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();
        }

    }
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved