Search code examples
androidandroid-viewandroid-custom-viewviewgroup

Should a custom View inside a custom ViewGroup use onDraw() or layout()?


At first, I created a custom view that drew itself by overriding the onDraw() method. This turned out to be impractical because of the large amount of views I needed to create. So I've created a custom ViewGroup that draws each of it's childs with the onLayout() method.

I've read in the android documentation that the child view should implement a layout() method. But the child view I have made, uses the onDraw method to draw itself. How should I handle this? Should I get rid of the onDraw() method? And could anyone give me an example of how the layout() method works and how I should 'convert' my onDraw() method to a layout() method?

my current onDraw() method looks like this:

protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);

        //Draw Border.
        canvas.drawRect(mCellBounds, mBorderPaint);

        //Draw Background.
        canvas.drawRect(mBackgroundBounds, mBackGroundPaint);

        //Draw Value if not 0.
        if(Value != 0)
            canvas.drawText(Integer.toString(Value), ValueX, ValueY, mNumberPaint);

        //Draw Notes if Value == 0.
        else
        {
            for(int i = 0 ; i < 9 ; i++)
                if(NoteList[i])
                    canvas.drawText(Integer.toString(i), NoteX + ((i%3) * NoteMeasureX), NoteY + ((i/3) * NoteMeasureY), mNotePaint);
        }
    }

Solution

  • So I've created a custom ViewGroup that draws each of it's childs with the onLayout() method.

    I don't see how you draw the ViewGroup's children in its onLayout method. That method should be used to position the children on the screen.

    I've read in the android documentation that the child view should implement a layout() method

    That method is already implemented, you call it with the right values so the View will know where it should be placed on the screen.

    Should I get rid of the onDraw() method?

    If you want to actually see something you shouldn't ignore the onDraw method.

    And could anyone give me an example of how the layout() method works and how I should 'convert' my onDraw() method to a layout() method?

    You don't convert the onDraw method to the layout method. As an example, I made a small sample consisting of a custom ViewGroup along with a custom child View. The custom ViewGroup it will placed the two(expected children) like in the image below(each child will have half the width and height of the parent):

    custom ViewGroup

    You can find the sample here. I hope it helps you. You could also have a look at the source code for the SDK layouts(like the simple FrameLayout) to see how they do their magic.