編輯:關於 Android 程式設計
本文承接上一篇。上一篇講了 View 的 measure 過程,這次來看 ViewGroup 的 measure。由於 ViewGroup 是抽象類,需要挑一個具體佈局來分析,這裡選最常見的 LinearLayout。若還沒讀過上一篇,建議先補一下基礎再往下看。
多數人會回答:「標明這個 View 在父容器中所佔的比例。」這個說法對嗎?暫且不下結論,先看兩個例子。
<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,結果上方高度恰好是下方的一半。
<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,結果比例反過來了——上方變成了下方的兩倍。
同一組權重,兩種相反的結果。帶著這個疑問,我們進入源碼。
@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,重新測量一次。
第二段中,條件 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 設定一致。
第二段中條件不成立(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 設定恰好相反。
它在第二輪測量完成之後,把剩餘空間 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)。
用 HttpClient 實作手機號碼歸屬地查詢:Android 網路請求完整範例
資料來源 https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx 該服務除了 HTTP GET/PO
Android Service 完全解析:從啟動模式到 AIDL 跨進程通訊
一、先認清 Service 的真面目 很多初學者會把 Service 和 Thread 混為一談,這是個常見誤解。Service 與 Activity 一樣,預設都跑在應
Android 官方文檔翻譯:Lint 靜態代碼檢查完整指南
Lint 是什麼 Android Lint 是 ADT 16(以及 Tools 16)引入的檢查工具,用來掃描 Android 專案源碼中潛在的 bug。它既可以作為命
Android系統定制之路(初識MTK):藍牙名稱、WiFi熱點、通知彈窗與休眠選項
今天接到一個客戶的新訂單需求,總共有40多項,先記錄其中幾個較典型的系統定制項目:修改系統藍牙名稱、WiFi熱點名稱、通知彈窗預設值,以及在休眠選項中新增「永不休眠」。以