ViewPager that simply don’t measure up

If you, like me, have worked on an Android app that has used a ViewPager to act as a carousel for displaying images somewhere inside a view, then you probably have noticed that when specifying either width or height as wrap_content the ViewPager simply disappears from the view. Why is that?

According to some StackOverflow questions and answers: here and there, it seems that ViewPager doesn’t support wrap_content as it stands now because it doesn’t load all of its children at the same time, meaning it can’t get an appropriate measurement. That’s a bummer. There is however, solutions to the problem, yay!

  • JoostTheHost

    In your code you have:

    View firstChild = getChildAt(0);

    // Initially set the height to that of the first child - the
    // PagerTitleStrip (since we always know that it won't be 0).
    int height = firstChild.getMeasuredHeight();

    Shouldn’t this be like this:

    View firstChild = getChildAt(0);

    firstChild.measure(widthMeasureSpec, heightMeasureSpec);

    // Initially set the height to that of the first child - the
    // PagerTitleStrip (since we always know that it won't be 0).
    int height = firstChild.getMeasuredHeight();

    Thus with the added firstChild.measure(..)?

  • Pingback: Custom ViewPager inside ObservableScrollView not measuring Height Properly | DL-UAT()