我有一个ViewGroup(我们称之为 A ),其中添加了一个子项。我希望 A 是父级宽度的一半。
现在在onMeasure中我将宽度设置为widthMeasureSpec中的父级大小的一半,但我面临的问题是A视图覆盖了屏幕的一半,但测量不是因为孩子不是正确放置。
下面是我的onMeasure和onLayout。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthLimit = MeasureSpec.getSize(widthMeasureSpec) - getPaddingRight();
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int width = 0;
int height = 0;
int rightPadding = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
rightPadding = child.getPaddingRight();
measureChild(child, MeasureSpec.makeMeasureSpec((widthLimit / 2) - rightPadding - child.getPaddingLeft(), widthMode), heightMeasureSpec);
width += child.getMeasuredWidth();
height += child.getMeasuredHeight();
}
width = widthLimit / 2;
width -= rightPadding;
setMeasuredDimension(width, resolveSize(height, heightMeasureSpec));
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
}
}
我添加了一个示例视图以供参考。