View在測量時的MeasureSpec由什麼決定?

来源:http://www.cnblogs.com/tangZH/archive/2017/06/17/7040785.html
-Advertisement-
Play Games

我們都知道系統要確定View的大小,首先得先獲得MeasureSpec,再通過MeasureSpec來決定View的大小。 MeasureSpec(32為int值)由兩部分組成: SpecMode(高2位):測量模式。 SpecSize(低30位):某種測量模式下的規格大小。 SpecMode有3類 ...


 

我們都知道系統要確定View的大小,首先得先獲得MeasureSpec,再通過MeasureSpec來決定View的大小。

MeasureSpec(32為int值)由兩部分組成:

SpecMode(高2位):測量模式。

SpecSize(低30位):某種測量模式下的規格大小。

 

SpecMode有3類:

UNSPECIFIED: 父容器不對view做大小限制,一般用於系統內部,表示一種測量狀態。

EXACTLY:精確模式。對應於:LayoutPrams中的match_parent和具體數值。

AT_MOST:最大值模式。對應於LayoutParam中的wrap_content模式。

 

那麼問題來了,這個MeasureSpec又是由什麼決定的呢?我們從源代碼裡面入手。

ViewGroup裡面有一個方法,叫做measureChildWithMargins,用來測量子view的大小的。

/**
     * Ask one of the children of this view to measure itself, taking into
     * account both the MeasureSpec requirements for this view and its padding
     * and margins. The child must have MarginLayoutParams The heavy lifting is
     * done in getChildMeasureSpec.
     *
     * @param child The child to measure
     * @param parentWidthMeasureSpec The width requirements for this view
     * @param widthUsed Extra space that has been used up by the parent
     *        horizontally (possibly by other children of the parent)
     * @param parentHeightMeasureSpec The height requirements for this view
     * @param heightUsed Extra space that has been used up by the parent
     *        vertically (possibly by other children of the parent)
     */
    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);
    }

可以看出,在代碼里,會先獲取childWidthMeasureSpec和childHeightMeasureSpec,然後再測量子元素 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);

我們關鍵是要看這兩個MeasureSpec是怎麼獲取到的,通過方法getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);我們可以看出MeasureSpec的獲取不但與子元素本身的LayoutParam有關,還與父容器的MeasureSpec有關,當然,也與它的padding,margin有關。
我們進去看看,這部分代碼有點長,不過裡面的邏輯很簡單,我們直接在源代碼裡面通過加註釋來分析。

/**
     * Does the hard part of measureChildren: figuring out the MeasureSpec to
     * pass to a particular child. This method figures out the right MeasureSpec
     * for one dimension (height or width) of one child view.
     *
     * The goal is to combine information from our MeasureSpec with the
     * LayoutParams of the child to get the best possible results. For example,
     * if the this view knows its size (because its MeasureSpec has a mode of
     * EXACTLY), and the child has indicated in its LayoutParams that it wants
     * to be the same size as the parent, the parent should ask the child to
     * layout given an exact size.
     *
     * @param spec The requirements for this view
     * @param padding The padding of this view for the current dimension and
     *        margins, if applicable
     * @param childDimension How big the child wants to be in the current
     *        dimension
     * @return a MeasureSpec integer for the child
     */
    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//子元素的specSize
        int resultMode = 0//子元素的specMode

        switch (specMode) {
        // Parent has imposed an exact size on us
        case MeasureSpec.EXACTLY: //如果父容器的測量模式為EXACTLY
            if (childDimension >= 0) { //如果子元素的LayoutParam為具體數值>=0
                resultSize = childDimension; //那麼子元素的specSize就是childDimension
                resultMode = MeasureSpec.EXACTLY; //那麼子元素的specMode是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
 //這裡View.sUseZeroUnspecifiedMeasureSpec一直都是false,因此resultSize==0;
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; } return MeasureSpec.makeMeasureSpec(resultSize, resultMode); }


由以上的分析可以看出子元素的MeasureSpec的獲取不但與子元素本身的LayoutParam有關,還與父容器的MeasureSpec有關,當然,也與它的padding,margin有關。

其實我們可以得出下麵的結論:

 

 

            parentMeasureSpec

 

