Search code examples
androidandroid-custom-view

Do I need to call back super.onDraw() in a custom view?


I'm not too clear about this and neither are the docs.

When I'm creating a custom view, I override like so:

@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    //more code here...
}

My question is whether it's necessary to call super.onDraw(canvas);. The code seems to work fine without it, but I want to be sure that it's okay to leave it out.

So is it necessary?


Solution

  • If you want it to call the superclass onDraw method (think TextView or KeyboardView rather than a generic View), then call super.onDraw. If you don't want that, i.e. you are planning on drawing the entire View yourself (which it seems you are), there's no reason to call it.

    Also, if you're extending View (and not some class that extends view), super.onDraw doesn't really do anything.

    For me, I call super.onDraw when I want to draw lines over a KeyboardView. So, super.onDraw draws the keyboard, and my custom LatinKeyboardView (which extends KeyboardView) draws the swiping path on top of the keyboard.