我有 2 个不同的列表视图,仅包含图像
列表视图中静态图像内存优化的最佳解决方案
我每次都遇到内存问题 内存不足问题
每个解决方案都与动态图像或从 Web 服务加载图像有关
静态图像呢?
我在列表视图中有大约 70-80 张图片(总共)
不需要代码,因为我只是用图像填充列表视图,没有使用网络服务。
代码 :
private ListView lv;
private ArrayList<Integer> cd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select);
lv = (ListView) findViewById(R.id.lv);
cd = new ArrayList<Integer>();
cd1.add(R.drawable.fuld1);
cd1.add(R.drawable.ful2);
cd1.add(R.drawable.fu4);
lv.setAdapter(new Select(this, cd1));
lv.setOnItemClickListener(this);
}
适配器类:
公共类 SelectAdapter 扩展 BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private ViewHolder holder;
private ArrayList<Integer> list;
public SelectAdapter(Activity activity, ArrayList<Integer> list) {
this.activity = activity;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.list = list;
}
@Override
public int getCount() {
return 43;
}
@Override
public Object getItem(int arg0) {
return arg0;
}
@Override
public long getItemId(int arg0) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.select_item, parent,
false);
holder = new ViewHolder();
holder.iv = (ImageView) convertView
.findViewById(R.id.ivSelect;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.iv.setBackgroundResource(list.get(position));
return convertView;
}
private class ViewHolder {
ImageView ivCard;
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
}
日志 :
java.lang.OutOfMemoryError: Failed to allocate a 34560012 byte allocation with 4194304 free bytes and 14MB until OOM