从源码角度彻底分析 layout_weight 使用「建议收藏」

从源码角度彻底分析 layout_weight 使用「建议收藏」从源码角度彻底分析 layout_weight 使用

转载请注明出处:blog.csdn.net/zhaodai11?v…

layout_weight是线性布局特有的一个属性,这个属性可以按照比例设置控件的大小。线性布局中控件layout_weight默认值为0。
你想按照比例分配界面高度时:LinearLayout 的orientation属性设置为vertical,子控件高度建议0dp
这里写图片描述

计算方式 View1高度: 1/(1+2)=1/3 View2 高度: 2/(1+2)=2/3
当时当你把高度设置为wrap_content或者match_parent时,会是什么样子呢?
当设置为wrap_content时:
这里写图片描述
看起来好像没有区别,好多人因此得出wrap_content和0dp的效果相同,但是这就说明wrap_content和0dp效果一样吗?这个放在最后面讲。
当设置为match_parent时:
这里写图片描述
当设置为match_parent时,两个控件的高度比正好和上面相反。
这就涉及到了在线性布局中LinearLayout在onMeasure方法中对layout_weight属性的处理。

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

其实横向和纵向的原理差不多,这里我们这分析纵向的measureVertical(widthMeasureSpec, heightMeasureSpec);方法。在代码中已经添加相关注释,这里就不多加说明了。

void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
        mTotalLength = 0;//所有子控件高度之和
        int maxWidth = 0;//子控件的最大宽度
        int childState = 0;子控件的测量状态
        int alternativeMaxWidth = 0; // 子控件中layout_weight<=0的View的最大宽度
        int weightedMaxWidth = 0;// 子控件中layout_weight>0的View的最大宽度
        boolean allFillParent = true;//所有子控件宽度是否全部为fillParent
        float totalWeight = 0;//子控件所有layout_weight之和

        final int count = getVirtualChildCount();//获取所有子控件的数量
        //获取宽度和高度的测量模式
        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        boolean matchWidth = false;
        boolean skippedMeasure = false;

        final int baselineChildIndex = mBaselineAlignedChildIndex; 
        final boolean useLargestChild = mUseLargestChild;

        int largestChildHeight = Integer.MIN_VALUE;

        // See how tall everyone is. Also remember max width.
        for (int i = 0; i < count; ++i) {
            final View child = getVirtualChildAt(i);//获取对应子控件

            if (child == null) {
                mTotalLength += measureNullChild(i);
                continue;
            }

            if (child.getVisibility() == View.GONE) {
               i += getChildrenSkipCount(child, i);
               continue;
            }

            if (hasDividerBeforeChildAt(i)) {
                mTotalLength += mDividerHeight;
            }

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

            totalWeight += lp.weight;
            //判断是否需要测量子控件
            if (heightMode == MeasureSpec.EXACTLY && lp.height == 0 && lp.weight > 0) {
                // Optimization: don't bother measuring children who are going to use
                // leftover space. These views will get measured again down below if
                // there is any leftover space.
                //如果LinearLayout测量规格为MeasureSpec.EXACTLY,说明,LinearLayout的高度已经确定,并不需要依赖于子控件的高度,并且子控件的高度为0,weight>0,说明子控件的高度,依赖于LinearLayout的剩余空间来计算的
                final int totalLength = mTotalLength;
                mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin);
                skippedMeasure = true;
            } else {
            //进入说明LinearLayout高度不确定,依赖于子控件高度
                int oldHeight = Integer.MIN_VALUE;
//当LinearLayout高度不确定,子控件高度为0,weight>0,会强制设置子控件的高度计算模式为WRAP_CONTENT来配合LinearLayout高度计算。
                if (lp.height == 0 && lp.weight > 0) {
                    // heightMode is either UNSPECIFIED or AT_MOST, and this
                    // child wanted to stretch to fill available space.
                    // Translate that to WRAP_CONTENT so that it does not end up
                    // with a height of 0
                    oldHeight = 0;
                    lp.height = LayoutParams.WRAP_CONTENT;
                }

                // Determine how big this child would like to be. If this or
                // previous children have given a weight, then we allow it to
                // use all available space (and we will shrink things later
                // if needed).
                measureChildBeforeLayout(
                       child, i, widthMeasureSpec, 0, heightMeasureSpec,
                       totalWeight == 0 ? mTotalLength : 0);

                if (oldHeight != Integer.MIN_VALUE) {
                // 测量完成之后,重新设置 LayoutParams.height
                   lp.height = oldHeight;
                }

                final int childHeight = child.getMeasuredHeight();
                //重新计算子控件高度之和
                final int totalLength = mTotalLength;
                mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +
                       lp.bottomMargin + getNextLocationOffset(child));

                if (useLargestChild) {
                //比较高度,设置最大子控件高度
                    largestChildHeight = Math.max(childHeight, largestChildHeight);
                }
            }

            /**
             * If applicable, compute the additional offset to the child's baseline
             * we'll need later when asked {@link #getBaseline}.
             */
            if ((baselineChildIndex >= 0) && (baselineChildIndex == i + 1)) {
               mBaselineChildTop = mTotalLength;
            }

            // if we are trying to use a child index for our baseline, the above
            // book keeping only works if there are no children above it with
            // weight.  fail fast to aid the developer.
            if (i < baselineChildIndex && lp.weight > 0) {
                throw new RuntimeException("A child of LinearLayout with index "
                        + "less than mBaselineAlignedChildIndex has weight > 0, which "
                        + "won't work.  Either remove the weight, or don't set "
                        + "mBaselineAlignedChildIndex.");
            }

            boolean matchWidthLocally = false;
            if (widthMode != MeasureSpec.EXACTLY && lp.width == LayoutParams.MATCH_PARENT) {
                // The width of the linear layout will scale, and at least one
                // child said it wanted to match our width. Set a flag
                // indicating that we need to remeasure at least that view when
                // we know our width. matchWidth = true;
                matchWidthLocally = true;
            }

            final int margin = lp.leftMargin + lp.rightMargin;
            final int measuredWidth = child.getMeasuredWidth() + margin;
            maxWidth = Math.max(maxWidth, measuredWidth);
            childState = combineMeasuredStates(childState, child.getMeasuredState());

            allFillParent = allFillParent && lp.width == LayoutParams.MATCH_PARENT;
            if (lp.weight > 0) {
                /*
                 * Widths of weighted Views are bogus if we end up
                 * remeasuring, so keep them separate.
                 */
                weightedMaxWidth = Math.max(weightedMaxWidth,
                        matchWidthLocally ? margin : measuredWidth);
            } else {
                alternativeMaxWidth = Math.max(alternativeMaxWidth,
                        matchWidthLocally ? margin : measuredWidth);
            }

            i += getChildrenSkipCount(child, i);
        }

        if (mTotalLength > 0 && hasDividerBeforeChildAt(count)) {
            mTotalLength += mDividerHeight;
        }
