如何在onMeasure中获取Custom ViewGroup高度

时间:2017-03-12 04:13:13

标签: android android-custom-view onmeasure

这是onMeasure()的CustomView extend FrameLayout。调查onMeasure()后,高度大小始终为零。我怎么知道这个CustomView的高度大小以便稍后操作子视图。

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

            int viewHeightMode = MeasureSpec.getMode(heightMeasureSpec);
            int viewWidthMode = MeasureSpec.getMode(widthMeasureSpec);
            int viewHeight = MeasureSpec.getSize(heightMeasureSpec);
            int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

1 个答案:

答案 0 :(得分:0)

首先请阅读this question。它是关于View的测量。

您应该在所有孩子的代码中衡量ViewGroup的主要区别。

for(int i=0; i<getChildCount(); i++) {
    View child = getChildAt(i);
    LayoutParams lp = child.getLayoutParams();
    int widthMeasureMode = lp.width == LayoutParams.WRAP_CONTENT ? MeasureSpec.AT_MOST : MeasureSpec.EXACTLY,
        heightMeasureMode = lp.height == LayoutParams.WRAP_CONTENT ? MeasureSpec.AT_MOST : MeasureSpec.EXACTLY;
    int widthMeasure = MeasureSpec.makeMeasureSpec(getWidth() - left, widthMeasureMode),
        heightMeasure = MeasureSpec.makeMeasureSpec(getHeight() - top, heightMeasureMode);
    child.measure(widthMeasure, heightMeasure);
    int childWidth = child.getMeasuredWidth(),
        childHeight = child.getMeasuredHeight();
    //make something with that
}

这显示了如何获得所有孩子的大小。可能是你想要计算高度之和,可能只是找到最大值 - 这是你自己的目标。

顺便说一下。如果您的基类不是ViewGroup,而是FrameLayout,则可以使用onLayout方法测量子项。在这种情况下,在您的onMeasure方法中,您无法对测量孩子做任何事情 - 只需要采取尺寸。 但这只是一个猜测 - 最好检查一下。

相关问题