我正在通过扩展 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()
方法?