记一次CoordinatorLayout 动态 addView() 不显示

问题描述:

页面显示出来之后,调用 addView() 方法添加子 view,界面并没有显示出相应的子 view,而后再次 removeView,再 addView,子 view 得以正确显示出来。

出现的原因:

通过捕捉 view 查看布局,发现新添加的 view 的宽高均为 0,所以可以初步判断是measure 子 view 的时候出了什么意外。

首先我们定位到 CoordinatorLayout的 measure 位置。

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
     ...省略部分代码

        final boolean applyInsets = mLastInsets != null && ViewCompat.getFitsSystemWindows(this);

        final int childCount = mDependencySortedChildren.size();
        for (int i = 0; i < childCount; i++) {
            final View child = mDependencySortedChildren.get(i);
            if (child.getVisibility() == GONE) {
                // If the child is GONE, skip...
                continue;
            }

            final LayoutParams lp = (LayoutParams) child.getLayoutParams();

            int keylineWidthUsed = 0;
            if (lp.keyline >= 0 && widthMode != MeasureSpec.UNSPECIFIED) {
                final int keylinePos = getKeyline(lp.keyline);
                final int keylineGravity = GravityCompat.getAbsoluteGravity(
                        resolveKeylineGravity(lp.gravity), layoutDirection)
                        & Gravity.HORIZONTAL_GRAVITY_MASK;
                if ((keylineGravity == Gravity.LEFT && !isRtl)
                        || (keylineGravity == Gravity.RIGHT && isRtl)) {
                    keylineWidthUsed = Math.max(0, widthSize - paddingRight - keylinePos);
                } else if ((keylineGravity == Gravity.RIGHT && !isRtl)
                        || (keylineGravity == Gravity.LEFT && isRtl)) {
                    keylineWidthUsed = Math.max(0, keylinePos - paddingLeft);
                }
            }

            int childWidthMeasureSpec = widthMeasureSpec;
            int childHeightMeasureSpec = heightMeasureSpec;
            // 是否应用 fitSystemWindows属性
            if (applyInsets && !ViewCompat.getFitsSystemWindows(child)) {
                // We're set to handle insets but this child isn't, so we will measure the
                // child as if there are no insets
                final int horizInsets = mLastInsets.getSystemWindowInsetLeft()
                        + mLastInsets.getSystemWindowInsetRight();
                final int vertInsets = mLastInsets.getSystemWindowInsetTop()
                        + mLastInsets.getSystemWindowInsetBottom();

                childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                        widthSize - horizInsets, widthMode);
                childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                        heightSize - vertInsets, heightMode);
            }

            final Behavior b = lp.getBehavior();
            // 如果 b 不为空,则调用 b 中的 measure 子 view 方法。
            if (b == null || !b.onMeasureChild(this, child, childWidthMeasureSpec, keylineWidthUsed,
                    childHeightMeasureSpec, 0)) {
                // 测量子 view
                onMeasureChild(child, childWidthMeasureSpec, keylineWidthUsed,
                        childHeightMeasureSpec, 0);
            }

            widthUsed = Math.max(widthUsed, widthPadding + child.getMeasuredWidth() +
                    lp.leftMargin + lp.rightMargin);

            heightUsed = Math.max(heightUsed, heightPadding + child.getMeasuredHeight() +
                    lp.topMargin + lp.bottomMargin);
            childState = View.combineMeasuredStates(childState, child.getMeasuredState());
        }

        final int width = View.resolveSizeAndState(widthUsed, widthMeasureSpec,
                childState & View.MEASURED_STATE_MASK);
        final int height = View.resolveSizeAndState(heightUsed, heightMeasureSpec,
                childState << View.MEASURED_HEIGHT_STATE_SHIFT);
        setMeasuredDimension(width, height);
    }

从上面的代码其实可以看到,fitSystemWindows 这个属性有着举重若轻的作用。所以就怀疑会不会是fitSystemWindows这个属性导致测量出了问题呢?所以进行了一系列的实验。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <android.support.design.widget.CoordinatorLayout
            android:id="@+id/coordinator"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:addStatesFromChildren="true"
            android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout
                android:layout_width="match_parent"
                android:layout_height="150dp"
                android:fitsSystemWindows="true"
                android:orientation="vertical"
                app:elevation="0dp">
            <android.support.design.widget.CollapsingToolbarLayout
                    android:id="@+id/collapsingToolbarLayout"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    app:contentScrim="@color/colorPrimary"
                    app:layout_scrollFlags="scroll|exitUntilCollapsed">
                <android.support.v7.widget.Toolbar
                        android:id="@+id/toolbar"
                        android:layout_width="match_parent"
                        android:layout_height="50dp"
                        app:layout_collapseMode="pin"
                        android:minHeight="10dp"
                        android:background="@color/colorPrimary"/>
            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>
        <RelativeLayout
                android:id="@+id/content_rl"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/colorPrimaryDark"
                app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <TextView
                    android:text="big"
                    android:gravity="center"
                    android:layout_width="match_parent" android:layout_height="match_parent"/>


        </RelativeLayout>


    </android.support.design.widget.CoordinatorLayout>

    <LinearLayout android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:orientation="horizontal">

        <TextView
                android:background="@color/colorAccent"
                android:text="change"
                android:layout_weight="1"
                android:gravity="center"
                android:id="@+id/text_add"
                android:layout_width="0dp"
                android:layout_height="100dp"/>
        <TextView
                android:background="@color/colorAccent"
                android:text="remove"
                android:layout_weight="1"
                android:gravity="center"
                android:id="@+id/text_remove"
                android:layout_width="0dp"
                android:layout_height="100dp"/>
    </LinearLayout>


