问题一、继承ViewGroup不调用onDraw()方法
在我们根据自己的需求自定义控件的时候,某些时候需要继承ViewGroup,并且需要在onDraw()方法中进行绘图操作;
按照往常继承View的控件的方式,实现onDraw()方法,在调用构造等方法后会自动调用onDraw()方法。但是在继承ViewGroup的时候,运行实际情况发现并不会自动调用onDraw()方法;
造成这种想象的原因是继承自LinearLayout,而LinearLayout这是一个容器,ViewGroup它本身并没有任何可画的东西,它是一个透明的控件,因些并不会触发onDraw;
如果我们要重写ViweGroup的onDraw()方法,有两种方法:
在构造函数里面,给其设置一个颜色,如#00000000;
在构造函数里面,调用setWillNotDraw(false),去掉其WILL_NOT_DRAW flag;
[java] view plaincopy
public class CustomViewGroup extends LinearLayout {
/** 画笔 */
private Paint paint;
public CustomViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
// 解析自定义布局
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.custom_viewgroup, this);
// 设置抗锯齿,防抖动效果
paint = new Paint();
paint.setAntiAlias(true);
paint.setDither(true);
setWillNotDraw(false);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//由于特殊需求,在加载布局之后,还需要进行绘图操作
canvas.drawLine(0, 0, getWidth(), getHeight(), paint);
}
}
运行效果如下:
评论