Search code examples
androidandroid-custom-view

How to know LayoutParams of View before measurement?


I have custom view with child items, which are configureable via xml. However they are can be configurable in runtime via something like a Configuration class. After that I just notify parent view about changes and all is ok.
BTW. My question in fact touches measurement: I can change child items size in runtime, but for the first launch I want to set to all of them size (width and height) accordingly to layout params defined in xml.

Maybe some code will add more clarification to you.

protected int getItemWidth() {
    if (cell != null) {
        int width = cell.getWidth();
        return width == 0 ? <layout_width_defined_in_xml> : ScreenUtils.convertToDp(context, width);
    } else {
        return canvasWidth;
    }
}

So, I want to know. Is possible to get layout params before measurement? And how to that?


Solution

  • The size defined in XML isn't always the right size the view should have when it's actually laid out. For example, a child of a LinearLayout may have android:layout_width="0", but might have nonzero width because of android:layout_weight. (There are other examples as well with other kinds of layouts.) Additionally, the values match_parent and wrap_content map to negative integer values in java code, which I don't think is helpful to you here.

    If your custom view is interested in measuring and positioning child views, you should be overriding onMeasure() and onLayout(). If you aren't doing that or if you don't need to do that, getWidth() and getHeight() will tell you a view's actual size, and getMeasuredWidth() and getMeasuredHeight() will tell you the measured size (which can differ from the actual size). THe only caveat is that you have to wait for the first measure/layout before calling those 4 methods because otherwise those methods all return zero.

    If you do want to inspect the layout parameters of a view, you can do

    LayoutParams params = view.getLayoutParams();
    int width = params.width;
    int height = params.height;
    

    As noted, either or both of those may be negative. You can compare them to LayoutParams.MATCH_PARENT and LayoutParams.WRAP_CONTENT to check for these cases, but again I'm not sure this is helpful to you if you aren't implementing onMeasure() and onLayout().