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);
}
}
I don’t see how you draw the
ViewGroup‘s children in itsonLayoutmethod. That method should be used to position the children on the screen.That method is already implemented, you call it with the right values so the
Viewwill know where it should be placed on the screen.If you want to actually see something you shouldn’t ignore the
onDrawmethod.You don’t convert the
onDrawmethod to thelayoutmethod. As an example, I made a small sample consisting of a customViewGroupalong with a custom childView. The customViewGroupit will placed the two(expected children) like in the image below(each child will have half the width and height of the parent):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.