代码之家  ›  专栏  ›  技术社区  ›  Steve Pomeroy

使用LinearLayout的自定义小部件未获得onDraw()

  •  45
  • Steve Pomeroy  · 技术社区  · 14 年前

    我正在通过扩展 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.
        }
    }
    

    我可以很好地添加孩子,但我从来没有得到我的习惯 onDraw() 被召唤。 dispatchDraw() 被调用,但它似乎有一个不同的画布(在填充中的画布)。我需要绘制整个布局区域)。有没有什么旗子需要设置才能拿到 onDraw() 有人要布置吗?

    1 回复  |  直到 14 年前
        1
  •  124
  •   weston    7 年前

    你需要打电话 setWillNotDraw(false) 在构造函数中。

    因为默认情况下布局不需要绘制,所以优化是不调用is draw方法。通过呼叫 setWillNotDraw(假) 告诉UI工具箱您要绘制。