自定义View设置padding和wrap_content无效的解决办法
当我们使用重写onDraw方法来实现自定义View的时候,发现在xml文件设置自定义View的padding不起作用和设置wrap_content时与match_parent效果一样。其实采用重写onDraw方法自定义View是需要自己支持wrap_content,并且padding也是要自己处理的。举个例子说明一下:使用重写onDraw方法来实现自定义一个实心圆canvas.drawCircle(width / 2, height / 2, radius, mPaint);
- 对于设置wrap_content属性无效的问题,在自定义View类添加如下重写方法,设置默认值即可。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode ==
MeasureSpec.AT_MOST)
setMeasuredDimension(200, 200);
else if (widthSpecMode == MeasureSpec.AT_MOST)
setMeasuredDimension(200, heightSpecSize);
else if (heightSpecMode == MeasureSpec.AT_MOST)
setMeasuredDimension(widthSpecSize, 200);
}
- 对于设置padding值无效的问题,在onDraw方法中获取对应padding的值,然后进行对应的计算即可。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int paddingLeft = getPaddingLeft();
int paddingRight =getPaddingRight();
int paddingBottom = getPaddingBottom();
int paddingTop = getPaddingTop();
int width = getWidth()-paddingLeft-paddingRight;
int height = getHeight()-paddingBottom-paddingTop;
float radius = Math.min(width,height)/2;
canvas.drawCircle(paddingLeft + width/2,paddingTop + height/2,radius,paint);
}
这里有个问题:为什么margin 不需要自行设置?
这是因为margin属性是由父容器控制的,因此不需要在circleView类中处理。