View那些事兒(2) -- 理解MeasureSpec

View的繪制的三大流程的第一步就是Measure(測量),想要理解View的測量過程,必須要先理解MeasureSpec,從字面上看,MeasureSpec就是“測量規(guī)格”的意思。其實(shí)它在一定程度上決定了View的測量過程,具體來講它包含了一個(gè)View的尺寸規(guī)格信息。在系統(tǒng)測量View的尺寸規(guī)格的時(shí)候會(huì)將View的LayoutParams根據(jù)父容器所施加的規(guī)則轉(zhuǎn)換成對應(yīng)的MeasureSpec,然后再根據(jù)MeasureSpec測量出View的寬高。

一.MeasureSpec的組成

MeasureSpec代表了一個(gè)32位的int值,高2位代表了SpecMode(測量模式),低30位代表了SpecSize(規(guī)格大小)。下面結(jié)合一段源碼來分析:

public static class MeasureSpec {
    private static final int MODE_SHIFT = 30;//二進(jìn)制數(shù)左移的位數(shù)
    private static final int MODE_MASK  = 0x3 << MODE_SHIFT;//將二進(jìn)制數(shù)11左移動(dòng)30位
    public static final int UNSPECIFIED = 0 << MODE_SHIFT;//將二進(jìn)制數(shù)00左移動(dòng)30位          
    public static final int EXACTLY= 1 << MODE_SHIFT;//將二進(jìn)制數(shù)01左移動(dòng)30位
    public static final int AT_MOST= 2 << MODE_SHIFT;//將二進(jìn)制數(shù)10左移動(dòng)30位  
    //將SpecMode和SpecSize包裝成MeasureSpec
    public static int makeMeasureSpec(int size, int mode ){
        if (sUseBrokenMakeMeasureSpec) {
            return size + mode;
        } else {
            return (size & ~MODE_MASK) | (mode & MODE_MASK);
        }
    }
    //從mesureSpec中取出SpecMode
    public static int getMode(int measureSpec) {
        return (measureSpec & MODE_MASK);
    }
    //從measureSpec中取出SpecSize
    public static int getSize(int measureSpec) {
        return (measureSpec & ~MODE_MASK);
    }
}

通過以上源碼,便可以很清晰地看出整個(gè)MeasureSpec的工作原理,其中涉及到了java里的按位運(yùn)算操作,“&”是按位與的意思,“~”則是按位取反的意思,“<<”是左移運(yùn)算符(x<<1就表示x的值乘2),這些運(yùn)算符都是在2進(jìn)制數(shù)的層面上進(jìn)行運(yùn)算的,具體的運(yùn)算規(guī)則google上面一大堆,這里就不多說了。
MeasrureSpec類的三個(gè)常量:UNSPECIFIED、EXACTLY、AT_MOST分別代表的三種SpecMode(測量模式):

  • UNSPECIFIED(不指定大小的)
    父容器不對View有任何限制,想要多大有多大,這種情況一般屬于系統(tǒng)內(nèi)部,表示一種測量狀態(tài),幾乎用不到。例如:系統(tǒng)對ScrollView的繪制過程。
  • EXACTLY(精確的)
    父容器已經(jīng)檢測出View所需要的精確的大小,這個(gè)時(shí)候View的最終大小就是SpecSize所指定的值。這里對應(yīng)于:LayoutParams中的match_parent和具體的數(shù)值,如20dp。
  • AT_MOST(最大的)
    這種模式稍微難處理一點(diǎn),它指的是父容器指定了一個(gè)可用的大小(SpecSize),View的大小不能超過這個(gè)值的大小。如果超過了,就取父容器的大小,如果沒超過,就取自身的大小。這里對應(yīng)于:LayoutParams中的wrap_content模式。

全部都是些理論,沒點(diǎn)demo怎么行,下面直接上一段代碼吧:

首先,要實(shí)現(xiàn)的效果很簡單,就是一個(gè)圓形的自定義View(我們主要是要處理wrap_content的情況下的數(shù)據(jù),必須給它一個(gè)默認(rèn)值):

public class CircleView extends View {
    Paint mPaint;//畫筆類
    public CircleView(Context context) {
        super(context);
    }

    public CircleView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public CircleView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        //第一步肯定是拿到View的測量寬高(SpecSize)和測量模式(SpecMode)
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        //View顯示的時(shí)候的實(shí)際的大小
        int width = 0;
        int height = 0;
        //開始處理寬度
        //默認(rèn)的寬度(在wrap_content的情況下必須有個(gè)默認(rèn)的寬高)
        int defaultWidth = 200;
        //判斷SpecMode(在xml中指定View的寬度的時(shí)候就已經(jīng)決定了View的SpecMode)
        switch (widthMode){
            case MeasureSpec.AT_MOST://這里指的是wrap_content,在這個(gè)模式下不能超過父容器的寬度
                width = defaultWidth;
                break;
            case MeasureSpec.EXACTLY://這里指的是match_parent或者具體的值,不需要做什么處理,width直接等于widthSize就可以了
                width = widthSize;
                break;
            case MeasureSpec.UNSPECIFIED://這個(gè)模式用不到,完全可以忽略
                width = defaultWidth;
                break;
            default:
                width = defaultWidth;
                break;
        }
        //開始處理高度
        int defaultHeight = 200;
        switch (heightMode){
            case MeasureSpec.AT_MOST://這里指的是wrap_content,在這個(gè)模式下不能超過父容器的高度
                height = defaultHeight;
                break;
            case MeasureSpec.EXACTLY://這里指的是match_parent或者具體的值,不需要做什么處理,height直接等于heightSize就可以了
                height = heightSize;
                break;
            case MeasureSpec.UNSPECIFIED://這個(gè)模式用不到,完全可以忽略
                height = defaultHeight;
                break;
            default:
                height = defaultHeight;
                break;
        }
        //最后必須調(diào)用父類的測量方法,來保存我們計(jì)算的寬度和高度,使得設(shè)置的測量值生效
        setMeasuredDimension(width,height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //初始化畫筆,并進(jìn)行一系列的設(shè)置,如顏色等。
        mPaint = new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setAntiAlias(true);//設(shè)置抗鋸齒
        //canvas.drawCircle的幾個(gè)參數(shù)分別是:圓心的x坐標(biāo),y坐標(biāo),半徑,畫筆
        canvas.drawCircle(getWidth()/2,getHeight()/2,Math.min(getWidth()/2,getHeight()/2),mPaint);
    }
}

顯示效果如下:

處理wrap_content后的自定義View

大家可以試一下,如果把不在onMreasure中做以上處理(注釋掉onMeasure方法即可看見效果),給CircleView設(shè)置的wrap_content會(huì)失效,實(shí)際的顯示效果和match_parent沒什么區(qū)別。
在這個(gè)地方提前寫了一個(gè)自定義View是為了幫助讀者理解MeasureSpec的相關(guān)用法,詳細(xì)結(jié)合前一篇文章的講解加上代碼的注釋,大家還是能很容易看懂的。
當(dāng)然為了把這個(gè)過程表述清楚,我把代碼寫得很詳細(xì),顯得有點(diǎn)累贅,實(shí)際中其實(shí)可以不用這么詳細(xì)。

二.MeasureSpec和LayouParams的關(guān)系

上面都在講MeasureSpec是什么,現(xiàn)在就該說說他是怎么來的了。
這里要分兩部分說:第一是普通的View,第二是DecorView

  • 在普通View測量過程中,系統(tǒng)會(huì)將View自身的LayoutParams在父容器的約束下轉(zhuǎn)換為對應(yīng)的MeasureSpec,然后再根據(jù)這個(gè)MeasureSpec來確定View測量后的寬和高;
  • 在DecorView(頂級View)的測量過程中,系統(tǒng)會(huì)將View自生的LayoutParams在窗口尺寸的約束下轉(zhuǎn)換為對應(yīng)的MeasureSpec 。

1.首先,重點(diǎn)說一下普通的View

對于普通的View(即在布局文中的View)來說,它的measure過程由ViewGroup傳遞而來,所以先來看看ViewGroup的measureChildWithMargins()方法:

//對ViewGroup的子View進(jìn)行Measure的方法
protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
              int parentHeightMeasureSpec, int heightUsed) {
    //獲取子View的布局參數(shù)信息(MarginLayoutParams是繼承自ViewGroup.LayoutParmas的)
    final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
    //獲取子View的寬度的MeasureSpec,需要傳入父容器的parentWidthMeasureSpec等信息
    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
            mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                    + widthUsed, lp.width);
    //獲取子View的高度的MeasureSpec,需要傳入父容器的parentHeightMeasureSpec等信息    
    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
            mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                    + heightUsed, lp.height);

    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}  

