android开发记录1 GridView加载大量本地图片的bitmap的回收问题

本文介绍了一种在Android ListView中有效回收Bitmap资源的方法。通过重写ImageView并利用RecyclerListener接口中的onMovedToScrapHeap方法,实现了在item不可见时回收Bitmap资源,避免内存泄漏。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要回收的Bitmap必须是当前不显示的item的view,那么首先就得获取当前不显示的 view,通过查看AbsListView的源码可以看见有一个RecyclerListener接口,该类中有一个方法:

void onMovedToScrapHeap(View view);//在List滑动时,当某个item不可见就会调用该方法,但是该方法没有实现,我们可以在该方法里面对该item的资源进行回收。

eg:

这是某个item的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:descendantFocusability="blocksDescendants" >

    <com.zhouhao.mima.model.MyImageView
        android:id="@+id/image_list_item_image"
        android:layout_width="@dimen/image_width"
        android:layout_height="@dimen/image_height"
        android:layout_centerInParent="true"
        android:scaleType="fitXY"
        android:src="@drawable/ic_launcher" />

    <CheckBox
        android:id="@+id/image_list_item_check"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/image_list_item_image"
        android:layout_alignRight="@id/image_list_item_image"
        android:button="@drawable/check_box_selector" />

</RelativeLayout>
其中MyImageView是我继承ImageView写的类,后面会提到
每个item都有一个imageView,会使用大量的bitmap,我们就可以在onMovedToScrapHeap(View view)对bitmap进行回收。但是现在有个问题就是怎么获得该ImageView的bitmap,网上有些方法如下
image.setDrawingCacheEnabled(true);
		Bitmap bm=image.getDrawingCache();
我试了一下,获得的bm为空。

我使用的方法是重写ImageView的public void setImageBitmap(Bitmap bm) 方法

代码如下:

private Bitmap bitmap;

	@Override
	public void setImageBitmap(Bitmap bm) {
		this.bitmap = bm;
		super.setImageBitmap(bm);
	}

	public Bitmap getBitmap() {
		return bitmap;
	}

这样我们就可以获得该bitmap。

然后再onMovedToScrapHead()方法中处理

@Override
	public void onMovedToScrapHeap(View view) {
		MyImageView image = (MyImageView) view
				.findViewById(R.id.image_list_item_image);
		Bitmap bm = image.getBitmap();
		if (bm != null && !bm.isRecycled()) {
			bm.recycle();
			bm = null;
			System.gc();
			Log.e("不可见", "回收");
		}
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值