Skip to content

Instantly share code, notes, and snippets.

@neilbantoc
Created February 5, 2014 10:38
Show Gist options
  • Save neilbantoc/8820948 to your computer and use it in GitHub Desktop.
Save neilbantoc/8820948 to your computer and use it in GitHub Desktop.
A simple view pager that supports wrapping of content by measuring first child and setting that as the viewpager's height.
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
/*
* A simple view pager that supports wrapping of content
* by measuring first child and setting that as the viewpager's height.
*/
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) {
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));
}
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment