当您在onMeasure方法中创建自定义组件时,可以指定大小甚至缩进(通过使用this.getPaddingTop()等)。问题是onMeasure的计算方法是否得到值“ margin ...”?鉴于不欢迎在 onMeasure 中使用“this.getLayoutParams ()”方法 - 请给出正确的规范解决方案来设置/获取“ margin ...”的值。
例子:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int wSpecMode = MeasureSpec.getMode( widthMeasureSpec );
int wSpecSize = MeasureSpec.getSize( widthMeasureSpec );
int hSpecMode = MeasureSpec.getMode( heightMeasureSpec );
int hSpecSize = MeasureSpec.getSize( heightMeasureSpec );
int lMargin = ((RelativeLayout.LayoutParams)this.getLayoutParams()).leftMargin;
int rMargin = ((RelativeLayout.LayoutParams)this.getLayoutParams()).rightMargin;
int tMargin = ((RelativeLayout.LayoutParams)this.getLayoutParams()).topMargin;
int bMargin = ((RelativeLayout.LayoutParams)this.getLayoutParams()).bottomMargin;
int wSize = 256, hSize = 256;
if (wSpecMode == MeasureSpec.EXACTLY) {
wSize = wSpecSize;
} else {
wSize += this.getPaddingLeft() + this.getPaddingRight() + lMargin + rMargin;
if (wSpecMode == MeasureSpec.AT_MOST) {
wSize = Math.min(wSize, wSpecSize);
}
}
if (hSpecMode == MeasureSpec.EXACTLY) {
hSize = hSpecSize;
} else {
hSize += this.getPaddingTop() + this.getPaddingBottom() + tMargin + bMargin;
if (hSpecMode == MeasureSpec.AT_MOST) {
hSize = Math.min(hSize, hSpecSize);
}
}
this.setMeasuredDimension( wSize, hSize );
}
在这个例子中,计算的均值可以,我们已经考虑了边距和填充,但是获取边距的方法不太优雅。
此外,这种方法区域组件在相同的边距上变得更多,并且通过getMeasuredWidth()和getMeasuredHeight()获得尺寸- 计算不正确。