Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onMeasure not getting called in my custom viewgroup android

Im having two custom viewgroups, superViewGroup and subViewGroup. The subviewgroup contains views. Im adding my superviewgroup to a linearLayout and the subViewGroups to my superviewgroup.

The superviewgroup onMeasure() is getting called but not in the subviewgroup. but in both cases onLayout() method is getting called.

The code as follows

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());

            }
        }


    }


}

Comments are appreciated. thanks in advance.

like image 765
srinivasan Avatar asked Oct 13 '11 05:10

srinivasan


1 Answers

Because you have to actually pass the measure to the children views:

@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);
        }
    }
}

Otherwise you never actually measure your children. It is up to you to decide how to do this. Just because your SuperViewGroup is in a linear layout, your SuperViewGroup takes on responsibility to measure its children.

like image 139
Chris.Jenkins Avatar answered Oct 03 '22 05:10

Chris.Jenkins