在GridView适配器中回收位图是为了避免内存泄漏和提高应用性能。以下是一种常见的方法:
以下是一个示例代码:
public class MyAdapter extends BaseAdapter {
private Context mContext;
private List<String> mImageUrls;
private LayoutInflater mInflater;
public MyAdapter(Context context, List<String> imageUrls) {
mContext = context;
mImageUrls = imageUrls;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mImageUrls.size();
}
@Override
public Object getItem(int position) {
return mImageUrls.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.grid_item, parent, false);
holder = new ViewHolder();
holder.imageView = convertView.findViewById(R.id.image_view);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
// 回收之前的位图
if (holder.bitmap != null) {
holder.bitmap.recycle();
}
}
// 加载位图
Bitmap bitmap = loadBitmap(position);
holder.imageView.setImageBitmap(bitmap);
holder.bitmap = bitmap;
return convertView;
}
private Bitmap loadBitmap(int position) {
// 加载位图的逻辑
// 使用BitmapFactory.Options的inBitmap属性来复用位图
BitmapFactory.Options options = new BitmapFactory.Options();
options.inBitmap = holder.bitmap;
return BitmapFactory.decodeFile(mImageUrls.get(position), options);
}
private static class ViewHolder {
ImageView imageView;
Bitmap bitmap;
}
}
这样,在GridView适配器中回收位图可以有效地避免内存泄漏和提高应用性能。请注意,以上示例代码仅供参考,实际实现可能因应用需求而有所不同。
领取专属 10元无门槛券
手把手带您无忧上云