getMeasuredWidth returns totally wrong value

 ̄綄美尐妖づ 提交于 2019-11-29 20:58:40

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!