Android -- onMeasure()源碼分析


1,作為自定義控件最重要的三個方法之一,onMeasure()可以說是我們研究的重點,今天我們更詳細的來研究一下View的onMeasure()方法和ViewGroup的onMeasure()方法

2,onMeasure()什么時候調用

  我們先來自定義一個控件TestView,然后重寫對應的構造函數、onFinishflate()、onSizeChange()、onDraw()、onMeasure()、onLayout()方法,下面是具體代碼

package com.qianmo.activitydetail.view;

import android.content.Context;
import android.graphics.Canvas;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

/**
 * Created by Administrator on 2017/3/22 0022.
 * E-Mail:543441727@qq.com
 */

public class TestView extends View {
    private static String TAG = "TestView";

    public TestView(Context context) {
        this(context, null);
    }

    public TestView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TestView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        Log.i(TAG, "TestView被創建");
    }

    /**
     * 當所有的控件中所有的子view均被映射成xml觸發
     */
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        Log.i(TAG, "onFinishInflate()");
    }

    /**
     * 當view的大小發生變化時觸發
     *
     * @param w
     * @param h
     * @param oldw
     * @param oldh
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.i(TAG, "onSizeChanged()" + ",w:" + w + ",h:" + w + ",oldw:" + oldw + ",oldh" + oldh);
    }

    /**
     * view渲染內容的細節
     *
     * @param canvas
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.i(TAG, "onDraw()");
    }

    /**
     * onLayout方法是ViewGroup中子View的布局方法,用於放置子View的位置。放置子View很簡單,只需在重寫onLayout方法,
     * 然后獲取子View的實例,調用子View的layout方法實現布局。在實際開發中,一般要配合onMeasure測量方法一起使用。
     *
     * @param changed
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        Log.i(TAG, "onLayout()");
    }

    /**
     * 測量控件高度
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.i(TAG, "onMeasure()");
    }
}

  在布局中引用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:myview="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0a08ff"
    android:orientation="vertical"
    android:padding="10dp"
    >
    <com.qianmo.activitydetail.view.TestView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginTop="20dp"
        android:layout_weight="1"
        android:background="#00ff00"
        />
</LinearLayout>

  來看看我們的打印結果:

打印結果
03-21 22:36:21.240 2144-2144/? I/TestView: TestView被創建
03-21 22:36:21.240 2144-2144/? I/TestView: onFinishInflate()
03-21 22:36:21.332 2144-2144/? I/TestView: onMeasure()
03-21 22:36:21.470 2144-2144/? I/TestView: onMeasure()
03-21 22:36:21.470 2144-2144/? I/TestView: onSizeChanged(),w:1080,h:1080,oldw:0,oldh0
03-21 22:36:21.470 2144-2144/? I/TestView: onLayout()
03-21 22:36:21.527 2144-2144/? I/TestView: onDraw()

  可以看到當我們所有的子view被映射到xml之后在執行onMeasure()測量自身view,測量完之后保存測量后的寬高及模式,通知view大小改變,在執行view相對於父控件的放置函數及onLayout()方法,在執行繪制onDraw()方法。

3,onMeasure執行的流程

  我們都知道onMeasure是由父控件ViewGroup調用的,而所有父控件都是ViewGroup的子類 ,且ViewGroup是一個抽象類,它里面有一個抽象方法onLayout,這個方法的作用就是擺放它所有的子控件(安排位置),因為是抽象類,不能直接new對象,所以我們在布局文件中可以使用View但是不能直接使用 ViewGroup。

  在給子控件確定位置之前,必須要獲取到子控件的大小(只有確定了子控件的大小才能正確的確定上下左右四個點的坐標),而ViewGroup並沒有重寫View的onMeasure方法,也就是說抽象類ViewGroup沒有為子控件測量大小的能力,它只能測量自己的大小。但是既然ViewGroup是一個能容納子控件的容器,系統當然也考慮到測量子控件的問題,所以ViewGroup提供了三個測量子控件相關的方法(measureChildren 和measureChild 和measureChildWithMargins方法)。只是在ViewGroup中沒有調用它們,所以它本身不具備為子控件測量大小的能力,但是他有這個潛力哦。

  為什么都有測量子控件的方法了而ViewGroup中不直接重寫onMeasure方法,然后在onMeasure中調用呢?因為不同的容器擺放子控件的方式不同,比如RelativeLayout,LinearLayout這兩個ViewGroup的子類,它們擺放子控件的方式不同,有的是線性擺放,而有的是疊加擺放,這就導致測量子控件的方式會有所差別,所以ViewGroup就干脆不直接測量子控件,他的子類要測量子控件就根據自己的布局特性重寫onMeasure方法去測量。這么看來ViewGroup提供的三個測量子控件的方法豈不是沒有作用?答案是NO,既然提供了就肯定有作用,這三個方法只是按照一種通用的方式去測量子控件,很多ViewGruop的子類測量子控件的時候就使用了ViewGroup的measureChildxxx系列方法。

  測量的時候父控件的onMeasure方法會遍歷他所有的子控件,挨個調用子控件的measure方法,measure方法會調用onMeasure,然后會調用setMeasureDimension方法保存測量的大小,一次遍歷下來,第一個子控件以及這個子控件中的所有子控件都會完成測量工作;然后開始測量第二個子控件…;最后父控件所有的子控件都完成測量以后會調用setMeasureDimension方法保存自己的測量大小。值得注意的是,這個過程不只執行一次,也就是說有可能重復執行,因為有的時候,一輪測量下來,父控件發現某一個子控件的尺寸不符合要求,就會重新測量一遍(這也解釋了我們上面onMeasure打印了兩次的原因)。

  舉個例子,如下圖所示

  再看看用例圖

4,看看ViewGroup關於測量的代碼

  我們知道,如果要自定義ViewGroup就必須重寫onMeasure方法,在這里測量子控件的尺寸。子控件的尺寸怎么測量呢?ViewGroup中提供了三個關於測量子控件的方法,源碼如下:

  /** *遍歷ViewGroup中所有的子控件,調用measuireChild測量寬高 */
    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);
            }
        }
    }

   /** * 測量某一個child的寬高 */
    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);
    }

  /** * 測量某一個child的寬高,考慮margin值 */
    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);
    }

  這三個方法分別做了那些工作大家應該比較清楚了吧?measureChildren 就是遍歷所有子控件挨個測量,最終測量子控件的方法就是measureChild 和measureChildWithMargins 了,所以這里我們來了解一些其它的知識點

  • measureChildWithMargins跟measureChild的區別就是父控件支不支持margin屬性

  支不支持margin屬性對子控件的測量是有影響的,比如我們的屏幕是1080x1920的,子控件的寬度為填充父窗體,如果使用了marginLeft並設置值為100; 在測量子控件的時候,如果用measureChild,計算的寬度是1080,而如果是使用measureChildWithMargins,計算的寬度是1080-100 = 980。

  • 怎樣讓ViewGroup支持margin屬性?

  ViewGroup中有兩個內部類ViewGroup.LayoutParams和ViewGroup. MarginLayoutParams,MarginLayoutParams繼承自LayoutParams ,這兩個內部類就是VIewGroup的布局參數類,比如我們在LinearLayout等布局中使用的layout_width\layout_hight等以“layout_ ”開頭的屬性都是布局屬性。在View中有一個mLayoutParams的變量用來保存這個View的所有布局屬性。

  • LayoutParams和MarginLayoutParams 的關系:

  LayoutParams 中定義了兩個屬性(現在知道我們用的layout_width\layout_hight的來頭了吧?):

