Override onDraw() or draw()? Override onDraw() or draw()? android android

Override onDraw() or draw()?


I tried cleaning my project and it did solve the problem. Try it.


SurfaceView.draw() basically calls View.draw(); If you want to implement your drawing, you should do it in View.onDraw() which is for you to implement which even says in the source code comments.

This method is called by ViewGroup.drawChild() to have each child view draw itself. This draw() method is an implementation detail and is not intended to be overridden or to be called from anywhere else other than ViewGroup.drawChild().

As for difference between them:
draw():

13416        /*13417         * Draw traversal performs several drawing steps which must be executed13418         * in the appropriate order:13419         *13420         *      1. Draw the background13421         *      2. If necessary, save the canvas' layers to prepare for fading13422         *      3. Draw view's content13423         *      4. Draw children13424         *      5. If necessary, draw the fading edges and restore layers13425         *      6. Draw decorations (scrollbars for instance)13426         */

onDraw() is empty. Its for you to implement.


I have the problem since ever.

I handle it like this:

1) Declare a method like the following.

@SuppressLint("WrongCall")public void drawTheView() {    theCanvas = null;    try{        theCanvas = getHolder().lockCanvas();        if(theCanvas != null) {            onDraw(theCanvas);        }    } finally {        getHolder().unlockCanvasAndPost(theCanvas);    }}

2) Now you can modify the onDraw() Method:

@Overridepublic void onDraw(Canvas canvas) {    //Do some drawing}

You can call the drawTheView() method from everywhere you want and call the onDraw() method this way without getting the error...

I think this is a practical way.