从源码角度解析 - ScrollView嵌套ViewPager不显示的问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hzw2017/article/details/82391795
<ScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
            <TextView
                android:id="@+id/tv_header"
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:gravity="center"
                android:text="Header"/>

            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabBackground="@android:color/white"
                app:tabIndicatorColor="@color/colorPrimary"
                app:tabIndicatorHeight="1dp"
                app:tabMode="fixed"
                app:tabSelectedTextColor="@color/colorPrimary"
                app:tabTextColor="@android:color/black"/>

            <ViewPager
                android:id="@+id/view_pager"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

        </LinearLayout>

    </ScrollView>

以上布局的方式(ScrollView嵌套ViewPager),在默认情况下是达不到我们想要的效果,整个ViewPager是无法显示的,网上已经有很多解决方案,但很少有文章解释为什么要这样修改,是什么原因造成ViewPager显示不了,现在我们从源码的角度来分析问题的所在。
既然是无法显示,那可能是在ViewPager测量过程中出现了异常,可以先从源码看下ViewPager在onMeasure方法是如何构成的

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // For simple implementation, our internal size is always 0.
        // We depend on the container to specify the layout size of
        // our view.  We can't really know what it is since we will be
        // adding and removing different arbitrary views and do not
        // want the layout to change as this happens.
        setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
                getDefaultSize(0, heightMeasureSpec));
      ……………………
      省略
}

在onMeasure方法内中通过setMeasuredDimension方法设置测量的宽高,而View的测量具体值,是在getDefaultSize方法中得到的,接下来看看源码

public static int getDefaultSize(int size, int measureSpec) {
        int result = size;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
        }
        return result;
    }

在onMeasure方法中,getDefaultSize传入两个参数,一个大小size,另外一个测量规格measureSpec,而传入的size的值是为0,在getDefaultSize方法内,可以看出在UNSPECIFIED测量模式 下,getDefaultSize返回值是0,而这个返回值就是我们想要的宽或高。所以在此猜测是UNSPECIFIED测量模式而导致的,可能有人会问,我明明在布局中给ViewPager设置的match_parent属性,是一个精确测量模式EXACTLY,这么突然变成了UNSPECIFIED模式了。

我们知道ViewGroup的measure测量过程是一个递归过程,它会在父元素中的onMeasure方法中,遍历所有的子元素进行对子元素逐个measure测量,而父元素的测量规格MeasureSpec同时也会影响到子元素的测量规格MeasureSpec;我们可以从ScrollView的onMeasure源码可以看出


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (!mFillViewport) {
            return;
        }

        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightMode == MeasureSpec.UNSPECIFIED) {
            return;
        }
 ……省略
 }

我们进入super.onMeasure方法中,再去看看具体

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();

        final boolean measureMatchParentChildren =
                MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
                MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
        mMatchParentChildren.clear();

        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
              //这个方法很重要,是用测量子view的大小
               measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);

                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                maxWidth = Math.max(maxWidth,
                        child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
                maxHeight = Math.max(maxHeight,
                        child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
                childState = combineMeasuredStates(childState, child.getMeasuredState());
                if (measureMatchParentChildren) {
                    if (lp.width == LayoutParams.MATCH_PARENT ||
                            lp.height == LayoutParams.MATCH_PARENT) {
                        mMatchParentChildren.add(child);
                    }
                }
            }
        }
        ……省略
}

从上面的源码可以看出,ScrollView的onMeasure方法内通过for循环遍历子view,通过measureChildWithMargins方法来实现子View的测量工作,我们再点进measureChildWithMargins方法内看看细节

protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

从上面的代码可知,会根据父元素的parentWidthMeasureSpec、parentHeightMeasureSpec的测量规格,得到子元素的childWidthMeasureSpec 、childHeightMeasureSpec 测量规格,在其过程中并未改变子元素的测量模式,其实这时候我们看到measureChildWithMargins这个方法是ViewGroup的标准测量过程,而ScrollView已经对measureChildWithMargins方法进行重写了,接下来看看ScrollView的重写后的measureChildWithMargins方法

   @Override
    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                lp.topMargin + lp.bottomMargin, MeasureSpec.UNSPECIFIED);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

从源码可知,在构建子元素的高度测量规格childHeightMeasureSpec 时,已经把子元素的测量模式设置成了UNSPECIFIED模式了,由此可知,ViewPager的高度测量模式实际上是UNSPECIFIED,并非我们在布局上设置match_parent属性了,此时再去看getDefaultSize方法会很明了了,知道问题所在。

解决思路
给ViewPager的设置一个具体的高度值,有两种方式
1> 通过view.post(runnable)或者ViewTreeObserver方法中设置具体值

 this.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                StickHeadScrollView.this.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                nestedContent.getLayoutParams().height = StickHeadScrollView.this.getHeight() - headView.getHeight();
                nestedContent.requestLayout();

            }
        });

2> 重写ViewPager的onMeasure方法

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

        int childCount = getChildCount();
        int h=0;
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            //1.测量子View的宽高
            child.measure(widthMeasureSpec,MeasureSpec.makeMeasureSpec(0,MeasureSpec.UNSPECIFIED));
            //2.获取view的高度
            int measuredHeight = child.getMeasuredHeight();
            //3.取所有的子View中的高度最高的那个
            if (measuredHeight>h){
                h =measuredHeight;
            }

            Log.d(TAG, "onMeasure: "+measuredHeight);
        }
        //4、最后设置高度的测量模式为EXACTLY
        heightMeasureSpec= MeasureSpec.makeMeasureSpec(h,MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

子元素如果是match_parent属性,是无法得到子元素的高度值,如果想得到子元素的值,前提必须知道父元素的剩余空间是多少,而此时父元素的剩余空间我们是无法获取的,因为在父元素中onMeasure方法中,还在遍历测量子元素,子元素都还在测量中,是获取不到父元素的具体值的。

猜你喜欢

转载自blog.csdn.net/hzw2017/article/details/82391795
今日推荐