views:

52

answers:

2

I have a complex custom view - photo collage.

What is observed is whenever any UI interaction happens, the view is redrawn.

How can I avoid complete redrawing (for example, use a cached UI) of the view specially when I click the "back" button to go back to previous activity because that also causes redrawing of the view.

While exploring the API and web, I found a method - getDrawingCache() - but don't know how to use it effectively.

How do I use it effectively?

I've had other issues with Custom Views that I outline here.

A: 

Hello!

First of all you will have to use the setDrawingCacheEnabled(true) method, so that you're View is cache-enabled. Then, you can use the getDrawingCache(boolean) method which returns a Bitmap representing the View. Then, you can draw that bitmap manually.

If you don't enable caching by calling the setDrawingCacheEnabled(true) method, you will have to call buildDrawingCache() before (and call destroyDrawingCache() when you're done).

Bye!

Cristian
Hi Casidiablo,Thanks for your response.It is advisable to have a cache like this in the scenario when the updates / refreshes are more frequent? Or will it be applicable to only when we know what needs to be shown - dynamic, but once defined that is it!
MasterGaurav
+1  A: 

I found a better way than using getDrawingCache.

In the method onDraw, apart from drawing in the natural canvas, I also draw on an memory-only canvas.

Bitmap cacheBmp = Bitmap.Create(....);
Canvas cacheCanvas = new Canvas(cacheBmp);


void onDraw(Canvas c)
{
   if(updateDueToInteraction)
   {
     c.drawXXX(...);
     cacheCanvas.drawXXX(...);
   } else
   {
     c.drawBitmap(cacheBmp, 0, 0);
   }
}
MasterGaurav