Custom Widget using LinearLayout not getting onDraw()

AndroidAndroid WidgetAndroid LinearlayoutOndraw

Android Problem Overview


I'm creating a custom widget by extending LinearLayout:

public class MyWidget extends LinearLayout {
    private static Paint PAINT = new Paint(Paint.ANTI_ALIAS_FLAG);
    static {
        PAINT.setColor(Color.RED);
    }

    public MyWidget(Context context) {
        this(context, null);
    }

    public MyWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight()/2, canvas.getWidth()/2, PAINT);
        // never gets called :-(
    }
    
    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        // this gets called, but with a canvas sized after the padding.
    }
}

I can add children just fine, but I'm never getting my custom onDraw() being called. dispatchDraw() gets called, but that seems to have a different canvas (the one that's within the padding. I need to draw on the whole layout area). Is there some flag that needs to get set to get onDraw() called for the layout?

Android Solutions


Solution 1 - Android

You need to call setWillNotDraw(false) in your constructor.

Because by default a layout does not need to draw, so an optimization is to not call is draw method. By calling setWillNotDraw(false) you tell the UI toolkit that you want to draw.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteve PomeroyView Question on Stackoverflow
Solution 1 - AndroidRomain GuyView Answer on Stackoverflow