Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: I am unable to have ViewPager WRAP_CONTENT

Tags:

android

Overriding onMeasure of your ViewPager as follows will make it get the height of the biggest child it currently has.

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int height = 0;
    int childWidthSpec = MeasureSpec.makeMeasureSpec(
        Math.max(0, MeasureSpec.getSize(widthMeasureSpec) -
            getPaddingLeft() - getPaddingRight()),
        MeasureSpec.getMode(widthMeasureSpec)
    );
    for (int i = 0; i < getChildCount(); i++) {
        View child = getChildAt(i);
        child.measure(childWidthSpec, MeasureSpec.UNSPECIFIED);
        int h = child.getMeasuredHeight();
        if (h > height) height = h;
    }
    
    if (height != 0) {
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

Another more generic solution is to get wrap_content to just work.

I've extended ViewPager to override onMeasure(). The height is wraped around the first child view. This could lead to unexpected results if the child views are not exactly the same height. For that the class can be easily extended to let's say animate to the size of the current view/page. But I didn't need that.

You can use this ViewPager in yout XML layouts just like the original ViewPager:

<view
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    class="de.cybergen.ui.layout.WrapContentHeightViewPager"
    android:id="@+id/wrapContentHeightViewPager"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"/>

Advantage: This approach allows using the ViewPager in any layout including RelativeLayout to overlay other ui elements.

One drawback remains: If you want to use margins, you have to create two nested layouts and give the inner one the desired margins.

Here's the code:

public class WrapContentHeightViewPager extends ViewPager {

    /**
     * Constructor
     *
     * @param context the context
     */
    public WrapContentHeightViewPager(Context context) {
        super(context);
    }

    /**
     * Constructor
     *
     * @param context the context
     * @param attrs the attribute set
     */
    public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // find the first child view
        View view = getChildAt(0);
        if (view != null) {
            // measure the first child view with the specified measure spec
            view.measure(widthMeasureSpec, heightMeasureSpec);
        }

        setMeasuredDimension(getMeasuredWidth(), measureHeight(heightMeasureSpec, view));
    }

    /**
     * Determines the height of this view
     *
     * @param measureSpec A measureSpec packed into an int
     * @param view the base view with already measured height
     *
     * @return The height of the view, honoring constraints from measureSpec
     */
    private int measureHeight(int measureSpec, View view) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            // set the height from the base view if available
            if (view != null) {
                result = view.getMeasuredHeight();
            }
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }

}

I based my answer on Daniel López Lacalle and this post http://www.henning.ms/2013/09/09/viewpager-that-simply-dont-measure-up/. The problem with Daniel's answer is that in some cases my children had a height of zero. The solution was to unfortunately measure twice.

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int mode = MeasureSpec.getMode(heightMeasureSpec);
    // Unspecified means that the ViewPager is in a ScrollView WRAP_CONTENT.
    // At Most means that the ViewPager is not in a ScrollView WRAP_CONTENT.
    if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) {
        // super has to be called in the beginning so the child views can be initialized.
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int h = child.getMeasuredHeight();
            if (h > height) height = h;
        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    }
    // super has to be called again so the new specs are treated as exact measurements
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

This also lets you set a height on the ViewPager if you so want to or just wrap_content.


I was just answering a very similar question about this, and happened to find this when looking for a link to back up my claims, so lucky you :)

My other answer:
The ViewPager does not support wrap_content as it (usually) never have all its children loaded at the same time, and can therefore not get an appropriate size (the option would be to have a pager that changes size every time you have switched page).

You can however set a precise dimension (e.g. 150dp) and match_parent works as well.
You can also modify the dimensions dynamically from your code by changing the height-attribute in its LayoutParams.

For your needs you can create the ViewPager in its own xml-file, with the layout_height set to 200dp, and then in your code, rather than creating a new ViewPager from scratch, you can inflate that xml-file:

LayoutInflater inflater = context.getLayoutInflater();
inflater.inflate(R.layout.viewpagerxml, layout, true);