在方法 onMeasure 中创建自定义组件时,可以指定大小甚至缩进(使用 this.getPaddingTop()等)。 问题是计算 onMeasure 的方法是否获得值“保证金 ...”?鉴于在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()获取大小 - 计算不正确。