这是我的代码:
int[] image = {R.drawable.image1, R.drawable.image2, R.drawable.image1, R.drawable.image2,
R.drawable.image1, R.drawable.image2, R.drawable.image1, R.drawable.image2,
R.drawable.image1, R.drawable.image2, R.drawable.image1, R.drawable.image2,
R.drawable.image1, R.drawable.image2, R.drawable.image1, R.drawable.image2,
R.drawable.image1, R.drawable.image2, R.drawable.image1, R.drawable.image2,
R.drawable.image1, R.drawable.image2, R.drawable.image1, R.drawable.image2};
和getView:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView=LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, null);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
imageView.setBackgroundResource(image[position]);
return convertView;
}
一切都很好。没有OOM。
然后,我想先对可绘制对象进行采样:
public static Bitmap sampleImage(Context context, int resourceId, int sampleSize) {
Bitmap resizeBmp = null;
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = sampleSize;
resizeBmp = BitmapFactory.decodeResource(context.getResources(), resourceId, opts);
return resizeBmp;
}
和新的getView:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView=LayoutInflater.from(getApplicationContext()).inflate(R.layout.item, null);
ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
Bitmap item = BitmapUtil.sampleMaskInShelf(getApplicationContext(), image[position], 4);
imageView.setImageBitmap(item);
// imageView.setBackgroundResource(image[position]);
return convertView;
}
事情发生了。起初,应用程序不会崩溃。但是使用的内存超过50MB,上下滚动后,导致OOM。
问题是:1)为什么对图像进行采样会增加使用的内存。2)如何减少使用的内存,还有其他方法吗?