-
-
Save blackmann/d2bf9af0640b0b10c6f371e047469540 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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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