I have a ViewGroup (lets call this A) in which a child is added. I want the A to be half the width of the parent.
Now in onMeasure I am setting the width to half of the parent size which comes in widthMeasureSpec but the problem I am facing is that the A view covers the half of the screen but the measurement does not due to which the children are not placed correctly.
Below is my onMeasure and 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());
}
}
I have added an example view for reference with the issue.