// 这里是处理useLargestChild相关操作
        if (useLargestChild &&
                (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED)) {
            mTotalLength = 0;

            for (int i = 0; i < count; ++i) {
                final View child = getVirtualChildAt(i);

                if (child == null) {
                    mTotalLength += measureNullChild(i);
                    continue;
                }

                if (child.getVisibility() == GONE) {
                    i += getChildrenSkipCount(child, i);
                    continue;
                }

                final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)
                        child.getLayoutParams();
                // Account for negative margins
                final int totalLength = mTotalLength;
                mTotalLength = Math.max(totalLength, totalLength + largestChildHeight +
                        lp.topMargin + lp.bottomMargin + getNextLocationOffset(child));
            }
        }

        // Add in our padding
        mTotalLength += mPaddingTop + mPaddingBottom;

        int heightSize = mTotalLength;

        // Check against our minimum height
        heightSize = Math.max(heightSize, getSuggestedMinimumHeight());

        // Reconcile our calculated size with the heightMeasureSpec
        int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0);
        heightSize = heightSizeAndState & MEASURED_SIZE_MASK;

        // Either expand children with weight to take up available space or
        // shrink them if they extend beyond our current bounds. If we skipped
        // measurement on any children, we need to measure them now.
        int delta = heightSize - mTotalLength;//计算剩余高度
        if (skippedMeasure || delta != 0 && totalWeight > 0.0f) {
        // 限定weight总和范围,假如我们给过weighSum范围,那么子控件的weight总和受此影响
            float weightSum = mWeightSum > 0.0f ? mWeightSum : totalWeight;

            mTotalLength = 0;

            for (int i = 0; i < count; ++i) {
                final View child = getVirtualChildAt(i);
                //判断如果子控件不可见 跳过
                if (child.getVisibility() == View.GONE) {
                    continue;
                }

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

                float childExtra = lp.weight;
                if (childExtra > 0) {
                    // Child said it could absorb extra space -- give him his share
                    // 计算 weight 属性分配的大小,可能为负值
                    int share = (int) (childExtra * delta / weightSum);
                    weightSum -= childExtra;
                    delta -= share;

                    final int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                            mPaddingLeft + mPaddingRight +
                                    lp.leftMargin + lp.rightMargin, lp.width);

                    // TODO: Use a field like lp.isMeasured to figure out if this
                    // child has been previously measured
                    //注意  子控件高度计算
                    if ((lp.height != 0) || (heightMode != MeasureSpec.EXACTLY)) {
                        // child was measured once already above...
                        // base new measurement on stored values
                        //子控件高度子控件真是高度为weight分配后的高度+本身高度
                        int childHeight = child.getMeasuredHeight() + share;
                        if (childHeight < 0) {
                            childHeight = 0;
                        }

                        child.measure(childWidthMeasureSpec,
                                MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY));
                    } else {
                        // child was skipped in the loop above.
                        // Measure for this first time here      
                        child.measure(childWidthMeasureSpec,
                                MeasureSpec.makeMeasureSpec(share > 0 ? share : 0,
                                        MeasureSpec.EXACTLY));
                    }

                    // Child may now not fit in vertical dimension. childState = combineMeasuredStates(childState, child.getMeasuredState()
                            & (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
                }

                final int margin =  lp.leftMargin + lp.rightMargin;
                final int measuredWidth = child.getMeasuredWidth() + margin;
                maxWidth = Math.max(maxWidth, measuredWidth);

                boolean matchWidthLocally = widthMode != MeasureSpec.EXACTLY &&
                        lp.width == LayoutParams.MATCH_PARENT;

                alternativeMaxWidth = Math.max(alternativeMaxWidth,
                        matchWidthLocally ? margin : measuredWidth);

                allFillParent = allFillParent && lp.width == LayoutParams.MATCH_PARENT;

                final int totalLength = mTotalLength;
                mTotalLength = Math.max(totalLength, totalLength + child.getMeasuredHeight() +
                        lp.topMargin + lp.bottomMargin + getNextLocationOffset(child));
            }

            // Add in our padding
            mTotalLength += mPaddingTop + mPaddingBottom;
            // TODO: Should we recompute the heightSpec based on the new total length?
        } else {
            alternativeMaxWidth = Math.max(alternativeMaxWidth,
                                           weightedMaxWidth);


            // We have no limit, so make all weighted views as tall as the largest child.
            // Children will have already been measured once.
            if (useLargestChild && heightMode != MeasureSpec.EXACTLY) {
                for (int i = 0; i < count; i++) {
                    final View child = getVirtualChildAt(i);

                    if (child == null || child.getVisibility() == View.GONE) {
                        continue;
                    }

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

                    float childExtra = lp.weight;
                    if (childExtra > 0) {
                        child.measure(
                                MeasureSpec.makeMeasureSpec(child.getMeasuredWidth(),
                                        MeasureSpec.EXACTLY),
                                MeasureSpec.makeMeasureSpec(largestChildHeight,
                                        MeasureSpec.EXACTLY));
                    }
                }
            }
        }

        if (!allFillParent && widthMode != MeasureSpec.EXACTLY) {
            maxWidth = alternativeMaxWidth;
        }

        maxWidth += mPaddingLeft + mPaddingRight;

        // Check against our minimum width
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                heightSizeAndState);

        if (matchWidth) {
            forceUniformWidth(count, heightMeasureSpec);
        }
    }

