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

手把手實作 LinearLayout:從 onMeasure 到 weight 的原始碼拆解

編輯:關於 Android 程式設計

前言

做了一年的 Android 應用開發,一直停留在應用層,總覺得難有新的突破。趁著最近不太忙,於是決定研究一下 Android SDK 的源碼,手動實作一些原生控制項,並把它當作一個系列來記錄。作為開篇,就從相對簡單的 LinearLayout 開始吧。

LinearLayout 對每個 Android 開發者都不陌生。本文不打算逐一講解它的每個屬性,而是聚焦在它的測量(measure)與布局(layout)部分,以及 weight 究竟是如何應用到布局中去的。我也不準備直接粘原生源碼,而是親手實作一個 LinearLayout——當然,大部分邏輯仍會參考原生源碼。

準備工作

本文適合對 View 繪製有一定了解的讀者閱讀。這裡只實作 LinearLayout 的以下功能:豎直方向上的測量與布局,以及 weight 的實現。

自訂 ViewGroup

首先自訂一個命名為 MyLinearLayout 的 ViewGroup,繼承自 ViewGroup。我們知道,一個 ViewGroup 必然對應一個 LayoutParams,於是在 MyLinearLayout 中定義一個靜態內部類 MyLinearLayoutParams,繼承自 MarginLayoutParams(因為我們要用到 margin 屬性)。

 public class MyLinearLayout extends ViewGroup { private static final String TAG = "MyLinearLayout"; //子 View 的總高度,注意,這個高度不等於布局高度 private int mTotalLength = 0; private float mWeightSum = 0; public MyLinearLayout(Context context) { super(context); } public MyLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.MyLinearLayout); mWeightSum = a.getFloat(R.styleable.MyLinearLayout_weightSum, 0); a.recycle(); } public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected LayoutParams generateDefaultLayoutParams() { return new MyLinearLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } @Override protected LayoutParams generateLayoutParams(LayoutParams p) { return new MyLinearLayoutParams(p); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MyLinearLayoutParams(getContext(), attrs); } public static class MyLinearLayoutParams extends ViewGroup.MarginLayoutParams { public float weight; public MyLinearLayoutParams(Context c, AttributeSet attrs) { super(c, attrs); TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.MyLinearLayout); weight = a.getFloat(R.styleable.MyLinearLayout_weight, 0); a.recycle(); } public MyLinearLayoutParams(int width, int height) { super(width, height); } public MyLinearLayoutParams(LayoutParams source) { super(source); } }

這裡要注意 MyLinearLayoutParams 中的 weight 變量。而 generateLayoutParams 可以理解為:為每個子 View 生成一個對應的 LayoutParams。

onMeasure:先實現不含 weight 的測量

我們先從最簡單的情況著手,暫不考慮 weight,只實現 vertical 方向的測量與布局。

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mTotalLength = 0; int childCount = getChildCount(); int maxWidth = 0; for (int i = 0; i < childCount; i++) { View child = getChildAt(i); MyLinearLayoutParams lp = (MyLinearLayoutParams) child.getLayoutParams(); if (child.getVisibility() == GONE) { i += 0; continue; } measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, mTotalLength); int totalLength = mTotalLength; mTotalLength = Math.max(totalLength, mTotalLength += (child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin)); maxWidth = Math.max(maxWidth, child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin); } maxWidth += getPaddingLeft() + getPaddingRight(); mTotalLength += (getPaddingTop() + getPaddingBottom()); int heightSize = mTotalLength; heightSize = Math.max(heightSize, getSuggestedMinimumHeight()); int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0); heightSize = heightSizeAndState & MEASURED_SIZE_MASK; setMeasuredDimension(maxWidth, heightSize); } 

這裡要重申:mTotalLength 並不是最終布局的高度,它還需要經過 resolveSizeAndState 的糾正:

public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) { final int specMode = MeasureSpec.getMode(measureSpec); final int specSize = MeasureSpec.getSize(measureSpec); final int result; switch (specMode) { case MeasureSpec.AT_MOST: if (specSize < size) { result = specSize | MEASURED_STATE_TOO_SMALL; } else { result = size; } break; case MeasureSpec.EXACTLY: result = specSize; break; case MeasureSpec.UNSPECIFIED: default: result = size; } return result | (childMeasuredState & MEASURED_STATE_MASK); }

到這一步,測量就完成了。布局部分直接看程式碼:

