You need to move the block where you generate the Bitmap outside of the if/then
. Right now, you only generate the new Bitmap when convertView == null
.
I believe your code would be correct as:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private List<String> mList;
private int mheight;
private int mwidth;
public ImageAdapter(Context context, List<String> list, int height, int width) {
mContext = context;
mList = list;
mheight = height;
mwidth = width;
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int position) {
return mList.get(position).toString();
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
} else {
imageView = (ImageView) convertView;
}
InputStream is;
try {
is = mContext.getAssets().open(mList.get(position));
Bitmap bm = BitmapFactory.decodeStream(is);
Bitmap bitmap = Bitmap.createScaledBitmap(bm, mwidth / 3, mwidth / 3, false);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
return imageView;
}
}
Your scrolling will not be very fluid and you'll get lots of dropped frames because your Bitmap decoding code is inefficient (no caching), and it all happens on the UI thread, which is bad for responsiveness. The bottleneck in your current code is not the allocation and garbage-collection of the ImageView
s.
The bottleneck is (probably by far) your handling and creation of Bitmap
s.
You can take a look at the following links for advice:
Displaying Bitmaps Efficiently
And specifically this one: