最近项目中需要Viewpager的高度能够自适应的动态改变,如果直接设置viewpager的高度为Android:layout_height="wrap_content",并不起作用,viewpager会铺满父布局,通过阅读viewpager的源码,发现创建一个viewpager的子类并重写onMeasure可实现这个需求,代码如下:
public class WrapContentHeightViewPager extends ViewPager {
public WrapContentHeightViewPager(Context context) {
super(context);
}
public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int childSize = getChildCount();
int maxHeight = 0;
for (int i = 0; i < childSize; i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
if (child.getMeasuredHeight() > maxHeight) {
maxHeight = child.getMeasuredHeight();
}
}
if (maxHeight > 0) {
setMeasuredDimension(getMeasuredWidth(), maxHeight);
}
}
}
思路很简单,遍历viewpager的每个childView,找出高度最大的那个childView的高度,并把这个高度设置为viewpager的高度。