MeasureSpec

一蒋畜、概念

1锦茁、MeasureSpec代表一個32位int值,高2位代表SpecMode胚吁,低30位代表SpecSize撑毛。
SpecMode是測量模式书聚,SpecSize是某種測量模式下的規(guī)格大小。

    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;

        /**
         * Creates a measure specification based on the supplied size and mode.
         *
         * The mode must always be one of the following:
         * <ul>
         *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
         *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
         *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
         * </ul>
         *
         * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
         * implementation was such that the order of arguments did not matter
         * and overflow in either value could impact the resulting MeasureSpec.
         * {@link android.widget.RelativeLayout} was affected by this bug.
         * Apps targeting API levels greater than 17 will get the fixed, more strict
         * behavior.</p>
         *
         * @param size the size of the measure specification
         * @param mode the mode of the measure specification
         * @return the measure specification based on size and mode
         */
        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);
            }
        }
    }

2藻雌、SpecMode的類型概念
(1)UNSPECIFIED :父容器不對View有任何限制雌续,要多大給多大,這種情況一般用于系統(tǒng)內(nèi)部蹦疑,表示一種的狀態(tài)西雀。
(2)EXACTLY:父容器已經(jīng)檢測出View所需要的精確大小,這個時候View的最終大小就是SpecSize所指定的值歉摧。對應(yīng)LayoutParams的match_parent和具體的數(shù)值兩種模式艇肴。
(3)AT_MOST:父容器指定了一個可用大小即SpecSize,View的大小不能大于這個值叁温,具體是什么值要看不同View的具體實現(xiàn)再悼,對應(yīng)于LayoutParams的wrap_content。

二膝但、與LayoutParams的對應(yīng)關(guān)系

對應(yīng)頂級View(DecorView)冲九,其MeasureSpec由窗口的尺寸和自身的LayoutParams共同確定;對于普通View,其MeasureSpec由父容器的MeasureSpec和資深的LayoutParams來共同確定莺奸,MeasureSpec一旦確定后丑孩,onMeasure就可以確定View的測量寬高。
1灭贷、DecorView的MeasureSpec創(chuàng)建過程


    /**
     * Figures out the measure spec for the root view in a window based on it's
     * layout params.
     *
     * @param windowSize
     *            The available width or height of the window
     *
     * @param rootDimension
     *            The layout params for one dimension (width or height) of the
     *            window.
     *
     * @return The measure spec to use to measure the root view.
     */
    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;
    }

~LayoutParams.MATCH_PARENT:精確模式温学,大小就是窗口的大小
~LayoutParams.WRAP_CONTENT:最大模式,大小不定甚疟,但是不能超過窗口大小
~固定大姓提:精確模式,大小為LayoutParams指定大小
2览妖、一般View的MeasureSpec創(chuàng)建過程
對于普通的View轧拄,其measure過程由ViewGroup傳遞過來。

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

在對子View進行measure前讽膏,ViewGroup通過getChildMeasureSpec得到子元素的MeasureSpec檩电,子View的MeasureSpec與父容器的MeasureSpec和子View本身的LayoutParams有關(guā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) {
                // 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);
    }

該方法根據(jù)父布局的MeasureSpec同時結(jié)合View本身的LayoutParams來確定子元素的MeasureSpec桅打。整理成表則為:


普通View的MeasureSpec創(chuàng)建規(guī)則

(1)當(dāng)View采用固定寬高的時候是嗜,不管父容器的MeasureSpec是什么,View的MeasureSpec都是精確模式并且遵循LayoutParams的大小挺尾。
(2)當(dāng)View的寬高是match_parent的時候鹅搪,如果父容器是精確模式,那么View也是精確模式并且其大小時父容器的剩余空間遭铺;如果父容器是最大模式丽柿,那么View也是最大模式并且大小不會超過父容器的剩余空間。
(3)當(dāng)View的寬高是wrap_content的時候魂挂,不管父容器的模式是精確還是最大化甫题,View的模式總是最大化并且不能超過父容器的剩余空間。

結(jié)尾

摘抄記錄自《Android開發(fā)藝術(shù)探討》

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末涂召,一起剝皮案震驚了整個濱河市坠非,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌果正,老刑警劉巖炎码,帶你破解...
    沈念sama閱讀 211,376評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異秋泳,居然都是意外死亡潦闲,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,126評論 2 385
  • 文/潘曉璐 我一進店門迫皱,熙熙樓的掌柜王于貴愁眉苦臉地迎上來歉闰,“玉大人,你說我怎么就攤上這事『途矗” “怎么了凹炸?”我有些...
    開封第一講書人閱讀 156,966評論 0 347
  • 文/不壞的土叔 我叫張陵,是天一觀的道長概龄。 經(jīng)常有香客問我还惠,道長,這世上最難降的妖魔是什么私杜? 我笑而不...
    開封第一講書人閱讀 56,432評論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮救欧,結(jié)果婚禮上衰粹,老公的妹妹穿的比我還像新娘。我一直安慰自己笆怠,他們只是感情好铝耻,可當(dāng)我...
    茶點故事閱讀 65,519評論 6 385
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蹬刷,像睡著了一般瓢捉。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上办成,一...
    開封第一講書人閱讀 49,792評論 1 290
  • 那天泡态,我揣著相機與錄音,去河邊找鬼迂卢。 笑死某弦,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的而克。 我是一名探鬼主播靶壮,決...
    沈念sama閱讀 38,933評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼员萍!你這毒婦竟也來了腾降?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,701評論 0 266
  • 序言:老撾萬榮一對情侶失蹤碎绎,失蹤者是張志新(化名)和其女友劉穎螃壤,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體混卵,經(jīng)...
    沈念sama閱讀 44,143評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡映穗,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,488評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了幕随。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蚁滋。...
    茶點故事閱讀 38,626評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出辕录,到底是詐尸還是另有隱情睦霎,我是刑警寧澤,帶...
    沈念sama閱讀 34,292評論 4 329
  • 正文 年R本政府宣布走诞,位于F島的核電站副女,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏蚣旱。R本人自食惡果不足惜碑幅,卻給世界環(huán)境...
    茶點故事閱讀 39,896評論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望塞绿。 院中可真熱鬧沟涨,春花似錦、人聲如沸异吻。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,742評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽诀浪。三九已至棋返,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間雷猪,已是汗流浹背睛竣。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留春宣,地道東北人酵颁。 一個月前我還...
    沈念sama閱讀 46,324評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像月帝,于是被迫代替她去往敵國和親躏惋。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,494評論 2 348