我有一个自定义视图类(称为FooView
),用作XML布局的根元素。FooView
在中onDraw()
,用于canvas
在的底部边缘绘制形状FooView
。
我认为,为了FooView
不中断形状,我需要重写它onMeasure
并做一些修改所FooView
报告的高度的操作,以使其现在包括所绘制形状的高度。
那是对的吗?如果是这样,我该怎么办?
谢谢!
是的,如果要创建自定义视图,则需要覆盖onMeasure()
并提供所需的大小。
因此,在的方法签名中onMeasure
,您将获得两个参数:
您应该使用MeasureSpec
该类来获取在调整View大小时应遵守的限制。
/*
* This will be one of MeasureSpec.EXACTLY, MeasureSpec.AT_MOST,
* or MeasureSpec.UNSPECIFIED
*/
int mode = MeasureSpec.getMode(measureSpec);
//This will be a dimension in pixels
int pixelSize = MeasureSpec.getSize(measureSpec);
如果得到MeasureSpec.EXACTLY
,则pixelSize
无论如何都应使用该值作为测得的宽度。
如果得到MeasureSpec.AT_MOST
,您应该确保将测量宽度设置为不大于pixelSize
。
如果得到MeasureSpec.UNSPECIFIED
,您可以根据需要容纳更多空间。我通常将其解释为WRAP_CONTENT
。
因此,您的onMeasure()
方法可能如下所示:
@Override
protected void onMeasure (int widthSpec, int heightSpec) {
int wMode = MeasureSpec.getMode(widthSpec);
int hMode = MeasureSpec.getMode(heightSpec);
int wSize = MeasureSpec.getSize(widthSpec);
int hSize = MeasureSpec.getSize(heightSpec);
int measuredWidth = 0;
int measuredHeight = 0;
if (wMode == MeasureSpec.EXACTLY) {
measuredWidth = wSize;
} else {
//Calculate how many pixels width you need to draw your View properly
measuredWidth = calculateDesiredWidth();
if (wMode == MeasureSpec.AT_MOST) {
measuredWidth = Math.min(measuredWidth, wSize);
}
}
if (hMode == MeasureSpec.EXACTLY) {
measuredHeight = hSize;
} else {
//Calculate how many pixels height you need to draw your View properly
measuredHeight = calculateDesiredHeight();
if (hMode == MeasureSpec.AT_MOST) {
measuredHeight = Math.min(measuredHeight, hSize);
}
}
setMeasuredDimension(measuredWidth, measuredHeight);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句