user291701
user291701

Reputation: 39681

Drawing something on my LinearLayout?

I'm extending LinearLayout:

public class MyLinearLayout extends LinearLayout {
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        Paint paint = new Paint();
        paint.setColor(0xFFFF0000);
        canvas.drawLine(0, 0, getWidth(), getHeight(), paint);
    }
}

If the layout has child elements, shouldn't the red line above be drawn on top of them? Considering a layout like:

<MyLinearLayout>
    <ImageView />
</MyLinearLayout>

I'd expect to get the red line drawn above the child ImageView. But it gets drawn below it. I was assuming all child drawing would have been completed after the super.onDraw() line is finished.

Is there a way to get to the canvas and draw something on it after all child drawing has been completed?

Thanks

Upvotes: 2

Views: 5616

Answers (3)

Interkot
Interkot

Reputation: 737

If you have a LinearLayout and you need:

  1. draw all of its children first, like buttons, image views
  2. then, on top of those components, draw something directly on the canvas.

    You can try this:

    public class YourClass extends LinearLayout
    {
    @Override
    protected void dispatchDraw(Canvas canvas)
    {
        super.dispatchDraw(canvas); 

    // do your custom drawings afterwards canvas.drawCircle... canvas.drawLine...

Upvotes: 1

Chris Sullivan
Chris Sullivan

Reputation: 586

I'm rewriting my answer as I hadn't seen your line of code where you were drawing to the canvas.

The canvas like some other graphics environments is inverted. So calling getHeight() is actually drawing the line at the bottom. Instead call

   canvas.drawLine( 0, 0, getWidth(), 0, paint);

This means draw the line at the top, across the width of the view.

Also, calling super first paints the children prior to any custom painting so your fine there.

Upvotes: 0

DeeV
DeeV

Reputation: 36035

Layouts don't draw unless you call setWillNotDraw(false);. They do that for efficiency reasons.

EDIT:

onDraw() really is meant to just allow you to modify the Canvas before the drawing operation happens. It doesn't actually draw. What you want to do is override draw() like so:

@Override
protected void draw(Canvas canvas) {
    super.draw(canvas);

    Paint paint = new Paint();
    paint.setColor(0xFFFF0000);
    canvas.drawLine(0, 0, getWidth(), getHeight(), paint);
}

Calling the super will draw all the children in the view. Then it will draw all the lines. I do still believe you need setWillNotDraw(false) to be called though.

Upvotes: 11

Related Questions