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.

13 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
  7. This is a really smart solution for the ViewPager content wrapping issue! I've struggled with this problem before and your approach with custom ViewPager and measuring children is elegant. Android development has so many of these tricky UI challenges that require creative solutions. The same kind of problem-solving mindset applies to AI development, where you often need to find creative ways to handle complex interactions between components. For developers expanding into AI, understanding these foundational problem-solving skills is essential. I've been looking into Agentic AI weekend classes in Electronic City to balance my learning with work commitments. Weekend classes are perfect for working professionals.

    ReplyDelete