Listview加載網絡數據、圖片並跳轉傳值

1、自定義Adapter,裏面有一個Imageview跟三個Textview,其中只有兩個Textview是顯示出來的,另一個是不顯示,用來存值,將這個值傳遞到跳轉的界面的:

public class LvImageAdapter extends BaseAdapter {

private ArrayList<String> mArrayList,mArrayList1,mArrayList2,mArrayList3;
private Context mContext;
private static Handler mHandler;
private static LruCache<String, Bitmap> mCache;
private ListView mListView;

public LvImageAdapter(ArrayList<String> arrayList , ArrayList<String> arrayList1,
         ArrayList<String> arrayList2,ArrayList<String> arrayList3,Context context, ListView listView) {
this.mArrayList = arrayList;
this.mArrayList1 = arrayList1;
this.mArrayList2 = arrayList2;
this.mArrayList3 = arrayList3;
mContext = context;
mHandler = new Handler();
int maxSize = (int) (Runtime.getRuntime().maxMemory() / 1024);
mCache = new LruCache<String, Bitmap>(maxSize / 2);
mListView = listView;
   }

@Override
public int getCount() {
return mArrayList.size();
   }

@Override
public String getItem(int arg0) {
return mArrayList.get(arg0);
   }

@Override
public long getItemId(int arg0) {
return arg0;
   }

public int getCount1() {
return mArrayList1.size();
   }

public String getItem1(int arg1) {
return mArrayList1.get(arg1);
   }

public long getItemId1(int arg1) {
return arg1;
   }
public int getCount2() {
return mArrayList2.size();
   }

public String getItem2(int arg2) {
return mArrayList2.get(arg2);
   }

public long getItemId2(int arg2) {
return arg2;
   }

public int getCount3() {
return mArrayList3.size();
   }

public String getItem3(int arg1) {
return mArrayList3.get(arg1);
   }

@Override
public View getView(int position, View convertView, ViewGroup arg2) {
      ViewHolder holder;

      convertView = View.inflate(mContext, R.layout.image_item, null);
      holder = new ViewHolder();
      holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
      holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
      holder.textView2 = (TextView) convertView.findViewById(R.id.textView2);
      holder.textview00 = (TextView) convertView.findViewById(R.id.textview00);
      convertView.setTag(holder);

if (convertView == null) {
         convertView = View.inflate(mContext, R.layout.image_item, null);
         holder = new ViewHolder();
         holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
         holder.textView1 = (TextView) convertView.findViewById(R.id.textView1);
         holder.textView2 = (TextView) convertView.findViewById(R.id.textView2);
         holder.textview00 = (TextView) convertView.findViewById(R.id.textview00);
         convertView.setTag(holder);
      }else{
         holder = (ViewHolder) convertView.getTag();
      }

//download image
holder.imageView.setImageResource(R.mipmap.download);
      holder.imageView.setScaleType(ScaleType.FIT_XY);
      holder.textView1.setText(mArrayList1.get(position));
      holder.textView2.setText(mArrayList2.get(position));
      holder.textview00.setText(mArrayList3.get(position));
      holder.textview00.setVisibility(View.GONE);
      Utils.loadImageFromUrl(mArrayList.get(position),
mHandler, holder.imageView, mCache, mListView, position);
      Log.i("LvImageAdapter", position+"");
return convertView;
   }    
static class ViewHolder{
private ImageView imageView;
private TextView textView1,textView2,textview00;
   }

}

2、下載圖片的類:

public class Utils {

public static void loadImageFromUrl(final String url, final Handler handler, final ImageView imageView, final LruCache<String, Bitmap> lruCache, final ListView listView, final int position){

if (lruCache.get(url) == null) {
new Thread(new Runnable() {

@Override
public void run() {
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);

                 HttpResponse response = null;
try {
                  response = client.execute(getRequest);
               } catch (ClientProtocolException e) {
                  e.printStackTrace();
               } catch (IOException e) {
                  e.printStackTrace();
               }
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)  {
                     Log.e("PicShow", "Request URL failed, error code =" + statusCode);
                 }

                 HttpEntity entity = response.getEntity();
if (entity == null) {
                     Log.e("PicShow", "HttpEntity is null");
                 }
                 InputStream is = null;
                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
                     is = entity.getContent();
byte[] buf = new byte[1024];
int readBytes = -1;
while ((readBytes = is.read(buf)) != -1) {
                         baos.write(buf, 0, readBytes);
                     }
                 } catch (IllegalStateException e) {
                  e.printStackTrace();
               } catch (IOException e) {
                  e.printStackTrace();
               } finally {
if (baos != null) {
try {
                        baos.close();
                     } catch (IOException e) {
                        e.printStackTrace();
                     }
                     }
if (is != null) {
try {
                        is.close();
                     } catch (IOException e) {
                        e.printStackTrace();
                     }
                     }
                 }
byte[] imageArray = baos.toByteArray();
final Bitmap bitmap = BitmapFactory.decodeByteArray(
                         imageArray, 0, imageArray.length);
handler.post(new Runnable() {

@Override
public void run() {
imageView.setImageBitmap(bitmap);
lruCache.put(url, bitmap);
                  }
               });
            }
         }).start();
      }else{
         handler.post(new Runnable() {

@Override
public void run() {
imageView.setImageBitmap(lruCache.get(url));
//listView.smoothScrollToPosition(position + 1);
}
         }); 
      }


   }


public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
        }
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
         View listItem = listAdapter.getView(i, null, listView);
         listItem.measure(0, 0);
         totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
          + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
   }

}

3、請求服務器,解析Json,得到數組,將數據加載到Listview中,傳入的值包括三個顯示的,還有一個不顯示的:

Handlerhandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
mArrayList = new ArrayList<String>();
mArrayList1 = new ArrayList<String>();
mArrayList2 = new ArrayList<String>();
mArrayList3 = new ArrayList<String>();
try {
final String status = jsonObject.getString("status");
if ("true".equals(status)) {
jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
item1 = jsonArray.getJSONObject(i);
title = item1.getString("title");
info = item1.getString("info");
imageurl = item1.getString("img");
myid = item1.getInt("id");
mArrayList.add(imageurl);
mArrayList1.add(title);
mArrayList2.add(info);
mArrayList3.add(myid+"");
                        }
                        LvImageAdapter lvImageAdapter = new
LvImageAdapter(mArrayList, mArrayList1, mArrayList2,mArrayList3, OperateActivity.this, main_operate_listview);
main_operate_listview.setAdapter(lvImageAdapter);
main_operate_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
        String str = mArrayList3.get(position);
        Intent intent = new Intent();
        intent.putExtra("ArticleNum", str);                                         intent.setClass(OperateActivity.this, Article.class);
         startActivity(intent);
                            }
                        });
                    } else {
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
break;
default:
break;
        }
    }
};

private class OperateThread implements Runnable {
@Override
public void run() {
path = path_url + 1 + "/aa/" + count;
responseMsg = JsonUtil.loginServer(path);
        Message msg = handler.obtainMessage();
try {
jsonObject = new JSONObject(responseMsg);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        msg.what = 0;
handler.sendMessage(msg);
    }
}
發佈了61 篇原創文章 · 獲贊 72 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章