-
在ViewPager中有Fragment,ViewPager的layout_height设置为wrap_content。如果Fragment中垂直排列三个模块,其中一个模块需要隐藏,代码设置隐藏后,Fragment的高度数值就会变小,此时底部会留出空白。
-
也就是说虽然ViewPager高度设置了wrap_content,并没有自适应高度,还需要重写onMeasure(),不多BB了,上代码。
public class CannotScrollViewPager extends ViewPager {
public CannotScrollViewPager(@NonNull Context context) {
this(context, null);
}
public CannotScrollViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = 0;
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = child.getMeasuredHeight();
if (h > height)
height = h;
}
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
-
其中的原理还没有深究,MeasureSpec.makeMeasureSpec()函数说明后续补上。