0

这是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);
    }
4

1 回答 1

1

首先请阅读这个问题。它是关于测量的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方法中,您对测量孩子无能为力 - 只需测量尺寸即可。但这只是一个猜测 - 最好检查一下。

于 2017-03-12T04:46:35.287 回答