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 = RelativeLayout.LayoutParams.WRAP_CONTENT;
int specWidth = MeasureSpec.makeMeasureSpec(wrapContent, MeasureSpec.AT_MOST);
view.measure(specWidth, specWidth);
int questionWidth = view.getMeasuredWidth();
This works as expected on an Android 4.3 emulator.
However the returned measured width on a Samsung Galaxy XCover 2 (S7710) Android 4.1.2 phone, is 16777214...
I tried everything, masking with View.MEASURED_SIZE_MASK
, but nothing helped.
Could you provide some help with this? Thanks in advance!
Passing
WRAP_CONTENT
instead of an actual value tomakeMeasureSpec()
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 basicallyMath.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 aScrollView
) your option isMeasureSpec.UNSPECIFIED
-- and any value as first argument.So, {gurus, correct me if I'm wrong} you get
WRAP_CONTENT
behavior with any mode other thanMeasureSpec.EXACTLY
That being said, try:
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 ofmeasure()
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.