第一種ide
public class MyViewPager extends ViewPager {
public MyViewPager(@NonNull Context context) {
super(context);
}.net
public MyViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {blog
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;
}get
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);it
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
弊端:每一個viewpager高度同樣,致使有的畫面會有大空白io
第二種class
public class CustomViewpager extends ViewPager {List
public CustomViewpager(Context context) {
super(context);
}select
public CustomViewpager(Context context, AttributeSet attrs) {
super(context, attrs);
}float
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int viewHeight = 0;
View childView = getChildAt(getCurrentItem());
if (childView != null) {
childView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
viewHeight = childView.getMeasuredHeight();
heightMeasureSpec = MeasureSpec.makeMeasureSpec(viewHeight, MeasureSpec.EXACTLY);
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
在viewpager中
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
selectionViewPager(position);
View view = viewPager.getChildAt(position);
int height = view.getMeasuredHeight();
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) viewPager.getLayoutParams();
layoutParams.height = height;
viewPager.setLayoutParams(layoutParams);
}
@Override
public void onPageScrollStateChanged(int state) {
} }); ———————————————— 版權聲明:本文爲CSDN博主「小小夜雨」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連接及本聲明。 原文連接:https://blog.csdn.net/qq_30711091/article/details/86537593