childLayoutParam

EXACTLY

AT_MOST

UNSPECIFIED

具體數值

EXACTLLY

childSize

EXACTLY

childSize

EXACTLY

childSize

Match_parent

EXACTLY

parentSize

AT_MOST

parentSize

UNSPECIFIED

0

Wrap_content

AT_MOST

parentSize

AT_MOST

parentSize

UNSPECIFIED

0

 parentSize是父容器的剩餘空間。

從上面的表格也可以看出,當我們直接繼承view來實現自定義控制項的時候,需要重寫onMeasure方法並設置wrap_content時候的自身大小,不然使用wrap_content得時候就相當於使用match_parent。我們可以用下麵的模板:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecMode=MeasureSpec.getMode(widthMeasureSpec);
        int heightSpecMode=MeasureSpec.getMode(heightMeasureSpec);

        int widthSpecSize=MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecSize=MeasureSpec.getSize(heightMeasureSpec);

        if (widthSpecMode==MeasureSpec.AT_MOST && heightSpecMode==MeasureSpec.AT_MOST)
        {
            setMeasuredDimension(100,100);
        }
        else if (widthSpecMode==MeasureSpec.AT_MOST)
        {
            setMeasuredDimension(100,heightSpecSize);
        }
        else if (heightSpecMode==MeasureSpec.AT_MOST)
        {
            setMeasuredDimension(widthSpecSize,100);
        }
    }

上面代碼中的100是我們自己設置的數值,你也可以用其他數值,根據自己需要。

 

以上便是對MeasureSpec由何決定的分析。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 做頁面需要兩個時間輸入框一個顯示當前時間,一個顯示之前的時間,並且需要一個select下拉框控制兩個時間輸入框之間的差,效果如下圖: 這裡使用的是My97DatePicer,簡單方便,引入my97插件,設置input時間框的格式,這裡設置的時間最大是當前時間,開始時間框不能比結束時間框的時間大 弄完 ...
  • 前言 個人觀點,供您參考 觀點源自作者的使用經驗和日常研究 排名基於框架的受歡迎度, 語法結構, 易用性等特性 ...
  • 今天逛園子,偶然看到最多推薦,有點好奇。 F12查看元素,發現是在css中加了一個after,內容中增加了一個“w”。 本著娛樂至上的準則,自己也試試。複製以下css到設置自定義css中 #digg_count:after{ content: 'w'; } :after, :before { web ...
  • 1、BUG-In android7 phone can not slide above 註:Android 7.0以上,iScroll滑動緩慢遲鈍問題解決 What browser are you using? There was a fix to iScroll's handling of pas ...
  • 介紹 vue schart 是使用vue.js封裝了sChart.js圖表庫的一個小組件。支持vue.js 1.x & 2.x 倉庫地址: "https://github.com/lin xin/vue schart" sChart.js 作為一個小型簡單的圖表庫,沒有過多的圖表類型,只包含了柱狀圖 ...
  • 本來是在看阮大神寫的ajax教程,突然發現點擊目錄文字會跳轉到相對應的文本內容,於是乎激發了我的興趣。 這個究竟怎麼做的,剛開始看的時候一知半解,找度娘就是:“點擊跳轉到頁面指定位置”,找了下,原來專業術語叫:錨點。 度娘真是個博大精深的地方,有著多種的方法可以使用。 最簡單的一種: 設置a標簽的錨 ...
  • 參考資料:ios模式詳解,runtime完整總結 類和對象 Objective-C語言是一門動態語言,它將很多靜態語言在編譯和鏈接時期做的事放到了運行時來處理。這種動態語言的優勢在於:我們寫代碼時更具靈活性,如我們可以把消息轉發給我們想要的對象,或者隨意交換一個方法的實現等。 這種特性意味著Obje ...
  • 這篇是講Glide源碼中into方法的實現原理,可以說with和load方法只是做了前期的初始化配置工作,而真正意義上的圖片載入就是在into方法中實現的,所以該方法的複雜程度是可以想象的,還是依照我之前的寫作習慣,一步步的分析,不留下任何的盲點給大家帶來困惑,那麼下麵就開始吧。 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...