结论:
由上面的源码分析可以得出下面的公式:
当View layout_height!=0时

delta = heightSize - mTotalLength;
 share = (int) (childExtra * delta / weightSum);
 height = share+child.getMeasuredHeight()
 剩余空间高度 = LinearLayout高度-所有子控件高度之和
 子控件真实高度 = (子控件所占比例)*(剩余空间高度)/总比例 + 子控件原本高度

当View layout_height=0时

delta = heightSize - mTotalLength;
 share = (int) (childExtra * delta / weightSum);
 height = share>0?share:0
 剩余空间高度 = LinearLayout高度-所有子控件高度之和
 子控件按比例分配的高度 share = (子控件所占比例)*(剩余空间高度)/总比例
 子控件真实高度 h = 当share>0时 为share 当share

所以当上面两个子控件高度为match_parent时,

假设 LinearLayout 高度为H  
剩余空间 delta = H-(H+H)=-H

h1 = 1*(-H)/(1+2)+H=2/3*H
h2 = 2*(-H)/(1+2)+H = 1/3*H

h1/h2 = 2/1

其实通过上面两个公式,我们也能理解当为wrap_content时为什么看起来效果和为0时一样,但其实不一样。主要是因为View高度不为0时,View本身的高度也会影响最终高度的计算。
下面我们来验证一下:
图1
0dp时

