MeasureSpec詳解

一、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;

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

    /**
     * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
     * will automatically get a size of 0. Older apps expect this.
     *
     * @hide internal use only for compatibility with system widgets and older apps
     */
    public static int makeSafeMeasureSpec(int size, int mode) {
        if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
            return 0;
        }
        return makeMeasureSpec(size, mode);
    }

    /**
     * Extracts the mode from the supplied measure specification.
     *
     * @param measureSpec the measure specification to extract the mode from
     * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
     *         {@link android.view.View.MeasureSpec#AT_MOST} or
     *         {@link android.view.View.MeasureSpec#EXACTLY}
     */
    @MeasureSpecMode
    public static int getMode(int measureSpec) {
        //noinspection ResourceType
        return (measureSpec & MODE_MASK);
    }

    /**
     * Extracts the size from the supplied measure specification.
     *
     * @param measureSpec the measure specification to extract the size from
     * @return the size in pixels defined in the supplied measure specification
     */
    public static int getSize(int measureSpec) {
        return (measureSpec & ~MODE_MASK);
    }

    static int adjust(int measureSpec, int delta) {
        final int mode = getMode(measureSpec);
        int size = getSize(measureSpec);
        if (mode == UNSPECIFIED) {
            // No need to adjust size for UNSPECIFIED mode.
            return makeMeasureSpec(size, UNSPECIFIED);
        }
        size += delta;
        if (size < 0) {
            Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
                    ") spec: " + toString(measureSpec) + " delta: " + delta);
            size = 0;
        }
        return makeMeasureSpec(size, mode);
    }

    /**
     * Returns a String representation of the specified measure
     * specification.
     *
     * @param measureSpec the measure specification to convert to a String
     * @return a String with the following format: "MeasureSpec: MODE SIZE"
     */
    public static String toString(int measureSpec) {
        int mode = getMode(measureSpec);
        int size = getSize(measureSpec);

        StringBuilder sb = new StringBuilder("MeasureSpec: ");

        if (mode == UNSPECIFIED)
            sb.append("UNSPECIFIED ");
        else if (mode == EXACTLY)
            sb.append("EXACTLY ");
        else if (mode == AT_MOST)
            sb.append("AT_MOST ");
        else
            sb.append(mode).append(" ");

        sb.append(size);
        return sb.toString();
    }
}

二盆昙、解析

參數(shù)

MeasureSpec是View中的內(nèi)部類(lèi),基本都是二進(jìn)制運(yùn)算焊虏。由于int是32位的淡喜,用高兩位表示mode,低30位表示size炕淮,MODE_SHIFT = 30的作用是移位

MODE_MASK = 0x3 << MODE_SHIFT拆火,其中0x3是十六進(jìn)制跳夭,它的二進(jìn)制是11涂圆,向左移位30,結(jié)果是11000.....0000(一共30個(gè)0)币叹,1與任何數(shù)“&運(yùn)算”均為任何數(shù)润歉,0與任何數(shù)“&運(yùn)算”均為0,故它的作用是獲取measureSpec的高兩位的mode颈抚,或者低30位的size(MODE_MASK取返踩衩,00111...111)

UNSPECIFIED = 0 << MODE_SHIFT,十進(jìn)制0的二進(jìn)制是00贩汉,左移30位是00000...000(00+30個(gè)0)

EXACTLY = 1 << MODE_SHIFT驱富,十進(jìn)制1的二進(jìn)制是01,左移30位是00000...000(01+30個(gè)0)

AT_MOST = 2 << MODE_SHIFT匹舞,十進(jìn)制2的二進(jìn)制是10褐鸥,左移30位是00000...000(10+30個(gè)0)

方法

makeMeasureSpec將mode、size二進(jìn)制運(yùn)算赐稽,如size=4(二進(jìn)制100)叫榕,mode是EXACTLY(01000...000),運(yùn)算結(jié)果01000...100

getMode獲取measureSpec 中的mode浑侥,與MODE_MASK進(jìn)行“&運(yùn)算”,如:10000...100與MODE_MASK(11000...000)晰绎,結(jié)果是10000...000寓落,獲取mode

getSize獲取measureSpec中的size,與MODE_MASK(00111...111)進(jìn)行“&運(yùn)算”荞下,如:10000...100與MODE_MASK(00111...111)伶选,結(jié)果是00000...100,獲取size

三尖昏、3種模式

UNSPECIFIED:不對(duì)View大小做限制考蕾,如:ListView,ScrollView
EXACTLY:確切的大小会宪,如:100dp或者march_parent
AT_MOST:大小不可超過(guò)某數(shù)值肖卧,如:wrap_content

四、子View的MeasureSpec

