Where to properly deactivate a bitmap on Android View?

I have a custom view that draws a bunch of things, including bitmaps. I want to cache this drawing on a bitmap, so I just need to draw one bitmap inside onDraw, instead of repeating these drawing and calculation tasks.

Raster images need to be processed after we no longer use it. I do not see onDestroy () or anything similar remotely in the View class. Is there a callback method that I can override to achieve this?

public void <insert_callback_here>() {
    cachedBitmap.recycle();
}

No animation. This is a static image. A lot of calculations were done to draw the image, so I would prefer to do it once on onMeasure ().

+5
source share
1 answer

I am going to answer my question here. The right methods to override onDetachedFromWindow. I delete the bitmap inside onDetachedFromWindowand redistribute them inside onMeasureif the width or height has changed.

@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);
}
+7
source

All Articles