我将在这里回答我自己的问题。覆盖的正确方法是onDetachedFromWindow
. 我在里面释放了我的位图,如果宽度或高度发生了变化,我在里面onDetachedFromWindow
重新分配它们。onMeasure
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (cachedBitmap != null && !cachedBitmap.isRecycled()) {
cachedBitmap.recycle();
cachedBitmap = null;
cachedBitmapWidth = -1;
cachedBitmapHeight = -1;
}
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int viewWidth = MeasureSpec.getSize(widthMeasureSpec);;
int viewHeight = MeasureSpec.getSize(heightMeasureSpec);;
if (cachedBitmapWidth != viewWidth || cachedBitmapHeight != viewHeight) {
if (cachedBitmap != null) {
cachedBitmap.recycle();
}
cachedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
cachedBitmapWidth = viewWidth;
cachedBitmapHeight = viewHeight;
Canvas canvas = new Canvas(cachedBitmap);
// do drawings here..
}
setMeasuredDimension(viewWidth, viewHeight);
}