ViewGroup 调用onDraw
2020-07-20 本文已影响0人
zcwfeng
ViewGroup默认情况下,出于性能考虑,会被设置成WILL_NOT_DROW,这样ondraw就不会被执行了,
如果我们想重写一个ViewGroup的onDraw()方法,有两种方法:
1、构造函数中,给ViewGroup设置一个颜色;
2、构造函数中,调用setWillNotDraw(false),去掉期WILL_NOT_DRAW flag,在ViewGroup初始化的时候,它调用了一个私有方法:initViewGroup,它里面会有一句setFlags(WILL_NOT_DRAW,DRAW_MASK);相当于调用 了setWillNOtDraw(true),所以说对于ViewGroup它就认为是透明的了,如果我们想要重写onDraw(),就要调用setWillNotDraw(false)。
源码:
/**
* If this view doesn't do any drawing on its own, set this flag to
* allow further optimizations. By default, this flag is not set on
* View, but could be set on some View subclasses such as ViewGroup.
*
* Typically, if you override {@link #onDraw(android.graphics.Canvas)}
* you should clear this flag.
*
* @param willNotDraw whether or not this View draw on its own
*/
public void setWillNotDraw(boolean willNotDraw) {
setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
}