Android 如何在onMeasure中获取自定义视图组高度

Android 如何在onMeasure中获取自定义视图组高度,android,android-custom-view,onmeasure,Android,Android Custom View,Onmeasure,这是对扩展FrameLayout的CustomView的测量。经过测量调查,高度大小始终为零。我怎么知道这个CustomView的高度大小,以便以后操作子视图 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int viewHeightMode = MeasureSpec.getMode(heightMeasureSpec);

这是对扩展FrameLayout的CustomView的测量。经过测量调查,高度大小始终为零。我怎么知道这个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);
    }
首先请阅读。它是关于测量视野的

关于视图组的主要区别在于,您应该在代码中度量所有孩子

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方法中,你无法测量孩子的尺寸——只需测量尺寸即可。但这只是一个猜测,最好检查一下。

谢谢你提供的信息,我将根据你的信息进行尝试