2

我有一个 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());
    }
}

我添加了一个示例视图以供参考。

在此处输入图像描述

4

0 回答 0