</LinearLayout>

上面是我的布局文件,可以看到我在 CoordinatorLayout 和 AppBarLayout 都添加了 fitSystemWindows 属性,这样替换 RelativeLayout 这一 part 的时候,即先 remove 掉 RelativeLayout 这 part,然后再添加入自己的子 view,然后,第一次 addView 的时候,显示是不正常的,然后 remove 掉子 view,再次添加子 view,却可以正常显示了。这显然是有问题,所以还需要一个一个控制fitSystemWindows来排除。

1、去掉 CoordinatorLayout 的 fitSystemWindows 属性

运行发现,毫无帮助,failed。

2、去掉 AppBarLayout 的 fitSystemWindows 属性

运行发现,首次添加也能成功,反复调试,确实可以正常显示。

所以,基本可以确定 AppBarLayout 的 fitSystemWindows 属性值会影响着 CoordinatorLayout 子view 的测量。

我们接着看源码,有这么一段

final Behavior b = lp.getBehavior();

if (b == null || !b.onMeasureChild(this, child, childWidthMeasureSpec, keylineWidthUsed,
                    childHeightMeasureSpec, 0)) {
                // 测量子 view
                onMeasureChild(child, childWidthMeasureSpec, keylineWidthUsed,
                        childHeightMeasureSpec, 0);
            }

如果 behavior 为 null 则直接测量子view,behavior 不为空,则调用 behavior 的 onMeasureChild 方法。断点调试确认首次 addView 的时候进入了实现类
HeaderScrollingViewBehavior 的该方法,跟进去看看有啥乾坤。

public boolean onMeasureChild(CoordinatorLayout parent, View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) {
        int childLpHeight = child.getLayoutParams().height;
        if (childLpHeight == -1 || childLpHeight == -2) {
            List<View> dependencies = parent.getDependencies(child);
            // 这里的 header 其实就是 AppBarLayout
            View header = this.findFirstDependency(dependencies);
            if (header != null) {
                // 如果 header 设置了 fsw 属性而当前子 view 未设置 fsw 属性
                if (ViewCompat.getFitsSystemWindows(header) && !ViewCompat.getFitsSystemWindows(child)) {
                    // 给当前子view 设置 fsw 属性
                    ViewCompat.setFitsSystemWindows(child, true);
                    if (ViewCompat.getFitsSystemWindows(child)) {
                        child.requestLayout();
                        // 直接就返回了
                        return true;
                    }
                }

                int availableHeight = MeasureSpec.getSize(parentHeightMeasureSpec);
                if (availableHeight == 0) {
                    availableHeight = parent.getHeight();
                }

                int height = availableHeight - header.getMeasuredHeight() + this.getScrollRange(header);
                int heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, childLpHeight == -1 ? 1073741824 : -2147483648);
                parent.onMeasureChild(child, parentWidthMeasureSpec, widthUsed, heightMeasureSpec, heightUsed);
                return true;
            }
        }

        return false;
    }

所以 onMeasureChild 方法就是对 header 判断,并对未设置 fsw 属性的子view 设置上 fsw 属性,如果不需要设置,则直接测量并返回。

断点调试的过程中,可以清晰的看到,第一次 addView 的时候,由于该子view 并未设置 fsw 属性,所以,初次测量就出现了问题,而第二次的时候,因为已经具备了 fsw 属性,则能正确测量并正常显示。

解决办法:

当需要协同布局,并且存在动态替换 view 的情况时,需要考虑到 fsw 属性对测量的影响。
1、如果不需要 fsw 属性,可以直接去掉 header 的 fsw 属性,即本文例子的 AppBarLayout 的 fsw 属性。
2、如果需要 fsw 属性,那根据源码,我们其实可以提前给将要添加的子view 设置上 fsw 属性,这样,添加后就可以正确测量。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容