LayoutParams是如何作用的

        在看LayoutParams之前,得要先了解MeasureSpec这个类,view的最终测量就是基于这个类,对于view树来说,view的尺寸的解析也是基于这个类的:

 

public static class MeasureSpec {
    private static final int MODE_SHIFT = 30;
    private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
    /** @hide */
    @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
    @Retention(RetentionPolicy.SOURCE)
    public @interface MeasureSpecMode {}
    public static final int UNSPECIFIED = 0 << MODE_SHIFT;
    public static final int EXACTLY     = 1 << MODE_SHIFT;
    public static final int AT_MOST     = 2 << MODE_SHIFT;
    public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
                                      @MeasureSpecMode int mode) {
        if (sUseBrokenMakeMeasureSpec) {
            return size + mode;
        } else {
            return (size & ~MODE_MASK) | (mode & MODE_MASK);
        }
    }
    public static int makeSafeMeasureSpec(int size, int mode) {
        if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
            return 0;
        }
        return makeMeasureSpec(size, mode);
    }
    @MeasureSpecMode
    public static int getMode(int measureSpec) {
        //noinspection ResourceType
        return (measureSpec & MODE_MASK);
    }
    public static int getSize(int measureSpec) {
        return (measureSpec & ~MODE_MASK);
    }
}

MeasureSpec:

        首先,对于view之间尺寸的传递是通过传递一个32位的int数,这个数的高两位存放的是对子view尺寸的限制,剩下的30位存放的父view给子view的大小,这个数的组装和解析就是交由MeasureSpec来做的,对于view尺寸的限制有以下三种模式:

UNSPECIFIED

        对子view没有任何限制,子view要多大就给多大,自定义view中用的很少;

ATMOST

        子view的大小不能超过父view给定的大小,"wrap_content"就是这个模式;

EXACTLY

        子view直接使用父view给定的大小,具体尺寸和“match_parent”就是这个模式;

这个类应该不难理解,就是将size和mode进行“与 或”运算以达到拼装和解析。

这里我们看一下TextView中onMeasure()的伪代码:

 

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;
    if (widthMode == MeasureSpec.EXACTLY) {
        width = widthSize;
    } else {
        width = desired;
    }
    if (heightMode == MeasureSpec.EXACTLY) {
        height = heightSize;
    } else {
        height = desired;
    }
    setMeasuredDimension(width, height);
}

这里我们看到对于传进来的关于宽高的两个数就是通过MeasureSpec去解析,拿到宽高的限制模式和尺寸,然后通过对应的限制模式来获取对应的尺寸,最后通过setMeasuredDimension()将获得的宽高设置到view中,setMeasuredDimension()调用的就是下面这个方法:

 

private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
    mMeasuredWidth = measuredWidth;
    mMeasuredHeight = measuredHeight;

    mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}

至此view的测量就结束了。现在我们回过来想一想,那这个mode是如何设置的呢?我们知道,子view的上一层肯定是ViewGroup,那measure中的数肯定就是从ViewGroup中传递下来的了,可以发现ViewGroup中有一个measureChild()的方法,顾名思义应该就是测量自view的了啊:

 

protected void measureChild(View child, int parentWidthMeasureSpec,
        int parentHeightMeasureSpec) {
    final LayoutParams lp = child.getLayoutParams();

    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
            mPaddingLeft + mPaddingRight, lp.width);
    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
            mPaddingTop + mPaddingBottom, lp.height);

    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

注意,这里就获取到了child的LayoutParams,对于LayoutParams是在哪里设置的呢,如果还不知道,可以看一下我的上一篇,上一篇在讲到递归生成view的时候,里面有一个方法:

 

viewGroup.addView(view, params);

这个方法里面就会将params设置到view中去,如果params为null,那么就会使用默认的params,默认的params如下:

 

protected LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}

可以看到用到的属性都是“wrap_content”。

        说到这,你可能对LayoutParams还不太明白,那我们就先来看看LayoutParams这个类:

 

public static class LayoutParams {
    @SuppressWarnings({"UnusedDeclaration"})
    @Deprecated
    public static final int FILL_PARENT = -1;
    public static final int MATCH_PARENT = -1;
    public static final int WRAP_CONTENT = -2;
    @ViewDebug.ExportedProperty(category = "layout", mapping = {
            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
    })
    public int width;
    
