Android getMeasuredHeight returns wrong values !

后端 未结 7 702
野的像风
野的像风 2020-12-02 20:13

I\'m trying to determine the real dimension in pixels of some UI elements !

Those elements are inflated from a .xml file and are initialized with dip width and height

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 20:42

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

提交回复
热议问题