3

I have a viewpager (in a CardView) that swipes between 4 different items. These pages are relatively the same layout and close in height (same width) however there are instances where one child has extra lines of text which bumps the cardview size noticeably bigger or smaller when swiping the viewpager.

I have a snippet of code I am using that makes sense from my understanding, it looks through the viewpager's children and measures their heights, saving the biggest one. Then it returns that max height and sets it for the viewpager. In my usage, pages 1,2,3 are working as intended (different amount of text content but show all the same height correctly) but page 4 reverts to its smaller size and returns different measurements for the child measuring steps. Any idea why that is?

public class WrapContentViewPager extends ViewPager {
public WrapContentViewPager(Context context) {
    super(context);
}

public WrapContentViewPager(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onMeasure(int widthMeasureSpec, int 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;
    }

    if (height != 0) {
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}

Thanks!

Steven
  • 95
  • 7

0 Answers0