Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 從 0 開始自定義控件之 View 的 measure 過程(七)

編輯:關於 Android 程式設計

前言

經過前幾篇的鋪墊,終於來到正式學習 View 的三大流程:測量、布局、繪製。這一篇先從 measure(測量)過程開始。

measure 過程分兩種情況:第一種是 View,第二種是 ViewGroup。如果是 View,透過 measure 方法即可完成其測量過程;但如果是 ViewGroup,不僅要完成自身的測量,還要完成它所有子 View 的測量,若子 View 又是一個 ViewGroup,則繼續遞歸這個流程。下面先從 View 說起。

View 的 measure 過程

View 的測量由 measure 方法完成,但該方法是 final 的,不能被重寫。measure 內部會呼叫 onMeasure(),因此我們只需重寫 onMeasure() 即可。先來看 View 預設的 onMeasure() 實現:

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

可以看到,它直接呼叫 setMeasuredDimension() 設定測量尺寸,關鍵在 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;
}

從程式碼可以看到,對於我們關心的 AT_MOST 和 EXACTLY 模式,getDefaultSize() 返回的就是 MeasureSpec 的 specSize,而這個 MeasureSpec 是由 ViewGroup 傳遞而來的。

这也就解釋了為什麼在佈局中寫 wrap_content 時,若不重寫 onMeasure(),預設大小就會是父控件的可用大小。當寫 wrap_content 時,測量模式為 AT_MOST,寬高等於 specSize,而 specSize 由 ViewGroup 傳來時就是 parentSize(父控件可用大小)。寫 match_parent 時寬高同樣是 parentSize。這時我們只需對 AT_MOST 模式做處理:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    int width = 0;
    int height = 0;
    if (widthMode == MeasureSpec.AT_MOST) {
        width = ...; // 自行計算寬度
    }
    if (heightMode == MeasureSpec.AT_MOST) {
        height = ...; // 自行計算高度
    }
    setMeasuredDimension(
        widthMode != MeasureSpec.AT_MOST ? widthSize : width,
        heightMode != MeasureSpec.AT_MOST ? heightSize : height);
}

至於 UNSPECIFIED 情況,使用的是第一個參數的值,即 getSuggestedMinimumWidth() 和 getSuggestedMinimumHeight(),一般用於系統內部的測量:

protected int getSuggestedMinimumHeight() {
    return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
}
protected int getSuggestedMinimumWidth() {
    return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}

大意是:若 View 沒有背景,值就是 View 最小的寬度或高度(對應 xml 中的 android:minWidth、android:minHeight,未指定則為 0);若有背景,則取 View 最小寬高與背景最小寬高中的較大值。

完成 measure 過程後,就能透過 getMeasuredWidth() 和 getMeasuredHeight() 取得正確的測量寬高。但需注意,某些極端情況下系統可能需要多次 measure 才能確定最終寬高,此時直接在 onMeasure() 中取得的值可能不準確,保險的做法是在 onLayout() 中獲取。

ViewGroup 的 measure 過程

ViewGroup 的 measure 過程與 View 不同,它不僅要完成自身的測量,還需遍歷所有子 View 的 measure 方法。ViewGroup 提供了一個 measureChildren() 方法:

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

它遍歷所有子 View,若子 View 沒有被 GONE 掉,就執行 measureChild():

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

它取得子 View 的 LayoutParams,透過 getChildMeasureSpec() 建立子 View 的 MeasureSpec,再傳給子 View 進行測量。

由此可見,ViewGroup 並未定義具體的測量過程,因為它是抽象類,其 onMeasure 需要由子類(如 LinearLayout、RelativeLayout)去實現。這是因為不同佈局的特性差異很大,無法統一實現。

注意事項

由於 View 的 measure 過程與 Activity 生命週期並非同步,若直接在 onCreate()、onStart()、onResume() 中取得 View 寬高,很可能取到 0。以下提供幾種解法:

方案 1:重寫 onWindowFocusChanged(),在該方法中取得寬高:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        int measuredWidth = view.getMeasuredWidth();
        int measuredHeight = view.getMeasuredHeight();
    }
}

該方法在 Activity 的 Window 獲得或失去焦點時回呼,此時 View 已初始化完畢、寬高已測量好。

方案 2:透過 post 將 Runnable 投遞到消息佇列底部:

view.post(new Runnable() {
    @Override
    public void run() {
        int measuredWidth = view.getMeasuredWidth();
        int measuredHeight = view.getMeasuredHeight();
    }
});

方案 3:透過 ViewTreeObserver 監聽 View 樹的狀態變化:

ViewTreeObserver treeObserver = view.getViewTreeObserver();
treeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        int measuredWidth = view.getMeasuredWidth();
        int measuredHeight = view.getMeasuredHeight();
    }
});

此回呼會被呼叫多次,因此應在第一次回呼中移除監聽,避免重複獲取。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved