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

Android View 繪制機制源碼分析(二):LinearLayout 如何處理 layout_weight

編輯:關於 Android 程式設計

本文承接上一篇。上一篇講了 View 的 measure 過程,這次來看 ViewGroup 的 measure。由於 ViewGroup 是抽象類,需要挑一個具體佈局來分析,這裡選最常見的 LinearLayout。若還沒讀過上一篇,建議先補一下基礎再往下看。

先從一個反直覺的現象說起:layout_weight 到底是什麼

多數人會回答:「標明這個 View 在父容器中所佔的比例。」這個說法對嗎?暫且不下結論,先看兩個例子。

示例一:layout_height 為 0dip

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="2"
        android:background="#998877"
        android:text="New" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="4"
        android:background="#334455"
        android:text="New" />
</LinearLayout>

上方 weight 為 2,下方為 4,結果上方高度恰好是下方的一半。

示例二:layout_height 改為 match_parent

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:background="#998877"
        android:text="New" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="4"
        android:background="#334455"
        android:text="New" />
</LinearLayout>

weight 仍然是 2 與 4,唯一差別是 layout_height 變成 match_parent,結果比例反過來了——上方變成了下方的兩倍。

同一組權重,兩種相反的結果。帶著這個疑問,我們進入源碼。

onMeasure:入口只有四行

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    if (mOrientation == VERTICAL) {
        measureVertical(widthMeasureSpec, heightMeasureSpec);
    } else {
        measureHorizontal(widthMeasureSpec, heightMeasureSpec);
    }
}

依方向分派到兩個方法,我們以縱向為例,分段看 measureVertical。

第一段:變量準備

void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
    mTotalLength = 0;          // 所有子 View 高度之和
    int maxWidth = 0;
    int alternativeMaxWidth = 0;
    int weightedMaxWidth = 0;
    boolean allFillParent = true;
    float totalWeight = 0;     // 所有子 View 的 weight 之和

    final int count = getVirtualChildCount();
    final int widthMode  = MeasureSpec.getMode(widthMeasureSpec);
    final int heightMode = MeasureSpec.getMode(heightMeasureSpec);

幾個關鍵變量:mTotalLength 累加子 View 高度,totalWeight 累加權重,heightMode 是父容器傳下來的測量模式。

第二段:第一輪遍歷

for (int i = 0; i < count; ++i) {
    final View child = getVirtualChildAt(i);
    if (child == null) {
        mTotalLength += measureNullChild(i);
        continue;
    }
    if (child.getVisibility() == View.GONE) {
        i += getChildrenSkipCount(child, i);
        continue;
    }

    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
    totalWeight += lp.weight;

    if (heightMode == MeasureSpec.EXACTLY && lp.height == 0 && lp.weight > 0) {
        // 父容器高度確定、子 View 高度為 0 且帶權重:
        // 這一輪先不測量,只把 margin 計入
        final int totalLength = mTotalLength;
        mTotalLength = Math.max(totalLength,
                totalLength + lp.topMargin + lp.bottomMargin);
    } else {
        int oldHeight = Integer.MIN_VALUE;
        if (lp.height == 0 && lp.weight > 0) {
            // 父容器 mode 是 UNSPECIFIED 或 AT_MOST,
            // 先把 0 換成 WRAP_CONTENT,避免測出高度為 0
            oldHeight = 0;
            lp.height = LayoutParams.WRAP_CONTENT;
        }

        measureChildBeforeLayout(child, i, widthMeasureSpec, 0,
                heightMeasureSpec, totalWeight == 0 ? mTotalLength : 0);

        if (oldHeight != Integer.MIN_VALUE) {
            lp.height = oldHeight;
        }

        final int childHeight = child.getMeasuredHeight();
        final int totalLength = mTotalLength;
        mTotalLength = Math.max(totalLength,
                totalLength + childHeight + lp.topMargin + lp.bottomMargin
                        + getNextLocationOffset(child));
        if (useLargestChild) {
            largestChildHeight = Math.max(childHeight, largestChildHeight);
        }
    }
}

這段是整個流程的核心,那個三條件的判斷式 heightMode == EXACTLY && lp.height == 0 && lp.weight > 0 就是兩個示例分岔的地方。示例一命中它(跳過測量),示例二不命中(正常測量)。

順帶留意 measureChildBeforeLayout 的最後一個參數:totalWeight == 0 ? mTotalLength : 0。也就是說,只要前面有兄弟節點設過 weight,這裡傳入的「已用高度」就是 0——這個細節會直接影響子 View 被分配到的可用空間。

void measureChildBeforeLayout(View child, int childIndex,
        int widthMeasureSpec, int totalWidth,
        int heightMeasureSpec, int totalHeight) {
    measureChildWithMargins(child, widthMeasureSpec, totalWidth,
            heightMeasureSpec, totalHeight);
}

它只是轉手呼叫父類的 measureChildWithMargins,最終仍是用父容器的 MeasureSpec 減去已用空間後,去 measure 子 View。

第三段:分配剩餘空間

int heightSize = mTotalLength;
heightSize = Math.max(heightSize, getSuggestedMinimumHeight());
heightSize = resolveSize(heightSize, heightMeasureSpec);