@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childTop = 0; int childLeft; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); MyLinearLayoutParams lp = (MyLinearLayoutParams) child.getLayoutParams(); if (child.getVisibility() == GONE) { childTop += 0; continue; } childLeft = lp.leftMargin; childTop += lp.topMargin; int childRight = child.getMeasuredWidth() + childLeft; int childBottom = childTop + 0 + child.getMeasuredHeight(); child.layout(childLeft, childTop, childRight, childBottom); childTop += lp.bottomMargin + child.getMeasuredHeight() + 0; } }

執行到這一步,就能看到一個垂直布局的效果了。

引入 weight

接下來才是重頭戲。首先要明白:LinearLayout 的 onMeasure 其實分為兩個階段——第一階段分配子 View 的真實高度(不考慮 weight),第二階段再對 weight 進行換算並重新測量帶有 weight 的 view。因此可以得出結論:如果一個 view 的 layout_height 不為 0,且 weight 有值,那麼它會被測量兩次。

@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mTotalLength = 0; int childCount = getChildCount(); int maxWidth = 0; float totalWeight = 0; boolean skippedMeasure = false; int heightMode = MeasureSpec.getMode(heightMeasureSpec); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); MyLinearLayoutParams lp = (MyLinearLayoutParams) child.getLayoutParams(); if (child.getVisibility() == GONE) { i += 0; continue; } totalWeight += lp.weight; if (heightMode == MeasureSpec.EXACTLY && lp.height == 0 && lp.weight > 0) { final int totalLength = mTotalLength; mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin); skippedMeasure = true; } else { if (lp.height == 0 && lp.weight > 0) { lp.height = LayoutParams.WRAP_CONTENT; } measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, totalWeight == 0 ? mTotalLength : 0); int totalLength = mTotalLength; mTotalLength = Math.max(totalLength, mTotalLength += (child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin)); } maxWidth = Math.max(maxWidth, child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin); } mTotalLength += (getPaddingTop() + getPaddingBottom()); int heightSize = mTotalLength; heightSize = Math.max(heightSize, getSuggestedMinimumHeight()); int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0); heightSize = heightSizeAndState & MEASURED_SIZE_MASK; //weight 測量的邏輯 int delta = heightSize - mTotalLength; if (skippedMeasure || delta > 0 && totalWeight > 0) { float weightSum = mWeightSum > 0.0f ? mWeightSum : totalWeight; mTotalLength = 0; for (int i = 0; i < childCount; i++) { final View child = getChildAt(i); if (child.getVisibility() == View.GONE) { continue; } MyLinearLayoutParams lp = (MyLinearLayoutParams) child.getLayoutParams(); float childExtra = lp.weight; if (childExtra > 0) { int share = (int) (childExtra * delta / weightSum); weightSum -= childExtra; delta -= share; final int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, getPaddingLeft() + getPaddingRight() + lp.leftMargin + lp.rightMargin, lp.width); 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)); } } final int totalLength = mTotalLength; mTotalLength = Math.max(totalLength, totalLength + child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin + 0); } } maxWidth += getPaddingLeft() + getPaddingRight(); setMeasuredDimension(maxWidth, heightSize); }

程式碼看似多,仔細讀幾遍便能理清。這裡梳理一下關鍵點:

第一次遍歷子 View 時,並非所有人都會被測量。當滿足父布局高度為精確值、子 View 高度為 0 且 weight 有值時,會跳過該 view 的測量。特別注意,當父布局高度為 wrap_content 時,若子 view 高度為 0 但 weight 有值,必須把它設為 WRAP_CONTENT,否則它的高度會變成 0。

由此可得出第一次測量的結論:若父布局高度為精確值,最終高度就是精確值;若父布局高度為 wrap_content,最終高度為所有子 View 高度之和。

接著進入第二次測量。先計算剩餘空間 delta,若父布局為 wrap_content,這裡沒有剩餘空間,也就解釋了為什麼 wrap_content 下 weight 會失效——因為根本不滿足進入 weight 計算的條件(skippedMeasure 為 true 或 delta > 0 且 totalWeight > 0)。進入 weight 計算後,邏輯就相對單純了,按 weight × 剩餘空間 ÷ weightSum 的公式換算大小即可。

總結

本文主要是對 LinearLayout 核心程式碼做個梳理。事實上其 onMeasure 還有更多細節,例如對 baseLine、divider 的處理,以及方向為 vertical 時寬度的計算也遠比範例複雜。但把主要流程疏通之後,其餘的都不是難事。

最後還是那句話:關於源碼的文章,目的不是讓你「看懂」,而是讓你把握一個大致方向,從而在自己閱讀源碼時更加得心應手。The end~!

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