ScrollView嵌套ViewPager嵌套ListView三者共存&冲突解决方案

在实际开发中,经常会需要需要在ScrollView下,嵌套一个ViewPager,整体可以上下滑动。ViewPager中是一些Fragment,可以进行左右滑动切换。Fragment中嵌套ListView,实现数据的列表显示,同理也是随着整个ScrollView上下滑动。效果图如下:

QQ图片20160111095955 QQ图片20160111100401

 

 

首先要解决的就是scrollview下viewpager大小自适应的问题

最有效的方法肯定是 自定义一个viewpager并重写它的onMeasure方法

相关注释如下,如果有不对的请指正

`
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    //如果 ViewPager 的上层是 ScrollView
    //按照viewpager的高度,决定父元素scrollview的高度
    if(viewInScrollView) {
        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);
    }

    //如果 ViewPager 的下层有 ListView
    //遍历所有子View,设置每个子View的大小,并找出高度最大的listview,设置为父元素viewpager的高度
    if(viewWithListView) {
        int maxHeight = 0;
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            if (child.getMeasuredHeight() > maxHeight) {
                maxHeight = child.getMeasuredHeight();
            }
        }

        if (maxHeight > 0) {
            setMeasuredDimension(getMeasuredWidth(), maxHeight);
        }
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

`

代码中用到了两个变量

private boolean viewInScrollView = false; private boolean viewWithListView = false;

默认为false,根据需要去set它们就好了

0%