declare-styleable name= "ViewGroup_Layout">
    <attr name ="layout_width" format="dimension">
        <enum name ="fill_parent" value="-1" />
        <enum name ="match_parent" value="-1" />
        <enum name ="wrap_content" value="-2" />
    </attr >
    <attr name ="layout_height" format="dimension">
        <enum name ="fill_parent" value="-1" />
        <enum name ="match_parent" value="-1" />
        <enum name ="wrap_content" value="-2" />
    </attr >
</declare-styleable >

  MarginLayoutParams 是LayoutParams的子類,它當然也延續了layout_width\layout_hight 屬性,但是它擴充了其他屬性:

< declare-styleable name ="ViewGroup_MarginLayout">
    <attr name ="layout_width" />   <!--使用已經定義過的屬性-->
    <attr name ="layout_height" />
    <attr name ="layout_margin" format="dimension"  />
    <attr name ="layout_marginLeft" format= "dimension"  />
    <attr name ="layout_marginTop" format= "dimension" />
    <attr name ="layout_marginRight" format= "dimension"  />
    <attr name ="layout_marginBottom" format= "dimension"  />
    <attr name ="layout_marginStart" format= "dimension"  />
    <attr name ="layout_marginEnd" format= "dimension"  />
</declare-styleable >
  • 為什么LayoutParams 類要定義在ViewGroup中? 

  大家都知道ViewGroup是所有容器的基類,一個控件需要被包裹在一個容器中,這個容器必須提供一種規則控制子控件的擺放,比如你的寬高是多少,距離那個位置多遠等。所以ViewGroup有義務提供一個布局屬性類,用於控制子控件的布局屬性。

  • 為什么View中會有一個mLayoutParams 變量?

  我們在之前學習自定義控件的時候學過自定義屬性,我們在構造方法中,初始化布局文件中的屬性值,我們姑且把屬性分為兩種。一種是本View的繪制屬性,比如TextView的文本、文字顏色、背景等,這些屬性是跟View的繪制相關的。另一種就是以“layout_”打頭的叫做布局屬性,這些屬性是父控件對子控件的大小及位置的一些描述屬性,這些屬性在父控件擺放它的時候會使用到,所以先保存起來,而這些屬性都是ViewGroup.LayoutParams定義的,所以用一個變量保存着。

