一、通过url地址获取Bitmap
public Bitmap loadImage(String url) {
final HttpClient client = new DefaultHttpClient(); final HttpGet getRequest = new HttpGet(url); try { HttpResponse response = client.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w("TAG", "从" + url + "下载图片出处!,错误码:" + statusCode); return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { inputStream = entity.getContent(); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int read = -1; while ((read = inputStream.read(b)) != -1) { baos.write(b, 0, read); }final byte[] data = baos.toByteArray();
baos.close();// 保持到sdcard
// File imgFile = new File(Common.recommend_icon + "/" +// url.hashCode() + ".png");// if(!imgFile.exists()){imgFile.createNewFile();}// FileOutputStream fOut = new FileOutputStream(imgFile);// fOut.write(data);// fOut.close();final Bitmap bitmap = BitmapFactory.decodeByteArray(data,
0, data.length); return bitmap; } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } catch (IOException e) { getRequest.abort(); Log.w("TAG", "I/O errorwhile retrieving bitmap from " + url, e); } catch (IllegalStateException e) { getRequest.abort(); Log.w("TAG", "Incorrect URL:" + url); } catch (Exception e) { getRequest.abort(); Log.w("TAG", "Error whileretrieving bitmap from " + url, e); } return null; }二、将bitmap转为BitmapDrawable
Resources resources=getResources();
Bitmap bm=loadImage(imagePath); BitmapDrawable bd= new BitmapDrawable(resources, bm);三、将BitmapDrawable对象放到simpleAdapter
map = new HashMap<String, Object>();
map.put("dd_refvalue", dd_refvalue); map.put("no_title", no_title); map.put("no_content", no_content); map.put("image", bd); map.put("more", ""); list.add(map);adapter = new SimpleAdapter(NoticeActivity.this, list,
R.layout.notice_item, new String[] { "dd_refvalue", "no_title", "no_content", "image","more" }, new int[] { R.id.tvId, R.id.tvNoticeTitle, R.id.tvContent, R.id.image,R.id.tvMore});四、为适配器setViewBinder
adapter.setViewBinder(new ViewBinder(){
public boolean setViewValue(View view,Object data,String textRepresentation){ if(view instanceof ImageView && data instanceof Drawable){ ImageView iv=(ImageView)view; iv.setImageDrawable((Drawable)data); return true; } else return false; } });
遇到问题:遇到地址为null的情况,需要令url=“”;