getMeasuredWidth returns totally wrong value

前端 未结 1 1625
粉色の甜心
粉色の甜心 2020-12-23 14:28

I have to measure a View for spacing others. I use this code for that:

ViewGroup view = ...;
view.setPadding(10, 0, 10, 0);
int wrapContent = Re         


        
相关标签:
1条回答
  • 2020-12-23 15:18

    Passing WRAP_CONTENT instead of an actual value to makeMeasureSpec() won't do any good, I don't think those were meant to be used together.

    Use actual constraint value as first parameter (e.g. size of the parent view or dimensions of the screen) with the MeasureSpec.AT_MOST mode, which is basically Math.min() -- with arguments being the value you put in the spec and the view's desired dimension.

    MeasureSpec.EXACTLY will make it use the spec value, MeasureSpec.UNSPECIFIED will make it use the view's desired value. So if you don't have any constraints (like if you put your view into a ScrollView) your option is MeasureSpec.UNSPECIFIED -- and any value as first argument.

    So, {gurus, correct me if I'm wrong} you get WRAP_CONTENT behavior with any mode other than MeasureSpec.EXACTLY

    That being said, try:

    ViewGroup view = ...;
    view.setPadding(10, 0, 10, 0);
    // Either this
    int specWidth = MeasureSpec.makeMeasureSpec(parentWidth, MeasureSpec.AT_MOST);
    // Or this
    int specWidth = MeasureSpec.makeMeasureSpec(0 /* any */, MeasureSpec.UNSPECIFIED);
    view.measure(specWidth, specWidth);
    int questionWidth = view.getMeasuredWidth();
    

    PS Funny thing about 16777214, take a look at the number in binary: https://www.google.ru/search?q=16777214+in+binary It's -2 (which is the constant value of LayoutParams.WRAP_CONTENT) but with 8 most significant bits truncated with a logical operation (hence no minus), there's something in call stack of measure() that does this :) I wonder if this is a bug. Maybe it should be checking the argument for being negative and throwing an exception or something.

    0 讨论(0)
提交回复
热议问题