【问题标题】:onMeasure not getting called in my custom viewgroup androidonMeasure 没有在我的自定义视图组 android 中被调用
【发布时间】:2011-10-13 05:50:15
【问题描述】:

我有两个自定义 viewgroupssuperViewGroupsubViewGroup。子视图组包含视图。我将我的超级视图组添加到一个线性布局,并将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());

            }
        }


    }


}

欢迎评论。提前致谢。

【问题讨论】:

    标签: android android-custom-view viewgroup


    【解决方案1】:

    因为您必须将度量实际传递给子视图:

    @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 就负责测量其子级。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 2014-02-06
      • 2012-08-29
      • 2014-05-17
      • 2018-07-21
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多