Android getMeasuredHeight returns wrong values !

You’re calling measure incorrectly.

measure takes MeasureSpec values which are specially packed by MeasureSpec.makeMeasureSpec. measure ignores LayoutParams. The parent doing the measuring is expected to create a MeasureSpec based on its own measurement and layout strategy and the child’s LayoutParams.

If you want to measure the way that WRAP_CONTENT usually works in most layouts, call measure like this:

frame.measure(MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST),
        MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST));

If you don’t have max values (for example if you’re writing something like a ScrollView that has infinite space) you can use the UNSPECIFIED mode:

frame.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
        MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

Leave a Comment