結(jié)合注釋,從上面這段測量子View的MeasureSpec的源碼中可以看出,在測量的時(shí)候傳入了父容器的MeasureSpec信息和子View自身的LayoutParams信息(如margin、padding),所以才說普通View的測量過程與父容器和自身的LayoutParams有關(guān)。
那么像知道測量的具體過程就得看看getChildMeasureSpec()這個(gè)方法了(看似代碼較多,但是很簡單):

public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
          //還是先拿到specMode和specSize信息
        int specMode = MeasureSpec.getMode(spec);
        int specSize = MeasureSpec.getSize(spec);
          //padding指的是父容器已經(jīng)占據(jù)的空間大小,所以,子View的大小因?yàn)楦溉萜鞯拇笮p去padding
        int size = Math.max(0, specSize - padding);
          //測量后View最終的specSize和specMode
        int resultSize = 0;
        int resultMode = 0;
          //針對三種specMode進(jìn)行判斷
        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);
    }

上面的代碼很清晰地展示這個(gè)測量過程,下面一個(gè)表格來梳理具體的判斷邏輯。(parentSize是指父容器目前可使用的大小)

parentSpecMode →
childLayoutParams↓
EXACTLY AT_MOST UNSPICIFIED
dp/px(確定的寬/高) EXACTLY
childSize
EXACTLY
childSize
EXACTLY
childSize
match_parent EXACTLY
parentSize
AT_MOST
parentSize
UNSPECIFIED
0
wrap_content AT_MOST
parentSize
AT_MOST
parentSize
UNSPECIFIED
0

根據(jù)表格,getChildMeasureSpec()方法的判斷規(guī)則一目了然:

  • 當(dāng)View的指定了確定的寬高的時(shí)候,無論父容器的SpecMode是什么,它的SpecMode都是EXACTLY,并且大小遵循LayoutParams中的大小;
  • 當(dāng)View的寬/高指定成match_parent的時(shí)候,它的SpecMode與父容器相同,并且大小不能超過父容器的剩余空間大小;
  • 當(dāng)View的寬/高指定成wrap_content的時(shí)候,它的SpecMode恒為(不考慮UNSPECIFIED的情況)AT_MOST,并且大小不能超過父容器的剩余空間大小。

由于UNSPECIFIED模式我們一般接觸不到,故在這里不做討論
從上面的總結(jié)來看,其實(shí)普通View的MeasureSpec的LayoutParams的關(guān)系還是很容易理解與記憶的。

2.下面該來看看DecorView(頂級View)了

對于DecorView來說,MeasureSpec是由窗口尺寸和自身的LayoutParams共同決定的。
還是來看看源碼吧,在ViewRootImpl(這個(gè)類被隱藏了,需要手動(dòng)搜索sdk目錄找出ViewRootImpl.java才能看見源碼)有一個(gè)meaureHierarchy()方法,其中有下面這段代碼:

childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);  
childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);  
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);      

其中,desiredWindowWidth和desiredWindowHeight分別指的是屏幕的寬高。
看到這里就隱約感覺到DecorView的MeasureSpec會(huì)和窗口尺寸有關(guān),再來看看getRootMeasureSpec就更明了了:

private int getRootMeasureSpec(int windowSize, int rootDimension) {  
    int measureSpec;  
    switch (rootDimension) {  
  
    case ViewGroup.LayoutParams.MATCH_PARENT:  
        // Window can't resize. Force root view to be windowSize.  
        measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);  
        break;  
    case ViewGroup.LayoutParams.WRAP_CONTENT:  
        // Window can resize. Set max size for root view.  
        measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);  
        break;  
    default:  
        // Window wants to be an exact size. Force root view to be that size.  
        measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);  
        break;  
    }  
    return measureSpec;  
}    

看到這里就豁然開朗了,DecorView的MeasureSpec的確和窗口尺寸有關(guān)。

所以,Decor的MeasureSpec根據(jù)它的LayoutParams遵循以下規(guī)則:

  • LayoutParams.MATCH_PARENT: EXACTLY(精準(zhǔn)模式),大小就是窗口的大小;
  • LayoutParams.WRAP_CONTENT: AT_MOST(最大模式),大小不定,但是不能超過窗口的大小;
  • 固定的大小(如200dp): EXACTLY(精準(zhǔn)模式),大小為LayoutParams所制定的大小。

至此,對MeasureSpec的理解就結(jié)束了

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容