子View的MeasureSpec由父View的MeasureSpec和子View本身的LayoutPramas共同決定掸鹅,在ViewGroup的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

    若父View是EXACTLY巍沙,則父View有確切數(shù)值或者march_parent
    case MeasureSpec.EXACTLY:
        若子View的childDimension大于0葵姥,則表示有確切數(shù)值,則子View大小為其本身且mode是EXACTLY
        if (childDimension >= 0) {
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } 
        若子View的childDimension是MATCH_PARENT句携,則子View的大小為父View的大小且mode是EXACTLY
        else if (childDimension == LayoutParams.MATCH_PARENT) {
            // Child wants to be our size. So be it.
            resultSize = size;
            resultMode = MeasureSpec.EXACTLY;
        } 
        若子View的childDimension是WRAP_CONTENT榔幸,則子View的大小為父View的大小且mode是AT_MOST,表示最大不可超過(guò)父View數(shù)值
        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
    若父View是AT_MOST矮嫉,則父View一般是wrap_content削咆,強(qiáng)給子View最大的值
    case MeasureSpec.AT_MOST:
        若子View的childDimension大于0,則表示有確切數(shù)值蠢笋,則子View大小為其本身且mode是EXACTLY
        if (childDimension >= 0) {
            // Child wants a specific size... so be it
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } 
        若子View的childDimension是MATCH_PARENT拨齐,則子View的大小不超過(guò)父View的大小且mode是AT_MOST
        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;
        } 
       若子View的childDimension是WRAP_CONTENT,則子View的大小不超過(guò)父View的大小且mode是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
    若父View是UNSPECIFIED昨寞,則父View不限制子View大小
    case MeasureSpec.UNSPECIFIED:
    若子View的childDimension大于0瞻惋,則表示有確切數(shù)值,則子View大小為其本身且mode是EXACTLY
        if (childDimension >= 0) {
            // Child wants a specific size... let him have it
            resultSize = childDimension;
            resultMode = MeasureSpec.EXACTLY;
        } 
        若子View的childDimension是MATCH_PARENT援岩,因?yàn)楦竀iew是UNSPECIFIED歼狼,所以子View大小為0
        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;
        }
        若子View的childDimension是WRAP_CONTENT,因?yàn)楦竀iew是UNSPECIFIED享怀,所以子View大小為0 
        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);
}

總結(jié)一下:
不管父View是何模式羽峰,若子View有確切數(shù)值,則子View大小就是其本身大小,且mode是EXACTLY
若子View是match_parent限寞,則模式與父View相同忍啸,且大小同父View(若父View是UNSPECIFIED,則子View大小為0)
若子View是wrap_content履植,則模式是AT_MOST计雌,大小同父View,表示不可超過(guò)父View大忻钓(若父View是UNSPECIFIED凿滤,則子View大小為0)

其實(shí)只要弄明白三種模式的含義,子View的模式及大小就明了了庶近。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末翁脆,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子鼻种,更是在濱河造成了極大的恐慌反番,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,470評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件叉钥,死亡現(xiàn)場(chǎng)離奇詭異罢缸,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)投队,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén)枫疆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人敷鸦,你說(shuō)我怎么就攤上這事息楔。” “怎么了扒披?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,577評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵值依,是天一觀(guān)的道長(zhǎng)。 經(jīng)常有香客問(wèn)我谎碍,道長(zhǎng)鳞滨,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,176評(píng)論 1 292
  • 正文 為了忘掉前任蟆淀,我火速辦了婚禮,結(jié)果婚禮上澡匪,老公的妹妹穿的比我還像新娘熔任。我一直安慰自己,他們只是感情好唁情,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,189評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布疑苔。 她就那樣靜靜地躺著,像睡著了一般甸鸟。 火紅的嫁衣襯著肌膚如雪惦费。 梳的紋絲不亂的頭發(fā)上兵迅,一...
    開(kāi)封第一講書(shū)人閱讀 51,155評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音薪贫,去河邊找鬼恍箭。 笑死,一個(gè)胖子當(dāng)著我的面吹牛瞧省,可吹牛的內(nèi)容都是我干的扯夭。 我是一名探鬼主播,決...
    沈念sama閱讀 40,041評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼鞍匾,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼交洗!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起橡淑,我...
    開(kāi)封第一講書(shū)人閱讀 38,903評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤构拳,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后梁棠,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體隐圾,經(jīng)...
    沈念sama閱讀 45,319評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,539評(píng)論 2 332
  • 正文 我和宋清朗相戀三年掰茶,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了暇藏。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,703評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡濒蒋,死狀恐怖盐碱,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情沪伙,我是刑警寧澤瓮顽,帶...
    沈念sama閱讀 35,417評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站围橡,受9級(jí)特大地震影響暖混,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜翁授,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,013評(píng)論 3 325
  • 文/蒙蒙 一拣播、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧收擦,春花似錦贮配、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,664評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至,卻和暖如春圆存,著一層夾襖步出監(jiān)牢的瞬間叼旋,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,818評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工沦辙, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留夫植,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,711評(píng)論 2 368
  • 正文 我出身青樓怕轿,卻偏偏與公主長(zhǎng)得像偷崩,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子撞羽,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,601評(píng)論 2 353