View onDraw(Canvas c) versus draw(Canvas c) in android?-ThrowExceptions

Exception or error:

I am new to android development, I am exploring about View. I come across to known two methods onDraw(Canvas c) and draw(Canvas c).

Could please explain me the difference and usage of these two methods? Which method will give better performance(FPS) when updating canvas with images?

How to solve:

There is difference between them

  1. The onDraw(Canvas c) is a override method and automatically called when the view is being rendered. Here you can do your additional drawing like make circles, lines or whatever you want.

  2. The draw(Canvas c) is used to manually render this view (and all of its children) to the given canvas. The view must have already done a full layout before this function is called. When implementing a view, implement onDraw( instead of overriding this method. If you do need to override this method, call the superclass version.

Or in simple words draw(Canvas c) is simply a function that is not automatically called when the view is rendered. User is needed to provide the canvas on which this view will rendered and user also have to do all the drawing on the canvas before calling this function.


Just if someone was still looking for answer like me and didn’t find it.

The draw() method is called by the framework when the view need to be re-drawn and the draw() method then calls the onDraw() to draw the view’s content.

void draw(Canvas canvas)
     ..... do default stuff (background, layers)
     ..... do other stuff ( scroll bars, fading edges, children)



There is a misconception about this as a result of awkward API documentation.
The short answer is that draw(Canvas) is an inbound call on a View to do some important stuff and somewhere in the middle of the draw(Canvas) implementation it will also trigger an onDraw(Canvas) callback.

  • Don’t override draw(Canvas) when implementing a custom View intended to be used inside a layout.
  • If your custom view is intended to be used as a full screen game, then overriding draw() will save you some unneeded calls on every cycle.

Longer Answer

  • The framework uses draw(Canvas) in its draw cycle. This is what I could find in the View code:
    • Step 1: draw the background, if needed
    • Step 2: save the canvas’ layers
    • Step 3: draw the content — onDraw() comes here
    • Step 4: draw the children
    • Step 5: draw the fade effect and restore layers
    • Step 6: draw the scrollbars

Useful tip

  • You can render any view into an offscreen Bitmap you create, and later use this bitmap anywhere:

    Canvas c = new Canvas();
    • for simple cases (when it’s not a ViewGroup and no scrollbars are needed), the simple onDraw(Canvas) could also do the trick.

Leave a Reply

Your email address will not be published. Required fields are marked *