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

深入剖析 LinearLayout 的源碼實現

編輯:關於 Android 程式設計

為什麼要研究源碼

自學 Android 自定義控件以來,我總有一種似懂非懂的感覺:說起來頭頭是道,也在專案裡封裝過一些自定義控件,可始終缺乏一個真正透徹的認知。於是我決定回過頭去看看,Android 究竟是如何封裝控件的。既然要入門,就從最基礎的 LinearLayout 開始,看看它到底是怎麼實現的。

什麼是 LinearLayout

作為最基礎的布局之一,做過 Android 開發的同學對它應該再熟悉不過。中文一般稱之為線性布局。相比 RelativeLayout,LinearLayout 要簡單得多——在沒有 weight 介入的情況下,它每次只需測量一遍即可,而 RelativeLayout 往往需要測量兩次。

幾個值得留意的屬性

orientation:決定子元素是縱向排列還是水平排列。

weight:權重,用來分配 LinearLayout 剩餘的空間,後文會詳細展開。

measureWithLargestChild:這個屬性比較冷門,當它被設為 true 時,所有帶 weight 的子 View 都會採用最大子 View 的最小尺寸。(至於 Android 為何要設計這個屬性,我也還沒完全想通。)

源碼分析

研究任何一個 View 類,通常都會從 measure、layout、draw 三條主線入手,順著它們的回調函數 onMeasure、onLayout、onDraw 追下去。把這三條流程摸清楚,一個控件的大致實現也就明瞭了。LinearLayout 作為 ViewGroup 的子類,主要扮演布局容器的角色,因此我們著重看它的 onMeasure 方法。

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

可以看到,onMeasure 的實現非常乾淨:它依據布局方向,把工作分派給 measureVertical 和 measureHorizontal。後面的 onLayout 與 onDraw 也是類似套路。由於橫向與縱向的內部邏輯幾乎如出一轍,這裡我只聚焦縱向的實現。

void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
    mTotalLength = 0;
    int maxWidth = 0;
    int childState = 0;
    int alternativeMaxWidth = 0;
    int weightedMaxWidth = 0;
    boolean allFillParent = true;
    float totalWeight = 0;
    final int count = getVirtualChildCount();
    final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    boolean matchWidth = false;
    boolean skippedMeasure = false;
    // ... 遍歷子 View、累計高度、處理 weight 的邏輯 ...
}

整個方法只有三百行左右,但思路格外清晰。我們順著流程一步步拆解。

先看初始化階段,這裡定義了一大堆變量,挑幾個關鍵的來看:

// 記錄容器內部累計使用的高度,注意別被字面意思誤導,它並非 LinearLayout 最終的高度
mTotalLength = 0;
// 所有子 View 權重值的總和
float totalWeight = 0;
// 子 View 數量;getVirtualChildCount() 內部其實就是調用 getChildCount(),
// 外層再包一層大概是為了讓語義更清晰易讀
final int count = getVirtualChildCount();
// 取出當前容器的寬度模式與高度模式
// 若對 MeasureSpec 的測量流程不熟悉,建議先補一補這塊知識
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);

初始化完成後,就進入遍歷子 View、逐一測量的環節:

// 取出當前子 View
final View child = getVirtualChildAt(i);
// 若子 View 為 null,跳過,繼續測量下一個
if (child == null) {
    mTotalLength += measureNullChild(i);
    continue;
}
// 若子 View 為 GONE,則不計入總高度——這裡也能看出 GONE 與 INVISIBLE 的區別
if (child.getVisibility() == View.GONE) {
    i += getChildrenSkipCount(child, i);
    continue;
}
// 若存在分割線,則把分割線高度累加進來
if (hasDividerBeforeChildAt(i)) {
    mTotalLength += mDividerHeight;
}

接著是取 LayoutParams 的關鍵一步:

// 我們常在代碼中通過 Inflater 服務動態加載布局,再設置它的 LayoutParams。
// 如果不引用父容器的 LayoutParams,就會拋出強轉異常,根源就在這一行:
// 父容器在 addView、measure 時,都會把子 View 的 LayoutParams 強轉為自己的類型
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
// 累加權重
totalWeight += lp.weight;
// 值得注意:當當前 LinearLayout 為 EXACTLY 模式,且子 View 高度為 0、權重大於 0 時,
// 這個子 View 只有在容器高度有剩餘時,才會按權重佔比去瓜分剩餘空間。
// 前文提到的「二次測量」說的就是這部分
if (heightMode == MeasureSpec.EXACTLY && lp.height == 0 && lp.weight > 0) {
    // 優化:懶得測量那些注定要吃掉剩餘空間的子 View,
    // 若後面確有剩餘空間,它們會被重新測量
    final int totalLength = mTotalLength;
    mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin);
    skippedMeasure = true;
}

如果不是上述情況,則走另一條分支:

