在我的自定义ViewGroup中,onMeasure方法没有被调用(Android)。

7
我有两个自定义的viewgroups,分别是superViewGroupsubViewGroup。其中,subViewGroup包含了视图。我将我的superviewgroup添加到一个LinearLayout中,并将subViewGroups添加到superviewgroup中。 superviewgrouponMeasure()方法被调用了,但是subviewgroup的没有被调用。不过,在这两种情况下,onLayout()方法都会被调用。
代码如下:
public class SuperViewGroup extends ViewGroup{

    public SuperViewGroup(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.i("boxchart","INSIDE ON MEASURE SUPER VIEWGROUP");
    }



    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        final int count = getChildCount();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != View.GONE) {
                child.layout(0, 0, getWidth(), getHeight());

            }
        }


    }


}


public class SubViewGroup extends ViewGroup{

    public SubViewGroup(Context context) {
        super(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.i("boxchart","INSIDE ON MEASURE SUB VIEWGROUP");
    }



    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        final int count = getChildCount();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != View.GONE) {
                child.layout(0, 0, getWidth(), getHeight());

            }
        }


    }


}

感谢您的评论。提前致谢。

以下是需要翻译的内容:
1个回答

7

因为你必须将测量值传递给子视图:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    Log.i("boxchart","INSIDE ON MEASURE SUPER VIEWGROUP");
    final int count = getChildCount();
    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (child.getVisibility() != View.GONE) {
            //Make or work out measurements for children here (MeasureSpec.make...)
            measureChild (child, widthMeasureSpec, heightMeasureSpec);
        }
    }
}

否则你永远无法真正测量你的子视图。如何做取决于你。仅仅因为你的 SuperViewGroup 在一个线性布局中,你的 SuperViewGroup 负责测量其子视图。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接