使用LinearLayout的自定义小部件无法获取onDraw()

Ste*_*roy 47 android android-widget ondraw android-linearlayout

我正在通过扩展来创建自定义小部件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.
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以添加孩子就好了,但我从来没有让我的自定义onDraw()被调用.dispatchDraw()被调用,但似乎有一个不同的画布(填充内的那个.我需要绘制整个布局区域).是否有一些标志需要设置onDraw()为布局调用?

Rom*_*Guy 117

你需要调用setWillNotDraw(false)你的构造函数.

因为默认情况下布局不需要绘制,所以优化是不调用draw方法.通过调用setWillNotDraw(false)您告诉您要绘制的UI工具包.

  • 因为默认情况下布局不需要绘制,所以优化是不调用draw方法.通过调用setWillNotDraw(false),您可以告诉您要绘制的UI工具包. (21认同)
  • @ Romain Guy,你能解释为什么需要添加`setWillNotDraw(false)`.谢谢! (3认同)
  • 伙计 - 你摇滚! (3认同)