widthMeasureSpec is 0 when in HorizontalScrollView

狂风中的少年 提交于 2020-01-07 00:44:23

问题


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

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