两个问题
1.在使用ViewPager组件设置高度为wrap_content布局时,会出现View不显示的问题;
2.在使用WrapContentViewPager时,pager的子页面高度一致,导致页面内容少的view出现空白;
解决第一个问题,直接下载WrapContentViewPager到项目中使用即可。但是会出现第二个问题;原因是,在WrapContentViewPager中复写OnMeasure方法,使用的高度是子页面中最大的高度,所以页面内容少的view会出现空白
解决第二个问题,动态改变pager的高度即可
/**
* ViewPager DynamicHeight解决方案
*/
public class DynamicHeightViewPager extends ViewPager {
/**
* Constructor
*
* @param context the context
*/
public DynamicHeightViewPager(Context context) {
super(context);
}
/**
* Constructor
*
* @param context the context
* @param attrs the attribute set
*/
public DynamicHeightViewPager(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));
// }
/**
* 解决pager中视图高度不一致的情况 动态更改pager高度
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
@Override
protected void onMeasure(final int widthMeasureSpec, int heightMeasureSpec) {
int index = getCurrentItem();
int height = 0;
View v = getChildAt(index);
if (v != null) {
v.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
height = v.getMeasuredHeight();
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height + 80, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
final ViewPager pager = this;
pager.addOnPageChangeListener(new SimpleOnPageChangeListener() {
private int position;
private int oldPositon;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
this.position = position;
}
@Override
public void onPageScrollStateChanged(int state) {
if (state == 2) {
requestLayout();
}
}
});
}
}