将高度设置为自定义ViewGroup

时间:2015-03-26 11:45:06

标签: java android view android-custom-view onmeasure

我有一个自定义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);
}

它也没有任何效果。那问题出在哪里?

2 个答案:

答案 0 :(得分:0)

假设您的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,你可能需要在这里应用更多的逻辑。

此外,我应该注意,此测量逻辑假定不存在填充。如果您有填充,则应将totalChildHeight初始化为bottomPadding + topPadding

答案 1 :(得分:0)

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

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

setMeasuredDimension(widthMeasureSpec,heightMeasureSpec);

它适合我...