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

2019-03-17 22:22发布

问题:

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?

回答1:

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.



回答2:

A peek at the source code shows that View.onDraw() is an empty method. So, calling super.onDraw(), if the parent class is View itself, does nothing. It's unnecessary yet harmless.

Whether you should go ahead and do it anyway is a separate question of efficiency, safety, and style.



回答3:

Yes, it is. If you custom a TextView, the super.onDraw will ensure to draw whatever belongs to TextView attributes (like the text, text color, text shadow, etc...) The same with other Views like Button, CheckBox...

In case your custom View extend View (not a specific subclass of View, just View), it is still better to leave super.onDraw(canvas) there for some View's draw methods (like setBackgroundDrawable, etc...)



回答4:

It's not required unless you are actually overriding the onDraw() method. If the new class doesn't override it, the super's method will automatically be called.