5,關於ViewGroup中的getChildMeasureSpec方法

  從上面我們貼的源碼可以看到,我們的measureChild()方法和measureChildWithMargin()方法都分調用了getChildMeasureSpec()方法,其作用就是通過父控件的寬高約束規則和父控件加在子控件上的寬高布局參數生成一個子控件的約束。我們知道View的onMeasure方法需要兩個參數(父控件對View的寬高約束),這個寬高約束就是通過這個方法生成的。有人會問為什么不直接拿着子控件的寬高參數去測量子控件呢?打個比方,父控件的寬高約束為wrap_content,而子控件為match_perent,是不是很有意思,父控件說我的寬高就是包裹我的子控件,我的子控件多大我就多大,而子控件說我的寬高填充父窗體,父控件多大我就多大。最后該怎么確定大小呢?所以我們需要為子控件重新生成一個新的約束規則。只要記住,子控件的寬高約束規則是父控件調用getChildMeasureSpec方法生成。

  下面是getChildMeasureSpec()方法的源碼

 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;
        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

  而對應的我們方法中的參數分別對應如下圖所示:

  getChildMeasureSpec()的代碼並不是很多,就是父布局約束和子布局的約束控制,所以我們可以得出下面結論

6,View控件中的onMeasure方法()

  從上面的measureChild的源碼可以看到,最后我們方法是調用的child.measure()方法,所以這里我們要回到View中看一下measure()方法,通過下面的源碼發現我們的measure()方法調用的是onMeasure()方法

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
       ......省略代碼

        // Suppress sign extension for the low bytes
        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);

        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
                widthMeasureSpec != mOldWidthMeasureSpec ||
                heightMeasureSpec != mOldHeightMeasureSpec) {

            // first clears the measured dimension flag
            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;

            resolveRtlPropertiesIfNeeded();

            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
                    mMeasureCache.indexOfKey(key);
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
                //在這里調用的
                onMeasure(widthMeasureSpec, heightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } else {
                long value = mMeasureCache.valueAt(cacheIndex);
                // Casting a long to int drops the high 32 bits, no mask needed
                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            }

            // flag not set, setMeasuredDimension() was not invoked, we raise
            // an exception to warn the developer
            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
                throw new IllegalStateException("View with id " + getId() + ": "
                        + getClass().getName() + "#onMeasure() did not set the"
                        + " measured dimension by calling"
                        + " setMeasuredDimension()");
            }

            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
        }

        mOldWidthMeasureSpec = widthMeasureSpec;
        mOldHeightMeasureSpec = heightMeasureSpec;

        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
    }         

  ok我們來看一下我們的onMeasure()方法的代碼,看看它具體干了些什么

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


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的寬高模式為未指定,他的寬高將設置為android:minWidth/Height =”“值與背景寬高值中較大的一個;
  • 如果View的寬高 模式為 EXACTLY (具體的size ),最終寬高就是這個size值;
  • 如果View的寬高模式為EXACTLY (填充父控件 ),最終寬高將為填充父控件;
  • 如果View的寬高模式為AT_MOST (包裹內容),最終寬高也是填充父控件。

  也就是說如果我們的自定義控件在布局文件中,只需要設置指定的具體寬高,或者MATCH_PARENT 的情況,我們可以不用重寫onMeasure方法。

  但如果自定義控件需要設置包裹內容WRAP_CONTENT ,我們需要重寫onMeasure方法,為控件設置需要的尺寸;默認情況下WRAP_CONTENT 的處理也將填充整個父控件。

  onMeasure方法最后需要調用setMeasuredDimension方法來保存測量的寬高值。

  這樣的話我們就基本分析完了 ,有沒有恍然大悟的感覺!!! See You Next Time ....

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM