我的一个GridView布局,用的是继承的BaseAdapter,现在的问题是每次我下拉GridView里面的每一行的图片都会变化,下面是我的basedapter主要代码,请高手帮忙看看。
- Java code
@Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if (convertView == null) { convertView = layoutInflater.inflate(R.layout.xin_fjshname, null); } TextView tv_name = (TextView) convertView.findViewById(R.id.tv_xin_fjshname); LinearLayout ll_image = (LinearLayout) convertView.findViewById(R.id.ll_xin_fjshtp); RatingBar rb_stars = (RatingBar) ll_image.findViewById(R.id.rb_xin_stars); String name = list.get(position).get("name"); tv_name.setText(name); float grade = Float.parseFloat(list.get(position).get("grade")); Log.i(TAG, "grade:" + grade); rb_stars.setRating(grade); String imagePath = list.get(position).get("imgPath"); Log.i(TAG, "imagePath:" + imagePath); if (!islocal) { imagePath = context.getString(R.string.imageIp) + imagePath; try { Bitmap bitmap = BitmapFactory.decodeStream(new URL(imagePath).openConnection().getInputStream()); if (bitmap != null) { if (bitmap.getWidth() > 150 && bitmap.getHeight() > 150) { bitmap = tpcq(bitmap); BitmapDrawable drawable = new BitmapDrawable(bitmap); if (drawable != null) { ll_image.setBackgroundDrawable(drawable); } } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } else { Bitmap bitmap = BitmapFactory.decodeFile(imagePath); if (bitmap != null) { if (bitmap.getWidth() > 150 && bitmap.getHeight() > 150) { bitmap = tpcq(bitmap); ll_image.setBackgroundDrawable(new BitmapDrawable(bitmap)); } } } return convertView; }
下面是裁图片的代码
- Java code
/** * 如果图片宽高大于150,则转化为150 * * @param bitmap * @return */ public Bitmap tpcq(Bitmap bitmap) { int width = bitmap.getWidth(); int height = bitmap.getHeight(); int newWidht = 150; int newHeight = 150; float scaleWidth = ((float) newWidht) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); return newBitmap; }
------解决方案--------------------
没有仔细看,不妨试一下ViewHolder类
- Java code
static class ViewHolder { TextView tv; LinearLayout ll; RatingBar rb; }
------解决方案--------------------
我以前也遇到这个问题,后来弄个全局变量,把图片缓存进去,然后adapter每次都去缓存里拿图片
------解决方案--------------------
用到Memory缓存,磁盘缓存,SoftReference等
用下面这开源的项目吧
http://code.google.com/p/android-query/#Image_Loading