【ViewPager2避坑系列】瞬间暴增数个Fragment

前言

最近我在关注ViewPager2的使用,期间一直基于官方的Demo调试android-viewpager2,今天遇到一个奇葩的问题,捉摸了半天最终找到缘由,原来是Demo中布局的问题,过后感受有必要分享一下这个过程,一来能够巩固View测量的知识,二来但愿你们能避开这个坑;android

阅读指南git

入坑现场

为了观察Fragment的生命周期,我事先在CardFragment类中,对生命周期方法进行埋点Log;github

异常发生的操做步骤:bash

横屏进入CardFragmentActivity或者CardFragmentActivity竖屏切到横屏,控制台瞬间打印多个Fragment的生命周期Log,场面让人惊呆;ide

CardFragmentActivity横屏下布局布局

控制台Log输出ui

因为Log太长,一屏根本截不完,反正就是不少个Fragment经历了onCreate->onDestory的全部过程;google

操做前,只有Fragment2建立并显示,理论上旋转屏幕以后,只有Fragment2销毁并重建,不会调用其余Fragment;如今问题发生在了,旋转以后有一堆Fragment建立而且销毁,最终保留的也只有Fragment2,这确定是个Bug,虽然发生在一行代码都没有改的官方Demo上;spa

初步缘由MATCH_PARENT计算失效

ViewPager2目前只支持ItemView的布局参数是MATCH_PARENT,就是填充父布局的效果;因为ViewPager2是基于RecyclerView,理论上每一个ItemView必定会是MATCH_PARENT,控制一屏只加载一个Item,可是一旦MATCH_PARENT计算失效,那么ViewPager2基本上就是RecyclerView的效果,瞬间多个Fragment是能够解释通的;调试

ViewPager2测量流程

ViewPager2

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    //测量mRecyclerView
    measureChild(mRecyclerView, widthMeasureSpec, heightMeasureSpec);
    int width = mRecyclerView.getMeasuredWidth();
    int height = mRecyclerView.getMeasuredHeight();
    int childState = mRecyclerView.getMeasuredState();
    //宽高计算
    width += getPaddingLeft() + getPaddingRight();
    height += getPaddingTop() + getPaddingBottom();
    //宽高约束
    width = Math.max(width, getSuggestedMinimumWidth());
    height = Math.max(height, getSuggestedMinimumHeight());
    //设置自身高度
    setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, childState),
            resolveSizeAndState(height, heightMeasureSpec,
                    childState << MEASURED_HEIGHT_STATE_SHIFT));
}
复制代码

ViewPager2.onMeasure()优先计算mRecyclerView的尺寸,因此关注的重点转移到RecyclerView.onMeasure()上,RecyclerView子View的计算和布局逻辑在LayoutManager中,因此本例子重要看LinearLayoutManager,LayoutManager对子View计算的方法是measureChildWithMargins(),下面看一下measureChildWithMargins()方法的调用栈;

主要分析measureChildWithMargins()代码:

RecyclerView.LayoutManager

public void measureChildWithMargins(@NonNull View child, int widthUsed, int heightUsed) {
    final LayoutParams lp = (LayoutParams) child.getLayoutParams();
    //获取当前View的Decor(传统理解的分割线)尺寸
    final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
    widthUsed += insets.left + insets.right;
    heightUsed += insets.top + insets.bottom;
    //获取宽测量信息
    final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(),
            getPaddingLeft() + getPaddingRight()
                    + lp.leftMargin + lp.rightMargin + widthUsed, lp.width,
            canScrollHorizontally());
    //获取高测量信息
    final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(),
            getPaddingTop() + getPaddingBottom()
                    + lp.topMargin + lp.bottomMargin + heightUsed, lp.height,
           canScrollVertically());
    //若是须要测量,调用child的测量方法
    if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) {
        child.measure(widthSpec, heightSpec);
    }
}
复制代码

获取宽高测量信息的代码:

