View#setWillNotDraw() 方法

今天在自定一个FrameLayout的时候发现onDraw()方法不会被调用, 最后定位到原因在WILL_NOT_DRAWViewGroup在默认情况下为了提高自身的绘制性能会设置WILL_NOT_DRAW标记, 用来设置不执行onDraw()方法.因此如果在自定义ViewGroup的时候一定都要注意去掉这个标记位, 否则onDraw() 不会被执行.有两种方法可以达到这种效果.

  • 设置ViewGroup的背景色, 通过设置PFLAG_SKIP_DRAW 其实WILL_NOT_DRAW 最终也会转换成前一个标记.
  • 使用setWillNotDraw(false) 去掉WILL_NOT_DRAW标志.

来看下该方法的内部实现

/**
 * 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);
}

你可能感兴趣的:(Android---基础学习)