View的工作原理-Measure

簡(jiǎn)介

自定義View必須要知道View的工作原理揣钦,我們都知道View的工作流程是measure->layout->draw,今天我們就逐個(gè)分析一下三個(gè)步驟伐庭。
首先要知道ViewRoot和Window和DecorView三者的關(guān)系璧函,ViewRoot對(duì)應(yīng)的是ViewRootImpl類笋籽,它是連接WindoManage和DecorView的紐帶柿菩,View的整個(gè)工作流程都是在ViewRootImpl的performTraversals中完成的振诬。
今天我們一起看看Measure的工作流程蹭睡。

理解MeasureSpec

在View的Measure過(guò)程MeasureSpec是一個(gè)很重要的內(nèi)容,它描述了要測(cè)量的尺寸和模式贷揽。View在Measure的過(guò)程是根據(jù)自身的LayoutParams和父容器的MeasureSpec轉(zhuǎn)換成對(duì)應(yīng)自身的MeasureSpec棠笑,然后再根據(jù)這個(gè)MeasureSpec測(cè)量出View的寬和高。
我們先看一下MeasureSpec的定義

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 {}

        /**
         * Measure specification mode: The parent has not imposed any constraint
         * on the child. It can be whatever size it wants.
         */
        public static final int UNSPECIFIED = 0 << MODE_SHIFT;

        /**
         * Measure specification mode: The parent has determined an exact size
         * for the child. The child is going to be given those bounds regardless
         * of how big it wants to be.
         */
        public static final int EXACTLY     = 1 << MODE_SHIFT;

        /**
         * Measure specification mode: The child can be as large as it wants up
         * to the specified size.
         */
        public static final int AT_MOST     = 2 << MODE_SHIFT;

        public static int makeMeasureSpec( int size, @MeasureSpecMode int mode) {
            if (sUseBrokenMakeMeasureSpec) {
                return size + mode;
            } else {
                return (size & ~MODE_MASK) | (mode & MODE_MASK);
            }
        }
        
        @UnsupportedAppUsage
        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 代表一個(gè)32位的int值禽绪,高2位代表SpecMode蓖救,低30位代表SpecSize。
通過(guò)靜態(tài)方法makeMeasureSpec將SpecMode和SpecSize打包成一個(gè)int值印屁,避免過(guò)多的對(duì)象內(nèi)存分配循捺,另外還提供了解包方法。
SpecMode有三種模式:
**UNSPECIFIED **
父容器對(duì)view沒有任何約束雄人,view想要多大就多大从橘,這種模式一般系統(tǒng)使用或者是scrollView使用。
EXACTLY
父容器檢測(cè)出View需要的精確大小础钠,View的大小是SpecSize指定的值恰力。它對(duì)應(yīng)于LayoutParams中的match_parent和具體的數(shù)值。
AT_MOST
父容器指定一個(gè)最大值SpecSize旗吁,View的大小不能超過(guò)該值踩萎,它對(duì)應(yīng)的是LayoutParams的wrap_content

MeasureSpec在DecorView和View以及ViewGroup中的表現(xiàn)是不一樣的,我們分別分析一下三者的區(qū)別很钓。

DecorView的MeasureSpec

DecorView的MeasureSpec是由Window的尺寸和自身的LayoutParams共同決定的香府。在ViewRootImpl的measureHierarchy中展示了MeasureSpec的創(chuàng)建過(guò)程

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

desiredWindowWidth和desiredWindowHeight表示屏幕的尺寸,接著看一下getRootMeasureSpec

  private static 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產(chǎn)生遵守如下規(guī)則:

  • MATCH_PARENT:精確模式码倦,大小是窗口大小
  • WRAP_CONTENT: 最大模式企孩,最大大小是窗口大小
  • 其他:精確模式,大小是LayoutParams指定的具體值袁稽。

View的MeasureSpec

先看一下ViewGroup的measureChildWithMargins

    protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

上述方法對(duì)子元素進(jìn)行measure勿璃,measure前的childXXXMeasureSpec是通過(guò)父容器的MeasureSpec,自身(ViewGroup)的被占用的空間(padding和margin),子View的LayoutParams綜合測(cè)量計(jì)算出來(lái)的蝗柔。我們看一下getChildMeasureSpec的實(shí)現(xiàn)

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) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                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) {
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

方法內(nèi)部主要是根據(jù)父容器的MeasureSpec和自身的LayoutParams來(lái)確定子元素的MeasureSpec闻葵,其中size是根據(jù)父容器的尺寸減去已經(jīng)被占用的空間尺寸,及可用的尺寸。為了更清楚的展示getChildMeasureSpec的流程我們繪制一個(gè)表格:


MeasureSpec.png

如果只是一個(gè)View的measure會(huì)調(diào)用onMeasure方法完成測(cè)量

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

重點(diǎn)是getDefaultSize

 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;
    }