    @ViewDebug.ExportedProperty(category = "layout", mapping = {
            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
    })
    public int height;
    public LayoutAnimationController.AnimationParameters layoutAnimationParameters;
    public LayoutParams(Context c, AttributeSet attrs) {
        TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
        setBaseAttributes(a, R.styleable.ViewGroup_Layout_layout_width,
                R.styleable.ViewGroup_Layout_layout_height);
        a.recycle();
    }
    
    public LayoutParams(int width, int height) {
        this.width = width;
        this.height = height;
    }
    public LayoutParams(LayoutParams source) {
        this.width = source.width;
        this.height = source.height;
    }
    LayoutParams() {
    }
    protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
        width = a.getLayoutDimension(widthAttr, "layout_width");
        height = a.getLayoutDimension(heightAttr, "layout_height");
    }
}

就维护了两个宽高属性,还记得我们一般在写layout的xml文件时,里面的view都会有layout_width和layout_parent这里两个属性,这两个属性就是作用在这里了,这里在多说一句,LayoutParams还有好多子类作用于不同的view,感兴趣的可以自己去看看。

        讲完LayoutParams后,就让我们回到上面的measureChild(),为了拿到子类的模式和尺寸,这里进入到getChildMeasureSpec()这个方法里面:

 

public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
    int specMode = MeasureSpec.getMode(spec);
    int specSize = MeasureSpec.getSize(spec);

    int size = Math.max(0, specSize - padding);

    int resultSize = 0;
    int resultMode = 0;

    switch (specMode) {
    // Parent has imposed an exact size on us
    case MeasureSpec.EXACTLY:
        if (childDimension >= 0) {
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
            // Child wants to be our size. So be it.
            resultSize = size;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
            // Child wants to determine its own size. It can't be
            // bigger than us.
            resultSize = size;
            resultMode = MeasureSpec.AT_MOST;
        }
        break;

    // Parent has imposed a maximum size on us
    case MeasureSpec.AT_MOST:
        if (childDimension >= 0) {
            // Child wants a specific size... so be it
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
            // Child wants to be our size, but our size is not fixed.
            // Constrain child to not be bigger than us.
            resultSize = size;
            resultMode = MeasureSpec.AT_MOST;
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
            // Child wants to determine its own size. It can't be
            // bigger than us.
            resultSize = size;
            resultMode = MeasureSpec.AT_MOST;
        }
        break;

    // Parent asked to see how big we want to be
    case MeasureSpec.UNSPECIFIED:
        if (childDimension >= 0) {
            // Child wants a specific size... let him have it
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } else if (childDimension == LayoutParams.MATCH_PARENT) {
            // Child wants to be our size... find out how big it should
            // be
            resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
            resultMode = MeasureSpec.UNSPECIFIED;
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
            // Child wants to determine its own size.... find out how
            // big it should be
            resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
            resultMode = MeasureSpec.UNSPECIFIED;
        }
        break;
    }
    //noinspection ResourceType
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

别看这个方法挺多的,其实挺简单的,这里盗张图:

LayoutParams是如何作用的_第1张图片

        这里再用文字总结一下(由于UNSPECIFIED一般系统内部使用,这里就把他排除):

        1、子view的childDimension大于0时,返回的mode是MeasureSpc.EXACTLY,size是chilDimension;

        2、子view的childDimension是LayoutParams.MATCH_PARENT和父view是EXACTLY时,返回的mode是MeasureSpec.EXACTLY,size是父view给的size;

        3、其他的情况返回的mode是MeasureSpec.AT_MOST,size是父view的尺寸;

 

这里我在说一下我们在实际中使用的的几种情况,都是与上面对应的:

        1、在layout的xml文件中,父view使用的是match_parent,子view使用的也是match_parent,那么子view的模式就是MeasureSpec.EXACTLY;

        2、在layout的xml文件中,父view使用的是match_parent,子view使用的是wrap_content,那么子view的模式就是MeasureSpec.AT_MOST;

       3、在layout的xml文件中,子view使用的也是具体的尺寸,那么不管父view使用的是什么,子view的模式都是MeasureSpec.EXACTLY;

        对于上面mode和size自己可以好好体会下,在这个地方刚开始看的时候是很迷糊的,后来多看了几遍才慢慢理解了,主要是一开始看的时候对这个LayoutParams也不是很懂(不知道是怎么设置的)。

 

你可能感兴趣的:(LayoutParams是如何作用的)