7

我有两个自定义viewgroupssuperViewGroupsubViewGroup。子视图组包含视图。我将我的 superviewgroup 添加到一个 linearLayout 和subViewGroups我的superviewgroup.

超级视图onMeasure()组被调用但不在子视图组中。但在这两种情况下,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());

            }
        }


    }


}

评论表示赞赏。提前致谢。

4

1 回答 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责任测量它的孩子。

于 2013-01-22T15:20:57.310 回答