Last active
July 24, 2017 05:30
-
-
Save samuel22gj/a1c6181913ef945c75f450f2889ec7a6 to your computer and use it in GitHub Desktop.
A ViewPager support height is WRAP_CONTENT
This file contains hidden or 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
/** | |
* A ViewPager support height is {@code WRAP_CONTENT}. | |
*/ | |
public class WrapContentViewPager extends ViewPager { | |
public WrapContentViewPager(Context context) { | |
super(context, null); | |
} | |
public WrapContentViewPager(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
@Override | |
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { | |
super.onMeasure(widthMeasureSpec, heightMeasureSpec); | |
int mode = MeasureSpec.getMode(heightMeasureSpec); | |
int size = MeasureSpec.getSize(heightMeasureSpec); | |
if (mode == MeasureSpec.UNSPECIFIED || mode == MeasureSpec.AT_MOST) { | |
int maxChildHeight = 0; | |
for (int i = 0; i < getChildCount(); i++) { | |
View child = getChildAt(i); | |
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); | |
int childHeight = child.getMeasuredHeight(); | |
if (childHeight > maxChildHeight) { | |
maxChildHeight = childHeight; | |
} | |
} | |
// The target height must equal or smaller than the height which from parent given. | |
// Otherwise, viewpager will can't scroll to end. | |
int targetHeight = Math.min(size, maxChildHeight); | |
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), targetHeight); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment