2

我有一个Linearlayout将一些视图组合在一起的习惯。我希望这Linearlayoutwrap_content为了高度。我尝试像这样在 custrucor 中添加布局参数

LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 
                                       ViewGroup.LayoutParams.WRAP_CONTENT);
setLayoutParams(params);

但它没有效果。高度还在match_parent。我还尝试onMeasure根据这样的孩子的身高来计算身高

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    measureChildren(widthMeasureSpec,heightMeasureSpec);
    int size = 0;
    for(int i = 0; i <getChildCount();i++) {
        size += getChildAt(i).getMeasuredHeight();
    }
    int height = resolveSize(size,heightMeasureSpec);
    setMeasuredDimension(widthMeasureSpec,height);
}

它也没有任何作用。那么问题出在哪里?

4

2 回答 2

1

假设您的LinearLayout子类垂直排列视图,则覆盖该onMeasure方法的代码应该可以工作:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    final int containerWidth = MeasureSpec.getSize(widthMeasureSpec);
    final int containerHeight = MeasureSpec.getSize(heightMeasureSpec);

    final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(containerWidth, MeasureSpec.EXACTLY);
    final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(containerHeight, MeasureSpec.UNSPECIFIED);

    View child;
    int totalChildHeight = 0;

    for (int i = 0; i < getChildCount(); i++) {
        child = getChildAt(i);

        if (child == null || child.getVisibility() == View.GONE)
            continue;

        measureChildWithMargins(child, childWidthMeasureSpec, 0, childHeightMeasureSpec, totalChildHeight);           

        totalChildHeight += child.getMeasuredHeight();
    }

    setMeasuredDimension(containerWidth, totalChildHeight);
}

请记住,这实质上会覆盖LinearLayout's测量逻辑。虽然这段代码几乎做同样的事情,除了以更明确的方式,它也完全忽略weights了给孩子,所以如果你需要weights,你可能需要在这里应用更多的逻辑。

另外,我应该注意,这个测量逻辑假设不存在填充。如果你有填充,你应该初始化totalChildHeightbottomPadding+ topPadding

于 2015-03-26T12:12:51.070 回答
-1

嗨,在onMeasure方法中,您必须在计算所需的总高度后添加它,您必须使用 makeMeasureSpec,如下所述:

heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightRequired, MeasureSpec.EXACTLY);

setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);

它对我有用...

于 2016-10-24T05:52:04.803 回答