Friday, May 9, 2014

How to force the View Pager to wrap its content.

The problem is that the "wrap_content" doesn't seem to be working with the View pager.
Here is the solution:
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;

public class CustomViewPager extends ViewPager {

    public CustomViewPager(Context context) {
        super(context);
    }

public CustomViewPager(Context context, AttributeSet attrs){

        super(context, attrs);
    }

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

        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.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

reference:
http://stackoverflow.com/questions/8394681/android-i-am-unable-to-have-viewpager-wrap-content

That's it, don't hesitate to comment, to share your knowledge and to correct me.

12 comments:

  1. Thanks man. It works like a charm!

    ReplyDelete
  2. saved my day. lots of thanks, millions of thanks

    ReplyDelete
  3. how about the layout? what i need to do?

    ReplyDelete
  4. Shit doesn't work.

    ReplyDelete
  5. thanks a lot.. this was a perfect solution for me

    ReplyDelete
  6. Great information you provided.Thank you for sharing
    If you are looking for data science training please visit our website
    Data science training in btm layout

    ReplyDelete