public static int getChildMeasureSpec(int parentSize, int parentMode, int padding,
        int childDimension, boolean canScroll) {
    int size = Math.max(0, parentSize - padding);
    int resultSize = 0;
    int resultMode = 0;
    if (canScroll) {
        if (childDimension >= 0) {
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
            switch (parentMode) {
                case MeasureSpec.AT_MOST:
                case MeasureSpec.EXACTLY:
                    resultSize = size;
                    resultMode = parentMode;
                    break;
                case MeasureSpec.UNSPECIFIED:
                    resultSize = 0;
                    resultMode = MeasureSpec.UNSPECIFIED;
                    break;
            }
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
            resultSize = 0;
            resultMode = MeasureSpec.UNSPECIFIED;
        }
    } else {
       //省略
    }
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
复制代码

分析getChildMeasureSpec()方法,因为ViewPager2强制设置MATCH_PARENT,因此childDimension确定是MATCH_PARENT,那么resultMode是什么呢,经过断点打印输出,这里的parentModeMeasureSpec.UNSPECIFIEDMeasureSpec.EXACTLY交替出现;

刚开始一直在关注子View计算流程,发现MeasureSpecMode异常,老是出现MeasureSpec.UNSPECIFIEDMeasureSpec.EXACTLY交替,最后直接打印RecyclerViewonMeasure输出;

RecyclerView.onMeasure输出日志

在竖屏时,widthMeasureMode一直都是1073741824(MATCH_PARENT),可是横屏状态下,widthMeasureMode在0(UNSPECIFIED)和MATCH_PARENT中徘徊;对比差异就是MeasureMode = UNSPECIFIED,因此问题应该出在MeasureMode = UNSPECIFIED上;

如何产生的UNSPECIFIED

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:background="#FFFFFF">
    <include layout="@layout/controls" />
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/view_pager"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1" />

</LinearLayout>
复制代码

总体布局是LinearLayout,在布局里面,ViewPager2 layout_width="0dp" layout_weight="1",多是width=0dp && weight=1形成,扒一扒LinearLayout测量代码逻辑;

LinearLayout

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (mOrientation == VERTICAL) {
        measureVertical(widthMeasureSpec, heightMeasureSpec);
    } else {
        measureHorizontal(widthMeasureSpec, heightMeasureSpec);
    }
}
复制代码

LinearLayoutonMeasure()方法分为竖直方向和水平方向,咱们这里选择measureHorizontal()入手;

measureHorizontal()方法中经过判断lp.width == 0 && lp.weight > 0判定是否须要过渡加载useExcessSpace,下面的过渡加载就是采用UNSPECIFIED方式测量;

为什么还要执行一次MATCH_PARENT测量

这是因为LinearLayoutmeasureHorizontal()针对过渡加载useExcessSpace的布局,会进行两次测量,第二次就会传递实际的测量模式;

为什么UNSPECIFIED模式下,MATCH_PARENT会失效

咱们暂时只讨论FrameLayout的状况,若是FrameLayout的父布局给该FrameLayout的测量模式是UNSPECIFIED,尺寸是自身的具体宽高,并且该FrameLayoutLayoutParamsMATCH_PARENT,试问FrameLayout能测量出准确的MATCH_PARENT尺寸吗?

FrameLayout

FrameLayout会测量全部可见View的尺寸,而后算出最大的尺寸maxWidthmaxHeight,自身尺寸的测量调用setMeasuredDimension()方法,每一个Dimension的设置调用resolveSizeAndState(maxWidth, widthMeasureSpec, childState)方法;

resolveSizeAndState()

public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
    //来自父布局建议的模式和尺寸
    final int specMode = MeasureSpec.getMode(measureSpec);
    final int specSize = MeasureSpec.getSize(measureSpec);
    final int result;
    switch (specMode) {//父布局建议的模式
        case MeasureSpec.AT_MOST:
            if (specSize < size) {
                result = specSize | MEASURED_STATE_TOO_SMALL;
            } else {
                result = size;
            }
            break;
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
        case MeasureSpec.UNSPECIFIED://在这里
        default:
            result = size;//这个size就是传入的size
    }
    return result | (childMeasuredState & MEASURED_STATE_MASK);
}
复制代码

分析resolveSizeAndState(),若是measureSpecspecMode=UNSPECIFIED,结果返回传入的size,在FrameLayout中是maxWidthmaxHeight,而并非parent给予的specSize;

为什么总体会测量两遍

这是因为FrameLayout针对MATCH_PARENT的布局,会进行二次测量,第一次测量为了找到最大尺寸maxsize,二次测量把用maxsize重新计算MATCH_PARENT的子View;

避免入坑

上诉讲解就是为了说明,UNSPECIFIED会影响MATCH_PARENT的测量,至少在FrameLayout上是影响的,FrameLayout会采起子View的最大尺寸,一旦失去MATCH_PARENT的意义,ViewPager2就失去了ItemView一屏显示一个的特性,因此会出现开头说的瞬间暴增多个Fragment现象;

因为ViewPager2配合Fragment使用时,根布局是FrameLayout这个没法改变,解决办法就是不容许出现跟滑动方向相同的维度测量上,出现UNSPECIFIED;

若是父布局是LinearLayout,横向滑动时要避免layout_width="0dp"和layout_weight="1",纵向滑动时要避免layout_height="0dp"和layout_weight="1",代码的解决方案很简单,去掉layout_weight="1",吧layout_width设置成match_parent;

总结

注意ViewPager2配合Fragment使用时,一旦发现Fragment瞬间暴增的状况,多是Item尺寸测量的不对,形成这个缘由要优先想到UNSPECIFIED,·若是用的LinearLayout多是layout_weight="1"的缘由,同理,RecyclerView+PagerSnapHelper+match_parent实现一屏一个Item的方案,也存在这个风险;

相关文章
相关标签/搜索