// 父容器實際高度與子 View 已用高度之差
int delta = heightSize - mTotalLength;

if (delta != 0 && totalWeight > 0.0f) {
    float weightSum = mWeightSum > 0.0f ? mWeightSum : totalWeight;
    mTotalLength = 0;

    for (int i = 0; i < count; ++i) {
        final View child = getVirtualChildAt(i);
        if (child.getVisibility() == View.GONE) continue;

        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
        float childExtra = lp.weight;

        if (childExtra > 0) {
            // 從 delta 中分得 (weight / weightSum) * delta,注意 delta 可能為負
            int share = (int) (childExtra * delta / weightSum);
            weightSum -= childExtra;
            delta -= share;

            final int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                    mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin,
                    lp.width);

            if ((lp.height != 0) || (heightMode != MeasureSpec.EXACTLY)) {
                // 第二輪已測量過,把 share 疊加上去重量一次
                int childHeight = child.getMeasuredHeight() + share;
                if (childHeight < 0) childHeight = 0;
                child.measure(childWidthMeasureSpec,
                        MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY));
            } else {
                // 第二輪被跳過了,這裡才是它第一次被測量
                child.measure(childWidthMeasureSpec,
                        MeasureSpec.makeMeasureSpec(share > 0 ? share : 0,
                                MeasureSpec.EXACTLY));
            }
        }
        // maxWidth / allFillParent 等統計省略
        final int totalLength = mTotalLength;
        mTotalLength = Math.max(totalLength,
                totalLength + child.getMeasuredHeight()
                        + lp.topMargin + lp.bottomMargin
                        + getNextLocationOffset(child));
    }
    mTotalLength += mPaddingTop + mPaddingBottom;
}

setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec), heightSize);

邏輯很清楚:先算出父容器能給的高度 heightSize,減去子 View 已用的 mTotalLength 得到剩餘 delta,再按權重比例把 delta 分給各子 View,重新測量一次。

回到兩個示例

示例一推演(height = 0dip,weight = 2 : 4)

第二段中,條件 heightMode == EXACTLY && lp.height == 0 && lp.weight > 0 成立,兩個 TextView 都沒有被測量,mTotalLength 保持為 0。

進入第三段,heightSize 等於螢幕高度,所以 delta = 螢幕高度 - 0 = 螢幕高度,weightSum = 6。

處理第一個 TextView:share = 螢幕高度 × (2/6),weightSum 變為 4,delta 減去 share。此時判斷式 (lp.height != 0) || (heightMode != EXACTLY) 為 false,於是走 else 分支:

child.measure(childWidthMeasureSpec,
        MeasureSpec.makeMeasureSpec(share > 0 ? share : 0, MeasureSpec.EXACTLY));

它的最終高度就是螢幕高度的 1/3。

處理第二個 TextView:此時 delta 已剩下螢幕高度的 4/6,weightSum 為 4,於是 share = delta × (4/4) = delta,也就是螢幕高度的 4/6。

結果 1 : 2,與 weight 設定一致。

示例二推演(height = match_parent,weight = 2 : 4)

第二段中條件不成立(lp.height 不為 0),走 else 分支執行 measureChildBeforeLayout。由於 totalWeight 不為 0,傳入的最後一個參數是 0,可用空間未被扣除,於是每個子 View 都被測成整整一個螢幕高——兩個都是。

因此 mTotalLength = 2 × 螢幕高度,delta = 螢幕高度 - 2×螢幕高度 = -螢幕高度,是個負數。

進入第三段,判斷式 (lp.height != 0) 成立,走 if 分支:

int childHeight = child.getMeasuredHeight() + share;   // 螢幕高度 + 負的 share
child.measure(childWidthMeasureSpec,
        MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY));

第一個 TextView 的 share = -螢幕高度 × (2/6),最終高度 = 螢幕高度 × (4/6)。同理第二個 = 螢幕高度 × (2/6)。

結果 2 : 1,與 weight 設定恰好相反。

結論:layout_weight 的正確理解

它在第二輪測量完成之後,把剩餘空間 delta 按權重比例分配給各子 View:

· 若 delta > 0(子 View 原本沒佔滿),就在原有大小上加上對應份額。
· 若 delta < 0(子 View 原本佔多了),就從原有大小中減去對應份額。

所以「weight 代表比例」這個說法只在子 View 高度為 0(或 wrap_content 且內容極小)時近似成立。一旦子 View 自己就要求了 match_parent,它先吃掉全部空間,後續分配只能做「減法」,比例自然看起來反了。

實踐建議:用 weight 做等分或按比例分割時,把 layout_height(縱向)或 layout_width(橫向)設為 0dip,讓子 View 先不佔空間,再純粹由權重決定最終尺寸。這樣行為可預測,也不會出現「改個 weight 結果反了」的困惑。另外,若各項權重之和固定,可直接設定 android:weightSum,省去源碼中回退到 totalWeight 的判斷分支。

理解了這套兩輪測量的機制,LinearLayout 的絕大多數「詭異」表現就都能解釋了——包括為什麼嵌套 LinearLayout 加 weight 容易掉效能(每個帶權重的子項都可能觸發二次 measure)。

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