Wednesday, December 7, 2011

Custom View Drawing in Android with Infinite Recursion

Nice title, eh?  No, it's not something you want to do, but it's something easy to do if you take a shortcut.

In View.onDraw, you might be tempted to call this.setBackgroundDrawable, or this.setBackgroundColor like this:
 @Override
 protected void onDraw(Canvas canvas) {
          if (image) {
            setBackgroundDrawable(d);
          } else {
            setBackgroundColor(0xffffffff);
          }
 }

That's a bad idea.  These calls result in a recursive call to your onDraw method (although the Android javadocs don't seem to say so).  You might not notice at first, or at all, until one day something draws attention to the fact that your view is furiously drawing itself repeatedly forever.

The solution is to use the Canvas and Drawable methods that do the same things. It's just as easy, and you'll avoid the unwanted recursion.
 @Override
 protected void onDraw(Canvas canvas) {
          if (image) {
            d.draw(canvas)
          } else {
            canvas.drawColor(0xffffffff);
          }
 }

No comments:

Post a Comment