else {
    int oldHeight = Integer.MIN_VALUE;
    if (lp.height == 0 && lp.weight > 0) {
        // 走到這一步,說明當前容器模式是 UNSPECIFIED 或 AT_MOST(EXACTLY 已在上一個判斷中攔截)。
        // 此時把子 View 高度臨時設為 WRAP_CONTENT(-1),避免它最終拿到 0 高度
        oldHeight = 0;
        lp.height = LayoutParams.WRAP_CONTENT;
    }
    // 開始測算子 View。若當前容器不是 EXACTLY 模式,且子 View 的 weight 大於 0,
    // 則優先把容器的全部可用高度用於該子 View 的測量
    measureChildBeforeLayout(
            child, i, widthMeasureSpec, 0, heightMeasureSpec,
            totalWeight == 0 ? mTotalLength : 0);
    // 恢復子 View 原始高度
    if (oldHeight != Integer.MIN_VALUE) {
        lp.height = oldHeight;
    }
    final int childHeight = child.getMeasuredHeight();
    final int totalLength = mTotalLength;
    // 疊加子 View 的 margin 後更新累計高度
    mTotalLength = Math.max(totalLength,
            totalLength + childHeight + lp.topMargin + lp.bottomMargin + getNextLocationOffset(child));
    if (useLargestChild) {
        largestChildHeight = Math.max(childHeight, largestChildHeight);
    }
}

再往裡鑽一層,看看 measureChildBeforeLayout 的實現:

// totalWeight == 0 ? mTotalLength : 0 決定了是否把全部可用高度交給子 View
void measureChildBeforeLayout(View child, int childIndex,
        int widthMeasureSpec, int totalWidth,
        int heightMeasureSpec, int totalHeight) {
    measureChildWithMargins(child, widthMeasureSpec, totalWidth, heightMeasureSpec, totalHeight);
}

protected void measureChildWithMargins(View child,
        int parentWidthMeasureSpec, int widthUsed,
        int parentHeightMeasureSpec, int heightUsed) {
    final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
    // 這裡與普通 ViewGroup 的實現一致:由子 View 的 LayoutParams 與父容器的 MeasureSpec 共同決定子 View 尺寸
    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);
}

子 View 測量完畢後,把 padding 高度補上,再與最小高度做比對:

// 加上 padding
mTotalLength += mPaddingTop + mPaddingBottom;
int heightSize = mTotalLength;
// 若設置了 minimumHeight,取當前高度與最小高度中的較大值
heightSize = Math.max(heightSize, getSuggestedMinimumHeight());
// 將計算出的尺寸與 heightMeasureSpec 進行調和
int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0);
heightSize = heightSizeAndState & MEASURED_SIZE_MASK;
// 若此前跳過了某些子 View 的測量,或存在剩餘空間需要分配,則在此處補測
int delta = heightSize - mTotalLength;
if (skippedMeasure || delta != 0 && totalWeight > 0.0f) {
    // 若手動設定了 weightSum 就用它,否則採用所有子 View 的權重總和
    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) {
            // 子 View 的權重佔比 × 剩餘高度
            int share = (int) (childExtra * delta / weightSum);
            weightSum -= childExtra;
            delta -= share;
            final int childWidthMeasureSpec = getChildMeasureSpec(
                    widthMeasureSpec,
                    mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin,
                    lp.width);
            // EXACTLY 模式下該子 View 此前被跳過,需要在此首次測量;
            // 非 EXACTLY 模式則在第一次循環中已測量過,這裡在原有高度上叠加 share
            if ((lp.height != 0) || (heightMode != MeasureSpec.EXACTLY)) {
                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、mTotalLength 等 ...
        }
    }
    mTotalLength += mPaddingTop + mPaddingBottom;
}

以上就是 onMeasure 的主幹分析。歸納兩個重點:

1. 帶 weight 且高度為 0 的子 View,在 EXACTLY 模式下優先級最低——一旦容器剩餘空間不足,它甚至可能完全不顯示;而在 AT_MOST 模式下,同樣條件的子 View 反而會優先拿到高度。

2. 為 LinearLayout 動態添加子 View 時,子 View 的 LayoutParams 必須是 LinearLayout 的內部類(這一點適用於所有 ViewGroup 子類)。

動手舉個例子

源碼解析终究是我們根據代碼的推論,配上幾個 demo 跑一跑,理解會深刻得多。

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

    <TextView
        android:background="@android:color/holo_orange_dark"
        android:layout_height="300dp"
        android:layout_weight="2"
        android:layout_width="match_parent" />

    <TextView
        android:background="@android:color/holo_blue_dark"
        android:layout_height="fill_parent"
        android:layout_width="match_parent" />

</LinearLayout>

先別急著往下看,試著預測一下結果。

假設屏幕高度為 1000dp:

父容器 LinearLayout 是 EXACTLY 模式,而 TextView1 自身高度為 300dp,因此會進入第一次測量,拿到 300dp 的高度。接著 TextView2 因為是 match_parent,會拿到 1000dp。由於存在帶 weight 的子 View,於是進入第二次測量:

delta = heightSize - mTotalLength = 1000 - 1300 = -300

share = 2.0 × (-300) / 2.0 = -300

由於 share 為負,makeMeasureSpec 時會取 0,所以最終 TextView1 的高度變成 0,根本不會顯示在屏幕上,整個屏幕會被 TextView2 填滿。

不信的話,可以自己動手試一試。

好了,LinearLayout 的測量過程就聊到這裡。剩下的 onLayout() 與 onDraw() 相對簡單,感興趣的同學不妨自己翻閱源碼體會一番。

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