图2
为wrap_content时
通过上面TextView1设置padding =100dp在wrap_content时会对View本身高度测量产生影响,和mTotalLength的计算产生影响


//mTotalLength计算

final int childHeight = child.getMeasuredHeight()
final int totalLength = mTotalLength
mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +lp.bottomMargin + getNextLocationOffset(child))

View最终高度计算 相关代码

 int childHeight = child.getMeasuredHeight() + share
                        if (childHeight < 0) {
                            childHeight = 0
                        }

child.measure(childWidthMeasureSpec,
                                MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY))

此外例如TextView字体大小等会影响高度的属性,也会导致wrap_content和0dp结果不一样。

所以如果你想正常使用layout_weight属性的话,最好将对应的layout_width或者layout_height设置为0dp。这样是不会出现任何偏差的。如果你想有特殊的运用,建议将上面的源码读懂,注意各种细节。

最后在举一个有意思的例子:
View
上面这个为android:layout_height="wrap_content"时比例和正常相反了。

大家可以思考一下再看答案。

原因在View的源码中:
View的onMeasure方法:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

//注意在这个里面MeasureSpec.AT_MOST MeasureSpec.EXACTLY处理方式是一样的,所以wrap_content 按照match_partent的方式处理了。
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;
    }
    }

有错误的地方欢迎反馈,大家一起进步。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/13339.html

(0)

相关推荐

  • Python中的无穷大

    Python中的无穷大随着计算机科学的不断进步,越来越多的应用程序需要处理非常大或者非常小的数字。Python作为一种强大的编程语言,在数字计算方面具有丰富的类型和功能。其中一种非常重要的类型就是无穷大。

    2024-05-09
    64
  • 利用while实现Python程序的循环执行

    利用while实现Python程序的循环执行使用Python语言编写程序时,经常需要让程序反复执行一段指令集,这个时候就需要使用循环结构。while循环结构是Python语言中用来实现循环执行的一种结构。

    2024-03-05
    80
  • Python数据类型及其应用场景

    Python数据类型及其应用场景Python是一种高级编程语言,流行于众多领域,如Web开发、数据科学、人工智能等,而数据类型是Python语言中的基础。Python提供了多种数据类型,包括数值型、字符串型、列表、元组、字典、集合等,每一种类型都有其特定的应用场景。

    2024-02-22
    109
  • 数据库备份与恢复命令_索引和视图的基本功能

    数据库备份与恢复命令_索引和视图的基本功能备份和恢复命令 备份库 直接在cmd窗口中直接输入,结束不需要输入; mysqldump -h端口号 -u用户名 -p密码 数据库名>备份地址 恢复库 在cmd窗口中进行 1、连接数据库 mys

    2023-05-26
    154
  • MySQL数据库性能优化[亲测有效]

    MySQL数据库性能优化[亲测有效]前言 由于部分企业要求本地部署系统(使用企业服务器进行部署系统且数据库也部署在同台服务器),本地部署系统的服务器往往达不到我们的云部署服务器,速度性能更是有所欠缺,特别是在查询统计报表的时候,云上几秒

    2023-05-16
    158
  • PCB制板流程及工艺

    PCB制板流程及工艺文章浏览阅读1.4k次,点赞2次,收藏4次。沉锡工艺是将整个PCB板浸入含有熔融锡的溶液中,使得整个PCB板表面都被覆盖上一层薄薄的锡层,从而达到保护电路、增加焊接能力的效果。蚀刻工艺是制作PCB板时的一项关键工艺,该工艺利用蚀刻液将没有被

    2023-11-07
    138
  • Python实现字符串比较

    Python实现字符串比较在日常开发中,字符串比较是一个很常见的操作。Python内置了很多用于字符串比较的方法和函数,本文将从多个方面对Python实现字符串比较做详细的阐述。

    2024-06-03
    49
  • ORM分组操作示例(与SQL语句的比较)[通俗易懂]

    ORM分组操作示例(与SQL语句的比较)[通俗易懂]
    class Employee(models.Model): name = models.CharField(max_length=16) age = mod…

    2023-04-05
    167

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注