Own defined Layout , onDraw() method not getting called
Asked Answered
P

1

96

I defined a class like that:

public class TestMyFrameLayout extends FrameLayout{

    Paint mPaint;
    public TestMyFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TestMyFrameLayout(Context context) {
        super(context);
        mPaint = new Paint();
        mPaint.setColor(Color.GREEN);
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(50f, 50f, 30, mPaint);
    }   
}

and called it like:

TestMyFrameLayout myFrameLayout = new TestMyFrameLayout(this);
LayoutParams myFrameLayoutParams = new LayoutParams(300,300);
myFrameLayout.setLayoutParams(myFrameLayoutParams);
setContentView(myFrameLayout);

But In fact TestMyFrameLayout.onDraw(Canvas canvas) function not getting called, why?

Pacific answered 16/10, 2011 at 2:6 Comment(2)
Could you show the code where you make use of it? Also add @Override before onDraw: this will check for typo in eclipse.Krystin
Thank you Laurent'. My problem is already solved. Add this.setWillNotDraw(false);Pacific
P
238

Solved. Add this.setWillNotDraw(false); in constructor

Pacific answered 16/10, 2011 at 12:51 Comment(4)
It could have only been an angst ridden developer who set it to true by default!Laing
@RyanShao for ViewGroups it's set to true by default.Stirring
why the hell will someone want it to be true? why??Postexilian
I guess it's an optimisation for when a ViewGroup is a pure container with nothing to draw for itselfTwosided

© 2022 - 2024 — McMap. All rights reserved.