举个例子,当我们继承View来实现一个自定义view时,重写onDraw方法,画一个圆,canvas.drawCircle(width / 2, height / 2, radius, mPaint);当我们在布局中使用时,对其加上padding属性:padding=10;会发现padding属性根本不起作用,或者我们把width设置为wrap_content,同样会发现该属性失效了,我们也会发现width设置为wrap_content和match_parent没有任何的区别。
解决方法:
1、针对wrap_content,只需要在onMeasure方法中指定默认宽高即可,
protected void onMeasure(int widthMeasureSpec, int 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(100, 100);
else if (widthSpecMode == MeasureSpec.AT_MOST) setMeasuredDimension(100, heightSpecSize);
else if (heightSpecMode == MeasureSpec.AT_MOST) setMeasuredDimension(widthSpecSize, 100);
}
2、padding问题:在onDraw方法中对其进行修改;
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
int paddingBottom = getPaddingBottom();
int width = getWidth() - paddingLeft - paddingRight;
int height = getHeight() - paddingTop - paddingBottom;
int radius = 50;
canvas.drawCircle(paddingLeft + width / 2, paddingTop + height / 2, radius, mPaint);
}