ViewPager和ScrollView之间的冲突

本文主要是在做项目中遇到scrollView需要嵌套ViewPager,需要解决Viewpage能够随着自身子空间高度自适应高度。参考网上例子许多会有因为viewpager有预加载功能,有些时候显示的高度不是当前fragment的高度。所以要实现自适应高度需要解决ViewPager的测量时间,确保当前fragment显示的时候能够正确的测量大小然后绘制当前页面的大小。
1 具体逻辑代码如下:
/**
 * Created by Administrator on 2017/11/21.
 *
 * @author liu
 *         scrollView嵌套viewpager
 *         viewpager高度自适应
 */

public class ViewPagerForScrollView extends ViewPager {
    private String Tag = "ViewPagerForScrollView";

    public ViewPagerForScrollView(Context context) {
        super(context);
    }

    public ViewPagerForScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                requestLayout();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height = 0;
        if (getAdapter() != null) {
            LogUtils.v(Tag,"getAdapter:不为空");
            int index = getCurrentItem();
            height = 0;
            View v = ((Fragment) getAdapter().instantiateItem(this, index)).getView();
            if (v != null) {
                v.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                height = v.getMeasuredHeight();
            }
        } else {
            LogUtils.v(Tag,"getAdapter:为空");
            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);
    }


}
因为代码编写有点久远逻辑有些遗忘后边补充,先做记录方便后边遇到再次使用。

你可能感兴趣的:(ViewPager和ScrollView之间的冲突)