使用 LinearLayout 的自定义小部件未获得 onDraw()
我正在通过扩展 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()
?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在构造函数中调用
setWillNotDraw(false)
。因为默认情况下布局不需要绘制,所以一个优化是不调用 is draw 方法。通过调用
setWillNotDraw(false)
,您可以告诉 UI 工具包您想要绘制。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.