從這里可以看出View的layoutParams是wrap_content的時(shí)候癣丧,getDefaultSize得到的是specSize,根據(jù)上邊的圖表分析知道specSize是父容器的剩余空間栈妆,這種情況和match_content的大小一樣胁编,所以我們?cè)谧远xView的時(shí)候需要處理specMode是AT_MOST的情況。

ViewGroup的measure過(guò)程

對(duì)于ViewGroup除了完成自身的測(cè)量還要完成子元素的測(cè)量鳞尔,ViewGroup沒有onMeasure方法但是它有一個(gè)meausreChildren方法

  protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
        final int size = mChildrenCount;
        final View[] children = mChildren;
        for (int i = 0; i < size; ++i) {
            final View child = children[i];
            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }
    }

只要子元素是可見的都進(jìn)行測(cè)量,我們看一下measureChild的內(nèi)容

 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);
    }

measureChild的思想就是根據(jù)子元素的LayoutParams,然后再通過(guò)getChildMeasureSpec計(jì)算出子元素的MeasureSpec嬉橙,將這個(gè)MeasureSpec傳遞給子元素的measure方法。

至此View,ViewGroup寥假,DecorView的meausure都介紹完了市框。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市糕韧,隨后出現(xiàn)的幾起案子枫振,更是在濱河造成了極大的恐慌,老刑警劉巖萤彩,帶你破解...
    沈念sama閱讀 221,198評(píng)論 6 514
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件粪滤,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡雀扶,警方通過(guò)查閱死者的電腦和手機(jī)杖小,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,334評(píng)論 3 398
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)愚墓,“玉大人予权,你說(shuō)我怎么就攤上這事±瞬幔” “怎么了扫腺?”我有些...
    開封第一講書人閱讀 167,643評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)议经。 經(jīng)常有香客問(wèn)我斧账,道長(zhǎng),這世上最難降的妖魔是什么煞肾? 我笑而不...
    開封第一講書人閱讀 59,495評(píng)論 1 296
  • 正文 為了忘掉前任咧织,我火速辦了婚禮,結(jié)果婚禮上籍救,老公的妹妹穿的比我還像新娘习绢。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,502評(píng)論 6 397
  • 文/花漫 我一把揭開白布闪萄。 她就那樣靜靜地躺著梧却,像睡著了一般。 火紅的嫁衣襯著肌膚如雪败去。 梳的紋絲不亂的頭發(fā)上放航,一...
    開封第一講書人閱讀 52,156評(píng)論 1 308
  • 那天,我揣著相機(jī)與錄音圆裕,去河邊找鬼广鳍。 笑死,一個(gè)胖子當(dāng)著我的面吹牛吓妆,可吹牛的內(nèi)容都是我干的赊时。 我是一名探鬼主播,決...
    沈念sama閱讀 40,743評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼行拢,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼祖秒!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起舟奠,我...
    開封第一講書人閱讀 39,659評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤竭缝,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后鸭栖,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體歌馍,經(jīng)...
    沈念sama閱讀 46,200評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,282評(píng)論 3 340
  • 正文 我和宋清朗相戀三年晕鹊,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了松却。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,424評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡溅话,死狀恐怖晓锻,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情飞几,我是刑警寧澤砚哆,帶...
    沈念sama閱讀 36,107評(píng)論 5 349
  • 正文 年R本政府宣布,位于F島的核電站屑墨,受9級(jí)特大地震影響躁锁,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜卵史,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,789評(píng)論 3 333
  • 文/蒙蒙 一战转、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧以躯,春花似錦槐秧、人聲如沸啄踊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,264評(píng)論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)颠通。三九已至,卻和暖如春膀懈,著一層夾襖步出監(jiān)牢的瞬間顿锰,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,390評(píng)論 1 271
  • 我被黑心中介騙來(lái)泰國(guó)打工启搂, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留撵儿,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,798評(píng)論 3 376
  • 正文 我出身青樓狐血,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親易核。 傳聞我的和親對(duì)象是個(gè)殘疾皇子匈织,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,435評(píng)論 2 359