Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 925
yydl Avatar asked Apr 09 '12 02:04

yydl


People also ask

Which view method one must override to customize the drawing of a view?

Override onDraw() The most important step in drawing a custom view is to override the onDraw() method. The parameter to onDraw() is a Canvas object that the view can use to draw itself.

How do I call onDraw?

Call mView. invalidate(); in your onClick() method for that View. This will call onDraw() (eventually), which will then run the drawing code for your view. This will allow you to also invoke onDraw() of the view in the main activity.

What is the use of Canvas view?

Canvas is a class in Android that performs 2D drawing of different objects onto the screen. The saying “a blank canvas” is very similar to what a Canvas object is on Android. It is basically, an empty space to draw onto.


1 Answers

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.

like image 126
lrAndroid Avatar answered Sep 28 '22 11:09

lrAndroid