LinearLayout中resolveSizeAndState解析

resolveSizeAndState

resolveSizeAndState
  • 方法说明:

Utility to reconcile a desired size and state, with constraints imposed by a MeasureSpec. Will take the desired size, unless a different size is imposed by the constraints. The returned value is a compound integer, with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the resulting size is smaller than the size the view wants to be.
@param size How big the view wants to be
@param measureSpec Constraints imposed by the parent
@return Size information bit mask as defined by
{@link #MEASURED_SIZE_MASK} and {@link #MEASURED_STATE_TOO_SMALL}.

一个计算期望大小和状态的工具方法,通过被强加的MeasureSpec来计算。除非有不同的大小限制,否则还是会使用期望的大小。返回的int值是一个合成值,通过MEASURED_SIZE_MASK来解析出size,并且使用可选的位MEASURE_STATE_TOO_SMALL来标识返回的结果大小比View期望的大小还要小。

public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
    if (Build.VERSION.SDK_INT >= 11) {
        return View.resolveSizeAndState(size, measureSpec, childMeasuredState);
    }
    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:
        if (specSize < size) {
            result = specSize | MEASURED_STATE_TOO_SMALL;
        } else {
            result = size;
        }
        break;
    case MeasureSpec.EXACTLY:
        result = specSize;
        break;
    }
    return result | (childMeasuredState&MEASURED_STATE_MASK);
}

参数size:View期望的大小
参数measureSpec:父View的measureSpec限制
返回:返回返回大小信息通过MEASURED_SIZE_MASK的掩码来获取,并且MEASURED_STATE_TOO_SMALL位来返回是否获取到的结果比期望的小

  1. 判断当前ROM版本是否大于11,如果大于11的话,则返回View.resolveSizeAndState,而View.resolveSizeAndState中的方法体和下述方法一致
  2. 如果ROM版本小于11的话,首先根据传入的MeasureSpec获取Size以及Mode
  3. 如果父View的MeasureSpec的Mode为MeasureSpec.UNSPECIFIED的话,那么size等于传入的size
  4. 如果父View的MeasureSpec的Mode为MeasureSpec.AT_MOST的话,那么就会判断父View的MeasureSpec中的size,是否比传入的size小,如果小的话,那么size等于specSize,并且加入MEASURE_STATE_TOO_SMALL标志位(result=specSize|MEASURE_STATE_TOO_SMALL),否则size等于传入的size
  5. 如果父View的MeasureSpec的Mode为MeasureSpec.EXACTLY的话,则size为specSize
  6. 返回的int值为size|(childMeasuredState&MEASURED_STATE_MASK)

推荐阅读更多精彩内容