问题
I'm writing a custom view in Android. Since I need precise size management, I've overridden onMeasure. Its documentation says, that View.MeasureSpec.getMode returns one of three values, defined as constants. But when my view was placed inside HorizontalScrollView, widthMeasureSpec was 0 - I was unable to get both mode and size from it.
What is even weirder is that this parameter was 0 even if I explicitly defined width for my view.
Why does it happen, how should I interpret the 0 value and what should I do in this particular case?
回答1:
0
means the mode is UNSPECIFIED
. This means you can be as big as you want, which makes sense since it is a ScrollView
...intended for a View
bigger than your actual screen.
Being unspecified, you don't have to care about the size, this is why it is 0
.
If you look at the source of HorizontalScrollView
you can also see that it just passes width: 0, UNSPECIFIED
to the child:
@Override
protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
ViewGroup.LayoutParams lp = child.getLayoutParams();
int childWidthMeasureSpec;
int childHeightMeasureSpec;
childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, mPaddingTop
+ mPaddingBottom, lp.height);
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
To get the child view as big as the parent you can use fillViewPort
from xml or java which will lead to a call with mode EXACTLY
:
if (!mFillViewport) {
return;
}
// ...
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
This is one way to handle your child view being as big as the ScrollView
.
来源:https://stackoverflow.com/questions/35589320/widthmeasurespec-is-0-when-in-horizontalscrollview