时常用到ScrollView中嵌套ViewPager,但即使ScrollView的layout_width和layout_height都设置为match_parent,同时android:fillViewport属性也设置为true了,但ViewPager中依然空白,数据无法显示的问题。这里记录常用的方法(即重写ViewPager的onMeasure方法),以备查阅。
public class MeasuredViewPager extends ViewPager { public MeasuredViewPager(@NonNull Context context) { super(context); } public MeasuredViewPager(@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 childHeight = child.getMeasuredHeight(); if (childHeight > height) { height = childHeight; } } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } }